From 26b489d130085844c7b08889d17cd2151b9e1798 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 24 Sep 2022 23:13:54 -0500 Subject: [PATCH 01/42] Initial commit --- .gitattributes | 2 + .gitignore | 398 +++++++++++++++++++++++++++++ LICENSE | 674 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 1074 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 LICENSE diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..426d76d --- /dev/null +++ b/.gitignore @@ -0,0 +1,398 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e62ec04 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ +GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. From db5d7d91a78038eebfba7e72c8021d1b8cca4b41 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 24 Sep 2022 23:18:31 -0500 Subject: [PATCH 02/42] initial shitshow works sometimes desktop to vr is reliable enough.. vr to desktop is struggling cannot get steamvr to let go of chillout after loading openvr device : think : --- DesktopVRSwitch/DesktopVRSwitch.csproj | 61 +++++++ DesktopVRSwitch/DesktopVRSwitch.sln | 25 +++ DesktopVRSwitch/Main.cs | 181 +++++++++++++++++++++ DesktopVRSwitch/Properties/AssemblyInfo.cs | 30 ++++ 4 files changed, 297 insertions(+) create mode 100644 DesktopVRSwitch/DesktopVRSwitch.csproj create mode 100644 DesktopVRSwitch/DesktopVRSwitch.sln create mode 100644 DesktopVRSwitch/Main.cs create mode 100644 DesktopVRSwitch/Properties/AssemblyInfo.cs diff --git a/DesktopVRSwitch/DesktopVRSwitch.csproj b/DesktopVRSwitch/DesktopVRSwitch.csproj new file mode 100644 index 0000000..2251ad3 --- /dev/null +++ b/DesktopVRSwitch/DesktopVRSwitch.csproj @@ -0,0 +1,61 @@ + + + + + net472 + enable + latest + false + + + + + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\MelonLoader\0Harmony.dll + + + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Assembly-CSharp.dll + + + ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Assembly-CSharp-firstpass.dll + + + ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\cohtml.Net.dll + + + ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Cohtml.Runtime.dll + + + ..\..\Giamoz\Giamoz\bin\Debug\net472\Giamoz.dll + + + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\MelonLoader\MelonLoader.dll + + + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\SteamVR.dll + + + ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.AnimationModule.dll + + + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.CoreModule.dll + + + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.InputLegacyModule.dll + + + ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.PhysicsModule.dll + + + ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.VRModule.dll + + + ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.XRModule.dll + + + + + + + + + diff --git a/DesktopVRSwitch/DesktopVRSwitch.sln b/DesktopVRSwitch/DesktopVRSwitch.sln new file mode 100644 index 0000000..758488c --- /dev/null +++ b/DesktopVRSwitch/DesktopVRSwitch.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32630.192 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DesktopVRSwitch", "DesktopVRSwitch.csproj", "{4008E6D1-32F9-449B-8820-80ACF0ED8233}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4008E6D1-32F9-449B-8820-80ACF0ED8233}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4008E6D1-32F9-449B-8820-80ACF0ED8233}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4008E6D1-32F9-449B-8820-80ACF0ED8233}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4008E6D1-32F9-449B-8820-80ACF0ED8233}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {3C86465A-87F5-49EF-915C-5B5F568A8815} + EndGlobalSection +EndGlobal diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs new file mode 100644 index 0000000..548df04 --- /dev/null +++ b/DesktopVRSwitch/Main.cs @@ -0,0 +1,181 @@ +using HarmonyLib; +using MelonLoader; +using UnityEngine; +using RootMotion.FinalIK; +using ABI_RC.Core.Player; +using ABI_RC.Core.Savior; +using ABI.CCK.Components; +using ABI_RC.Core.InteractionSystem; +using ABI_RC.Systems.MovementSystem; +using ABI_RC.Core.UI; +using System.Reflection; +using cohtml; +using ABI_RC.Core.IO; +using System.Collections; +using System; +using UnityEngine.XR; +using Valve.VR; + +namespace DesktopVRSwitch; + +public class DesktopVRSwitch : MelonMod +{ + + private static MelonPreferences_Category m_categoryDesktopVRSwitch; + private static MelonPreferences_Entry m_entryEnabled; + + private static System.Object melon; + + public override void OnApplicationStart() + { + m_categoryDesktopVRSwitch = MelonPreferences.CreateCategory(nameof(DesktopVRSwitch)); + m_entryEnabled = m_categoryDesktopVRSwitch.CreateEntry("Start SteamVR", false, description: "Launch SteamVR"); + m_entryEnabled.OnValueChangedUntyped += UpdateSettings; + } + private static void UpdateSettings() + { + melon = MelonCoroutines.Start(AttemptPlatformSwitch()); + } + + static IEnumerator AttemptPlatformSwitch() + { + if (MetaPort.Instance.isUsingVr) + { + //close the UI cause cohtml can get grumpy + ViewManager.Instance.UiStateToggle(false); + CVR_MenuManager.Instance.ToggleQuickMenu(false); + MelonLogger.Msg("Closed ChilloutVR UI."); + + MetaPort.Instance.isUsingVr = false; + MelonLogger.Msg("Set MetaPort isUsingVr to false."); + + SteamVR_Behaviour.instance.enabled = false; + SteamVR_Render.instance.enabled = false; + + yield return new WaitForEndOfFrame(); + + PlayerSetup.Instance._inVr = false; + PlayerSetup.Instance.Invoke("CalibrateAvatar", 0f); + MelonLogger.Msg("Invoked CalibrateAvatar() on PlayerSetup.Instance."); + PlayerSetup.Instance.desktopCameraRig.SetActive(true); + PlayerSetup.Instance.vrCameraRig.SetActive(false); + CohtmlHud.Instance.gameObject.transform.parent = PlayerSetup.Instance.desktopCamera.transform; + MelonLogger.Msg("Enabled Desktop camera rig."); + MelonLogger.Msg("Set PlayerSetup _inVr to false."); + + yield return new WaitForEndOfFrame(); + + MovementSystem.Instance.isVr = false; + MelonLogger.Msg("Set MovementSystem isVr to false."); + //CVR_MovementSystem.Instance.isVr = true; + //MelonLogger.Msg("Set CVR_MovementSystem isVR to false."); + + yield return new WaitForSeconds(0.5f); + + CVRInputManager.Instance.reload = true; + //CVRInputManager.Instance.inputEnabled = true; + //CVRInputManager.Instance.blockedByUi = false; + //CVRInputManager.Instance.independentHeadToggle = false; + //MelonLogger.Msg("Set CVRInputManager reload to true. Input should reload next frame..."); + + yield return new WaitForSeconds(1f); + + CVRInputManager.Instance.reload = true; + + yield return new WaitForSeconds(0.5f); + + XRSettings.enabled = false; + + PlayerSetup.Instance.Invoke("CalibrateAvatar", 0f); + MelonLogger.Msg("Invoked CalibrateAvatar() on PlayerSetup.Instance."); + //ViewManager.Instance.VrInputChanged(true); + } + else + { + //close the UI cause cohtml can get grumpy + ViewManager.Instance.UiStateToggle(false); + CVR_MenuManager.Instance.ToggleQuickMenu(false); + MelonLogger.Msg("Closed ChilloutVR UI."); + + MelonCoroutines.Start(LoadDevice("OpenVR")); + MelonLogger.Msg("OpenVR device loaded!"); + + yield return new WaitForSeconds(3); + + MelonLogger.Msg("Set MetaPort isUsingVr to true."); + MetaPort.Instance.isUsingVr = true; + + yield return new WaitForEndOfFrame(); + + VRIK ik = (VRIK)PlayerSetup.Instance._avatar.GetComponent(typeof(VRIK)); + if (ik == null) + { + ik = PlayerSetup.Instance._avatar.AddComponent(); + } + ik.solver.IKPositionWeight = 0f; + ik.enabled = false; + + PlayerSetup.Instance._inVr = true; + PlayerSetup.Instance.Invoke("CalibrateAvatar", 0f); + MelonLogger.Msg("Invoked CalibrateAvatar() on PlayerSetup.Instance."); + PlayerSetup.Instance.desktopCameraRig.SetActive(false); + PlayerSetup.Instance.vrCameraRig.SetActive(true); + CohtmlHud.Instance.gameObject.transform.parent = PlayerSetup.Instance.vrCamera.transform; + MelonLogger.Msg("Disabled Desktop camera rig."); + MelonLogger.Msg("Set PlayerSetup _inVr to true."); + + yield return new WaitForEndOfFrame(); + + MovementSystem.Instance.isVr = true; + MelonLogger.Msg("Set MovementSystem isVr to false."); + //CVR_MovementSystem.Instance.isVr = true; + //MelonLogger.Msg("Set CVR_MovementSystem isVR to false."); + + yield return new WaitForSeconds(0.5f); + + CVRInputManager.Instance.reload = true; + //CVRInputManager.Instance.inputEnabled = true; + //CVRInputManager.Instance.blockedByUi = false; + //CVRInputManager.Instance.independentHeadToggle = false; + //MelonLogger.Msg("Set CVRInputManager reload to true. Input should reload next frame..."); + + yield return new WaitForSeconds(1f); + + CVRInputManager.Instance.reload = true; + + //PlayerSetup.Instance.Invoke("CalibrateAvatar", 0f); + //MelonLogger.Msg("Invoked CalibrateAvatar() on PlayerSetup.Instance."); + + //ViewManager.Instance.VrInputChanged(true); + } + + yield return null; + } + + static IEnumerator LoadDevice(string newDevice) + { + if (String.Compare(XRSettings.loadedDeviceName, newDevice, true) != 0) + { + XRSettings.LoadDeviceByName(newDevice); + yield return null; + XRSettings.enabled = true; + if (SteamVR_Behaviour.instance.enabled == false) + { + SteamVR_Behaviour.instance.enabled = true; + SteamVR_Render.instance.enabled = true; + } + } + else + { + MelonLogger.Msg("OpenVR device already loaded!"); + MelonCoroutines.Stop(melon); + yield return null; + XRSettings.enabled = true; + if (SteamVR_Behaviour.instance.enabled == false) + { + SteamVR_Behaviour.instance.enabled = true; + SteamVR_Render.instance.enabled = true; + } + } + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Properties/AssemblyInfo.cs b/DesktopVRSwitch/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..8ff8fcf --- /dev/null +++ b/DesktopVRSwitch/Properties/AssemblyInfo.cs @@ -0,0 +1,30 @@ +using MelonLoader; +using DesktopVRSwitch.Properties; +using System.Reflection; + + +[assembly: AssemblyVersion(AssemblyInfoParams.Version)] +[assembly: AssemblyFileVersion(AssemblyInfoParams.Version)] +[assembly: AssemblyInformationalVersion(AssemblyInfoParams.Version)] +[assembly: AssemblyTitle(nameof(DesktopVRSwitch))] +[assembly: AssemblyCompany(AssemblyInfoParams.Author)] +[assembly: AssemblyProduct(nameof(DesktopVRSwitch))] + +[assembly: MelonInfo( + typeof(DesktopVRSwitch.DesktopVRSwitch), + nameof(DesktopVRSwitch), + AssemblyInfoParams.Version, + AssemblyInfoParams.Author, + downloadLink: "https://github.com/NotAKidOnSteam/DesktopVRSwitch" +)] + +[assembly: MelonGame("Alpha Blend Interactive", "ChilloutVR")] +[assembly: MelonPlatform(MelonPlatformAttribute.CompatiblePlatforms.WINDOWS_X64)] +[assembly: MelonPlatformDomain(MelonPlatformDomainAttribute.CompatibleDomains.MONO)] + +namespace DesktopVRSwitch.Properties; +internal static class AssemblyInfoParams +{ + public const string Version = "1.0.0"; + public const string Author = "NotAKidoS"; +} \ No newline at end of file From 144619837791b99011e8c099b156d42643e9e4c2 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 24 Sep 2022 23:20:55 -0500 Subject: [PATCH 03/42] Create README.md --- README.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..b1eafd4 --- /dev/null +++ b/README.md @@ -0,0 +1,34 @@ +# DesktopVRSwitch +kinda shit test to see how resilient the game is when switching between Desktop and VR during runtime + +Desktop to VR works enough +VR to Desktop does not close SteamVR and sometimes just refuses to work + +Sometimes all input just dies. Seems to be CVR issue, or maybe I have to manually reload all CoHTML myself..? + +Hud is not repositioned properly to fit the new camera. + +--- + +Here is the block of text where I tell you this mod is not affiliated or endorsed by ABI. +https://documentation.abinteractive.net/official/legal/tos/#7-modding-our-games + +> I am not affiliated with ABI in any official capacity, these mods are not endorsed or outright permitted by ABI and are subject to scrutiny. + +> Neither I nor these mods are in any way affiliated with Alpha Blend Interactive and/or ChilloutVR. Using these modifications might cause issues with the performance, security or stability of the game. Use at your own risk. + +> Any modifications that are not approved can get your ABI account terminated and such this modification is following the "modding guidelines" at the best it could be. +> They reserve the right to punish users using my mod. +> If you are scared of using modifications in your game do not install mods. + +> I do not affiliate ABI and the mod is not supported by ABI. + +> Me and this modification are in no affiliation with ABI and not supported by ABI. + +> This mod is not affiliated with Alpha Blend Interactive. The mod comes with no warranty. Use at your own risk, as I am not responsible for any misuse. + +> I'm not affiliated with Alpha Blend Interactive and this mod is not officially supported by the game. + +> When releasing mods to the public, it is required to state, that the mod authors and modification are in no affiliation with ABI and not supported by ABI. :trollface: + +> i ran out of places to steal disclaimers from From b5495e79475cdb520a886c4b6d856d128032a224 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 24 Sep 2022 23:32:23 -0500 Subject: [PATCH 04/42] Update README.md --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index b1eafd4..40e104b 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,7 @@ kinda shit test to see how resilient the game is when switching between Desktop Desktop to VR works enough VR to Desktop does not close SteamVR and sometimes just refuses to work -Sometimes all input just dies. Seems to be CVR issue, or maybe I have to manually reload all CoHTML myself..? - -Hud is not repositioned properly to fit the new camera. +https://user-images.githubusercontent.com/37721153/192128515-5630f47b-63ed-45c5-b0eb-0aac46d23731.mp4 --- From 35ee44bdb1a02bb2aeb5de67062e727f777afa0b Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 24 Sep 2022 23:34:25 -0500 Subject: [PATCH 05/42] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 40e104b..8707f5f 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ kinda shit test to see how resilient the game is when switching between Desktop and VR during runtime Desktop to VR works enough + VR to Desktop does not close SteamVR and sometimes just refuses to work https://user-images.githubusercontent.com/37721153/192128515-5630f47b-63ed-45c5-b0eb-0aac46d23731.mp4 From 500622967ea778116652c730cbb086482f58bd84 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sun, 25 Sep 2022 00:20:46 -0500 Subject: [PATCH 06/42] fixed desktop and calibrate..? --- DesktopVRSwitch/Main.cs | 38 ++++++++++++++++--------------------- DesktopVRSwitch/format.json | 23 ++++++++++++++++++++++ 2 files changed, 39 insertions(+), 22 deletions(-) create mode 100644 DesktopVRSwitch/format.json diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index 548df04..fe0b386 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -70,25 +70,21 @@ public class DesktopVRSwitch : MelonMod //CVR_MovementSystem.Instance.isVr = true; //MelonLogger.Msg("Set CVR_MovementSystem isVR to false."); - yield return new WaitForSeconds(0.5f); + yield return new WaitForSeconds(1); + CVRInputManager.Instance.reload = true; - //CVRInputManager.Instance.inputEnabled = true; - //CVRInputManager.Instance.blockedByUi = false; - //CVRInputManager.Instance.independentHeadToggle = false; - //MelonLogger.Msg("Set CVRInputManager reload to true. Input should reload next frame..."); + CVRInputManager.Instance.inputEnabled = true; + CVRInputManager.Instance.blockedByUi = false; + CVRInputManager.Instance.independentHeadToggle = false; + MelonLogger.Msg("Set CVRInputManager reload to true. Input should reload next frame..."); - yield return new WaitForSeconds(1f); - - CVRInputManager.Instance.reload = true; - - yield return new WaitForSeconds(0.5f); + yield return new WaitForSeconds(1); XRSettings.enabled = false; - PlayerSetup.Instance.Invoke("CalibrateAvatar", 0f); - MelonLogger.Msg("Invoked CalibrateAvatar() on PlayerSetup.Instance."); - //ViewManager.Instance.VrInputChanged(true); + PlayerSetup.Instance.ReCalibrateAvatar(); + MelonLogger.Msg("Called ReCalibrateAvatar() on PlayerSetup.Instance."); } else { @@ -131,22 +127,20 @@ public class DesktopVRSwitch : MelonMod //CVR_MovementSystem.Instance.isVr = true; //MelonLogger.Msg("Set CVR_MovementSystem isVR to false."); - yield return new WaitForSeconds(0.5f); + yield return new WaitForSeconds(1); CVRInputManager.Instance.reload = true; - //CVRInputManager.Instance.inputEnabled = true; - //CVRInputManager.Instance.blockedByUi = false; - //CVRInputManager.Instance.independentHeadToggle = false; - //MelonLogger.Msg("Set CVRInputManager reload to true. Input should reload next frame..."); + CVRInputManager.Instance.inputEnabled = true; + CVRInputManager.Instance.blockedByUi = false; + CVRInputManager.Instance.independentHeadToggle = false; + MelonLogger.Msg("Set CVRInputManager reload to true. Input should reload next frame..."); yield return new WaitForSeconds(1f); CVRInputManager.Instance.reload = true; - //PlayerSetup.Instance.Invoke("CalibrateAvatar", 0f); - //MelonLogger.Msg("Invoked CalibrateAvatar() on PlayerSetup.Instance."); - - //ViewManager.Instance.VrInputChanged(true); + PlayerSetup.Instance.ReCalibrateAvatar(); + MelonLogger.Msg("Called ReCalibrateAvatar() on PlayerSetup.Instance."); } yield return null; diff --git a/DesktopVRSwitch/format.json b/DesktopVRSwitch/format.json new file mode 100644 index 0000000..cca5e49 --- /dev/null +++ b/DesktopVRSwitch/format.json @@ -0,0 +1,23 @@ +{ + "_id": 95, + "name": "DesktopVRSwitch", + "modversion": "1.1.0", + "gameversion": "2022r168", + "loaderversion": "0.5.4", + "modtype": "Mod", + "author": "NotAKidoS", + "description": "Corrects MM and QM position when avatar is scaled.\nAdditional option to scale player collision.", + "searchtags": [ + "menu", + "scale", + "avatarscale", + "slider" + ], + "requirements": [ + "None" + ], + "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/r2/DesktopVRSwitch.dll", + "sourcelink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/", + "changelog": "Added option to scale player collision. Fixed some VR specific issues.", + "embedcolor": "804221" +} \ No newline at end of file From f85070cd4efceb53a80522e9b202ff26588e1918 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sun, 25 Sep 2022 04:56:19 -0500 Subject: [PATCH 07/42] fixed all but vr hud --- DesktopVRSwitch/Main.cs | 318 +++++++++++++-------- DesktopVRSwitch/Properties/AssemblyInfo.cs | 4 +- 2 files changed, 195 insertions(+), 127 deletions(-) diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index fe0b386..01018a6 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -1,18 +1,12 @@ -using HarmonyLib; -using MelonLoader; -using UnityEngine; -using RootMotion.FinalIK; +using ABI_RC.Core.InteractionSystem; using ABI_RC.Core.Player; using ABI_RC.Core.Savior; -using ABI.CCK.Components; -using ABI_RC.Core.InteractionSystem; -using ABI_RC.Systems.MovementSystem; using ABI_RC.Core.UI; -using System.Reflection; -using cohtml; -using ABI_RC.Core.IO; +using ABI_RC.Systems.MovementSystem; +using MelonLoader; +using RootMotion.FinalIK; using System.Collections; -using System; +using UnityEngine; using UnityEngine.XR; using Valve.VR; @@ -20,89 +14,160 @@ namespace DesktopVRSwitch; public class DesktopVRSwitch : MelonMod { - - private static MelonPreferences_Category m_categoryDesktopVRSwitch; - private static MelonPreferences_Entry m_entryEnabled; - private static System.Object melon; + private static bool isAttemptingSwitch = false; - public override void OnApplicationStart() + public override void OnUpdate() { - m_categoryDesktopVRSwitch = MelonPreferences.CreateCategory(nameof(DesktopVRSwitch)); - m_entryEnabled = m_categoryDesktopVRSwitch.CreateEntry("Start SteamVR", false, description: "Launch SteamVR"); - m_entryEnabled.OnValueChangedUntyped += UpdateSettings; - } - private static void UpdateSettings() - { - melon = MelonCoroutines.Start(AttemptPlatformSwitch()); - } - - static IEnumerator AttemptPlatformSwitch() - { - if (MetaPort.Instance.isUsingVr) + // assuming CVRInputManager.switchMode button was originally for desktop/vr switching before being left to do literally nothing in rootlogic + if (Input.GetKeyDown(KeyCode.F6) && (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && !isAttemptingSwitch) { - //close the UI cause cohtml can get grumpy - ViewManager.Instance.UiStateToggle(false); - CVR_MenuManager.Instance.ToggleQuickMenu(false); - MelonLogger.Msg("Closed ChilloutVR UI."); + isAttemptingSwitch = true; + melon = MelonCoroutines.Start(AttemptPlatformSwitch()); + } + } - MetaPort.Instance.isUsingVr = false; - MelonLogger.Msg("Set MetaPort isUsingVr to false."); + private static IEnumerator AttemptPlatformSwitch() + { + bool toVR = !MetaPort.Instance.isUsingVr; - SteamVR_Behaviour.instance.enabled = false; - SteamVR_Render.instance.enabled = false; + //load SteamVR/OpenVR if entering VR + MelonCoroutines.Start(LoadDevice("OpenVR", toVR)); - yield return new WaitForEndOfFrame(); + //we need to wait a frame or meet doom :shock: :shock: :stare: + //we are waiting a frame in LoadDevice after LoadDeviceByName() + yield return new WaitForEndOfFrame(); - PlayerSetup.Instance._inVr = false; - PlayerSetup.Instance.Invoke("CalibrateAvatar", 0f); - MelonLogger.Msg("Invoked CalibrateAvatar() on PlayerSetup.Instance."); - PlayerSetup.Instance.desktopCameraRig.SetActive(true); - PlayerSetup.Instance.vrCameraRig.SetActive(false); - CohtmlHud.Instance.gameObject.transform.parent = PlayerSetup.Instance.desktopCamera.transform; - MelonLogger.Msg("Enabled Desktop camera rig."); - MelonLogger.Msg("Set PlayerSetup _inVr to false."); + CloseMenuElements(); - yield return new WaitForEndOfFrame(); + yield return new WaitForEndOfFrame(); - MovementSystem.Instance.isVr = false; - MelonLogger.Msg("Set MovementSystem isVr to false."); - //CVR_MovementSystem.Instance.isVr = true; - //MelonLogger.Msg("Set CVR_MovementSystem isVR to false."); + SetMetaPort(toVR); - yield return new WaitForSeconds(1); + yield return new WaitForEndOfFrame(); + SetPlayerSetup(toVR); - CVRInputManager.Instance.reload = true; - CVRInputManager.Instance.inputEnabled = true; - CVRInputManager.Instance.blockedByUi = false; - CVRInputManager.Instance.independentHeadToggle = false; - MelonLogger.Msg("Set CVRInputManager reload to true. Input should reload next frame..."); + yield return new WaitForEndOfFrame(); - yield return new WaitForSeconds(1); + SetMovementSystem(toVR); - XRSettings.enabled = false; + yield return new WaitForEndOfFrame(); - PlayerSetup.Instance.ReCalibrateAvatar(); - MelonLogger.Msg("Called ReCalibrateAvatar() on PlayerSetup.Instance."); + SetSteamVRInstances(toVR); + + yield return new WaitForEndOfFrame(); + + ReloadCVRInputManager(); + + //some menus have 0.5s wait(), so to be safe + yield return new WaitForSeconds(1f); + + Recalibrate(); + + yield return null; + isAttemptingSwitch = false; + } + private static IEnumerator LoadDevice(string newDevice, bool isVR) + { + if (isVR) + { + if (String.Compare(XRSettings.loadedDeviceName, newDevice, true) != 0) + { + XRSettings.LoadDeviceByName(newDevice); + yield return null; + XRSettings.enabled = true; + SteamVR.settings.pauseGameWhenDashboardVisible = false; + if (SteamVR_Behaviour.instance.enabled == false) + { + SteamVR_Behaviour.instance.enabled = true; + SteamVR_Render.instance.enabled = true; + } + } + else + { + MelonLogger.Msg("OpenVR device already loaded!"); + MelonCoroutines.Stop(melon); + yield return null; + XRSettings.enabled = true; + if (SteamVR_Behaviour.instance.enabled == false) + { + SteamVR_Behaviour.instance.enabled = true; + SteamVR_Render.instance.enabled = true; + } + isAttemptingSwitch = false; + } } else { - //close the UI cause cohtml can get grumpy - ViewManager.Instance.UiStateToggle(false); - CVR_MenuManager.Instance.ToggleQuickMenu(false); - MelonLogger.Msg("Closed ChilloutVR UI."); - - MelonCoroutines.Start(LoadDevice("OpenVR")); - MelonLogger.Msg("OpenVR device loaded!"); - - yield return new WaitForSeconds(3); - - MelonLogger.Msg("Set MetaPort isUsingVr to true."); - MetaPort.Instance.isUsingVr = true; - + //holyfuck that was a lot of trial and error + SteamVR.enabled = false; yield return new WaitForEndOfFrame(); + XRSettings.LoadDeviceByName("None"); + yield return null; + } + } + // shouldn't be that important, right? + private static void CloseMenuElements() + { + if (ViewManager.Instance != null) + { + MelonLogger.Msg("Closed MainMenu Instance."); + ViewManager.Instance.UiStateToggle(false); + } + else + { + MelonLogger.Msg("MainMenu Instance not found!!!"); + } + if (ViewManager.Instance != null) + { + MelonLogger.Msg("Closed QuickMenu Instance."); + CVR_MenuManager.Instance.ToggleQuickMenu(false); + } + else + { + MelonLogger.Msg("QuickMenu Instance not found!!!"); + } + } + + private static void SetMetaPort(bool isVR) + { + if (MetaPort.Instance == null) + { + MelonLogger.Msg("MetaPort Instance not found!!!"); + return; + } + MelonLogger.Msg($"Set MetaPort isUsingVr to {isVR}."); + MetaPort.Instance.isUsingVr = isVR; + } + + //uh huh + private static void SetSteamVRInstances(bool isVR) + { + if (SteamVR_Behaviour.instance == null) + { + MelonLogger.Msg("SteamVR Instances not found!!!"); + return; + } + MelonLogger.Msg($"Set SteamVR monobehavior instances to {isVR}."); + SteamVR_Behaviour.instance.enabled = isVR; + SteamVR_Render.instance.enabled = isVR; + //set again just in case on desktop & disabling + XRSettings.enabled = isVR; + } + + private static void SetPlayerSetup(bool isVR) + { + if (PlayerSetup.Instance == null) + { + MelonLogger.Msg("PlayerSetup Instance not found!!!"); + return; + } + + if (isVR) + { + MelonLogger.Msg("Creating temp VRIK component."); VRIK ik = (VRIK)PlayerSetup.Instance._avatar.GetComponent(typeof(VRIK)); if (ik == null) { @@ -110,66 +175,69 @@ public class DesktopVRSwitch : MelonMod } ik.solver.IKPositionWeight = 0f; ik.enabled = false; - - PlayerSetup.Instance._inVr = true; - PlayerSetup.Instance.Invoke("CalibrateAvatar", 0f); - MelonLogger.Msg("Invoked CalibrateAvatar() on PlayerSetup.Instance."); - PlayerSetup.Instance.desktopCameraRig.SetActive(false); - PlayerSetup.Instance.vrCameraRig.SetActive(true); - CohtmlHud.Instance.gameObject.transform.parent = PlayerSetup.Instance.vrCamera.transform; - MelonLogger.Msg("Disabled Desktop camera rig."); - MelonLogger.Msg("Set PlayerSetup _inVr to true."); - - yield return new WaitForEndOfFrame(); - - MovementSystem.Instance.isVr = true; - MelonLogger.Msg("Set MovementSystem isVr to false."); - //CVR_MovementSystem.Instance.isVr = true; - //MelonLogger.Msg("Set CVR_MovementSystem isVR to false."); - - yield return new WaitForSeconds(1); - - CVRInputManager.Instance.reload = true; - CVRInputManager.Instance.inputEnabled = true; - CVRInputManager.Instance.blockedByUi = false; - CVRInputManager.Instance.independentHeadToggle = false; - MelonLogger.Msg("Set CVRInputManager reload to true. Input should reload next frame..."); - - yield return new WaitForSeconds(1f); - - CVRInputManager.Instance.reload = true; - - PlayerSetup.Instance.ReCalibrateAvatar(); - MelonLogger.Msg("Called ReCalibrateAvatar() on PlayerSetup.Instance."); } - yield return null; + MelonLogger.Msg($"Set PlayerSetup instance to {isVR}."); + PlayerSetup.Instance._inVr = isVR; + + //we invoke calibrate to get VRIK and calibrator instance set up, faster than full recalibrate + MelonLogger.Msg("Called CalibrateAvatar() on PlayerSetup.Instance. Expect a few errors from PlayerSetup Update() and LateUpdate()."); + PlayerSetup.Instance.CalibrateAvatar(); + + MelonLogger.Msg("Switched active camera rigs."); + PlayerSetup.Instance.desktopCameraRig.SetActive(!isVR); + PlayerSetup.Instance.vrCameraRig.SetActive(isVR); + + if (CohtmlHud.Instance == null) + { + MelonLogger.Msg("CohtmlHud Instance not found!!!"); + return; + } + MelonLogger.Msg("Parented CohtmlHud to active camera."); + CohtmlHud.Instance.gameObject.transform.parent = isVR ? PlayerSetup.Instance.vrCamera.transform : PlayerSetup.Instance.desktopCamera.transform; + + //i think the VR offset depends on headset... cant find where in the games code it is though so could be wrong... ? + CohtmlHud.Instance.gameObject.transform.localPosition = isVR ? new Vector3(-0.2f, -0.391f, 1.244f) : new Vector3(0f, 0f, 1.3f); } - static IEnumerator LoadDevice(string newDevice) + //hopefully whatever rework was hinted at doesn't immediatly break this + private static void SetMovementSystem(bool isVR) { - if (String.Compare(XRSettings.loadedDeviceName, newDevice, true) != 0) + if (MovementSystem.Instance == null) { - XRSettings.LoadDeviceByName(newDevice); - yield return null; - XRSettings.enabled = true; - if (SteamVR_Behaviour.instance.enabled == false) - { - SteamVR_Behaviour.instance.enabled = true; - SteamVR_Render.instance.enabled = true; - } + MelonLogger.Msg("MovementSystem Instance not found!!!"); + return; } - else + MelonLogger.Msg($"Set MovementSystem instance to {isVR}."); + MovementSystem.Instance.isVr = true; + } + + private static void ReloadCVRInputManager() + { + if (CVRInputManager.Instance == null) { - MelonLogger.Msg("OpenVR device already loaded!"); - MelonCoroutines.Stop(melon); - yield return null; - XRSettings.enabled = true; - if (SteamVR_Behaviour.instance.enabled == false) - { - SteamVR_Behaviour.instance.enabled = true; - SteamVR_Render.instance.enabled = true; - } + MelonLogger.Msg("CVRInputManager Instance not found!!!"); + return; } + MelonLogger.Msg("Set CVRInputManager reload to True. Input should reload next frame..."); + CVRInputManager.Instance.reload = true; + CVRInputManager.Instance.inputEnabled = true; + CVRInputManager.Instance.blockedByUi = false; + CVRInputManager.Instance.independentHeadToggle = false; + CVRInputManager.Instance.gestureLeft = 0f; + CVRInputManager.Instance.gestureLeftRaw = 0f; + CVRInputManager.Instance.gestureRight = 0f; + CVRInputManager.Instance.gestureRightRaw = 0f; + } + + private static void Recalibrate() + { + if (PlayerSetup.Instance == null) + { + MelonLogger.Msg("PlayerSetup Instance not found!!!"); + return; + } + MelonLogger.Msg("Called ReCalibrateAvatar() on PlayerSetup.Instance. Will take a second..."); + PlayerSetup.Instance.ReCalibrateAvatar(); } } \ No newline at end of file diff --git a/DesktopVRSwitch/Properties/AssemblyInfo.cs b/DesktopVRSwitch/Properties/AssemblyInfo.cs index 8ff8fcf..6795fe7 100644 --- a/DesktopVRSwitch/Properties/AssemblyInfo.cs +++ b/DesktopVRSwitch/Properties/AssemblyInfo.cs @@ -1,5 +1,5 @@ -using MelonLoader; -using DesktopVRSwitch.Properties; +using DesktopVRSwitch.Properties; +using MelonLoader; using System.Reflection; From 4de16ff1ecf2d6f717de28c5919a5f120b409132 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sun, 25 Sep 2022 05:05:10 -0500 Subject: [PATCH 08/42] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8707f5f..e84578b 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,9 @@ kinda shit test to see how resilient the game is when switching between Desktop Desktop to VR works enough -VR to Desktop does not close SteamVR and sometimes just refuses to work +VR to Desktop works enough + +Hud is not positioned correctly once entering VR https://user-images.githubusercontent.com/37721153/192128515-5630f47b-63ed-45c5-b0eb-0aac46d23731.mp4 From 1e0f96fae9ef23c278869fbdc19a3db9354bc1b4 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sun, 25 Sep 2022 06:56:34 -0500 Subject: [PATCH 09/42] timeout for error catch..? --- DesktopVRSwitch/Main.cs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index 01018a6..a4d85ef 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -16,14 +16,24 @@ public class DesktopVRSwitch : MelonMod { private static System.Object melon; private static bool isAttemptingSwitch = false; + private static float timedSwitch = 0f; public override void OnUpdate() { // assuming CVRInputManager.switchMode button was originally for desktop/vr switching before being left to do literally nothing in rootlogic if (Input.GetKeyDown(KeyCode.F6) && (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && !isAttemptingSwitch) { + //start attempt isAttemptingSwitch = true; melon = MelonCoroutines.Start(AttemptPlatformSwitch()); + timedSwitch = Time.time + 10f; + } + + if (isAttemptingSwitch && Time.time > timedSwitch) + { + isAttemptingSwitch = false; + MelonCoroutines.Stop(melon); + MelonLogger.Msg("Timer exceeded. Something is wrong."); } } @@ -38,7 +48,7 @@ public class DesktopVRSwitch : MelonMod //we are waiting a frame in LoadDevice after LoadDeviceByName() yield return new WaitForEndOfFrame(); - CloseMenuElements(); + CloseMenuElements(toVR); yield return new WaitForEndOfFrame(); @@ -109,12 +119,13 @@ public class DesktopVRSwitch : MelonMod } // shouldn't be that important, right? - private static void CloseMenuElements() + private static void CloseMenuElements(bool isVR) { if (ViewManager.Instance != null) { MelonLogger.Msg("Closed MainMenu Instance."); ViewManager.Instance.UiStateToggle(false); + ViewManager.Instance.VrInputChanged(isVR); } else { @@ -198,6 +209,7 @@ public class DesktopVRSwitch : MelonMod //i think the VR offset depends on headset... cant find where in the games code it is though so could be wrong... ? CohtmlHud.Instance.gameObject.transform.localPosition = isVR ? new Vector3(-0.2f, -0.391f, 1.244f) : new Vector3(0f, 0f, 1.3f); + CohtmlHud.Instance.gameObject.transform.localRotation = Quaternion.Euler( new Vector3(0f, 180f, 0f) ); } //hopefully whatever rework was hinted at doesn't immediatly break this From 517aa7c51b14735287d3f4afd57e2bcbc395393b Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Mon, 26 Sep 2022 18:25:33 -0500 Subject: [PATCH 10/42] first pass of implementing try-catch everything shall be caught --- DesktopVRSwitch/Main.cs | 295 +++++++++++++++++++++++----------------- 1 file changed, 172 insertions(+), 123 deletions(-) diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index a4d85ef..c568a8f 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -7,6 +7,7 @@ using MelonLoader; using RootMotion.FinalIK; using System.Collections; using UnityEngine; +using Object = UnityEngine.Object; using UnityEngine.XR; using Valve.VR; @@ -14,7 +15,6 @@ namespace DesktopVRSwitch; public class DesktopVRSwitch : MelonMod { - private static System.Object melon; private static bool isAttemptingSwitch = false; private static float timedSwitch = 0f; @@ -25,15 +25,16 @@ public class DesktopVRSwitch : MelonMod { //start attempt isAttemptingSwitch = true; - melon = MelonCoroutines.Start(AttemptPlatformSwitch()); + MelonCoroutines.Start(AttemptPlatformSwitch()); + //how long we wait until we assume an error occured timedSwitch = Time.time + 10f; } + //catch if coroutine just decided to not finish... which happens? if (isAttemptingSwitch && Time.time > timedSwitch) { isAttemptingSwitch = false; - MelonCoroutines.Stop(melon); - MelonLogger.Msg("Timer exceeded. Something is wrong."); + MelonLogger.Error("Timer exceeded. Something is wrong and coroutine failed partway."); } } @@ -41,12 +42,38 @@ public class DesktopVRSwitch : MelonMod { bool toVR = !MetaPort.Instance.isUsingVr; - //load SteamVR/OpenVR if entering VR - MelonCoroutines.Start(LoadDevice("OpenVR", toVR)); + //load or unload SteamVR + if (toVR) + { + //force SteamVR to fully initialize, this does all and more than what i did with LoadDevice() + SteamVR.Initialize(true); + + //Just to make sure. Game does this natively when entering VR. + SteamVR_Settings.instance.pauseGameWhenDashboardVisible = false; - //we need to wait a frame or meet doom :shock: :shock: :stare: - //we are waiting a frame in LoadDevice after LoadDeviceByName() - yield return new WaitForEndOfFrame(); + //TODO: something needs to be done to reinitialize SteamVR_Input or SteamVR_Actions + //If you restart SteamVR after already have been in VRMode, the steamvr action handles break + //ive tried: + //SteamVR_Input.Initialize(true) + //SteamVR_Actions.PreInitialize() + //Destroying SteamVR_Settings on DesktopMode + //Destroying SteamVR_Behavior on DesktopMode + //Destroying SteamVR_Render on DesktopMode + //Combinations of all of these.. + //Its probably really simple, but I just cannot figure out how. + } + else + { + //force SteamVR to let go of Chillout + XRSettings.LoadDeviceByName("None"); + XRSettings.enabled = false; + + //destroy [SteamVR] gameobject as next SteamVR.Initialize creates a new one + Object.Destroy(SteamVR_Behaviour.instance.gameObject); + + //what even does this do that is actually important? + SteamVR.SafeDispose(); + } CloseMenuElements(toVR); @@ -57,6 +84,10 @@ public class DesktopVRSwitch : MelonMod yield return new WaitForEndOfFrame(); SetPlayerSetup(toVR); + SwitchActiveCameraRigs(toVR); + CreateTempVRIK(toVR); + QuickCalibrate(toVR); + RepositionCohtmlHud(toVR); yield return new WaitForEndOfFrame(); @@ -64,10 +95,7 @@ public class DesktopVRSwitch : MelonMod yield return new WaitForEndOfFrame(); - SetSteamVRInstances(toVR); - - yield return new WaitForEndOfFrame(); - + //right here is the fucker most likely to break ReloadCVRInputManager(); //some menus have 0.5s wait(), so to be safe @@ -78,45 +106,12 @@ public class DesktopVRSwitch : MelonMod yield return null; isAttemptingSwitch = false; } - private static IEnumerator LoadDevice(string newDevice, bool isVR) - { - if (isVR) - { - if (String.Compare(XRSettings.loadedDeviceName, newDevice, true) != 0) - { - XRSettings.LoadDeviceByName(newDevice); - yield return null; - XRSettings.enabled = true; - SteamVR.settings.pauseGameWhenDashboardVisible = false; - if (SteamVR_Behaviour.instance.enabled == false) - { - SteamVR_Behaviour.instance.enabled = true; - SteamVR_Render.instance.enabled = true; - } - } - else - { - MelonLogger.Msg("OpenVR device already loaded!"); - MelonCoroutines.Stop(melon); - yield return null; - XRSettings.enabled = true; - if (SteamVR_Behaviour.instance.enabled == false) - { - SteamVR_Behaviour.instance.enabled = true; - SteamVR_Render.instance.enabled = true; - } - isAttemptingSwitch = false; - } - } - else - { - //holyfuck that was a lot of trial and error - SteamVR.enabled = false; - yield return new WaitForEndOfFrame(); - XRSettings.LoadDeviceByName("None"); - yield return null; - } - } + + + + //shitton of try catch below + + // shouldn't be that important, right? private static void CloseMenuElements(bool isVR) @@ -144,112 +139,166 @@ public class DesktopVRSwitch : MelonMod private static void SetMetaPort(bool isVR) { - if (MetaPort.Instance == null) + try { - MelonLogger.Msg("MetaPort Instance not found!!!"); - return; + MelonLogger.Msg($"Set MetaPort isUsingVr to {isVR}."); + MetaPort.Instance.isUsingVr = isVR; } - MelonLogger.Msg($"Set MetaPort isUsingVr to {isVR}."); - MetaPort.Instance.isUsingVr = isVR; - } - - //uh huh - private static void SetSteamVRInstances(bool isVR) - { - if (SteamVR_Behaviour.instance == null) + catch (Exception) { - MelonLogger.Msg("SteamVR Instances not found!!!"); - return; + MelonLogger.Error("Setting MetaPort isUsingVr failed. Is MetaPort.Instance invalid?"); + MelonLogger.Msg("MetaPort.Instance: " + MetaPort.Instance); + throw; } - MelonLogger.Msg($"Set SteamVR monobehavior instances to {isVR}."); - SteamVR_Behaviour.instance.enabled = isVR; - SteamVR_Render.instance.enabled = isVR; - //set again just in case on desktop & disabling - XRSettings.enabled = isVR; } private static void SetPlayerSetup(bool isVR) { - if (PlayerSetup.Instance == null) + try { - MelonLogger.Msg("PlayerSetup Instance not found!!!"); - return; + MelonLogger.Msg($"Set PlayerSetup instance to {isVR}."); + PlayerSetup.Instance._inVr = isVR; } - - if (isVR) + catch (Exception) { - MelonLogger.Msg("Creating temp VRIK component."); - VRIK ik = (VRIK)PlayerSetup.Instance._avatar.GetComponent(typeof(VRIK)); - if (ik == null) + MelonLogger.Error("Setting PlayerSetup _inVr failed. Is PlayerSetup.Instance invalid?"); + MelonLogger.Msg("PlayerSetup.Instance: " + PlayerSetup.Instance); + throw; + } + } + + private static void CreateTempVRIK(bool isVR) + { + try + { + if (isVR) { - ik = PlayerSetup.Instance._avatar.AddComponent(); + MelonLogger.Msg("Creating temp VRIK component."); + VRIK ik = (VRIK)PlayerSetup.Instance._avatar.GetComponent(typeof(VRIK)); + if (ik == null) + { + ik = PlayerSetup.Instance._avatar.AddComponent(); + } + ik.solver.IKPositionWeight = 0f; + ik.enabled = false; + } + else + { + MelonLogger.Msg("Temp VRIK component is not needed. Ignoring."); } - ik.solver.IKPositionWeight = 0f; - ik.enabled = false; } - - MelonLogger.Msg($"Set PlayerSetup instance to {isVR}."); - PlayerSetup.Instance._inVr = isVR; - - //we invoke calibrate to get VRIK and calibrator instance set up, faster than full recalibrate - MelonLogger.Msg("Called CalibrateAvatar() on PlayerSetup.Instance. Expect a few errors from PlayerSetup Update() and LateUpdate()."); - PlayerSetup.Instance.CalibrateAvatar(); - - MelonLogger.Msg("Switched active camera rigs."); - PlayerSetup.Instance.desktopCameraRig.SetActive(!isVR); - PlayerSetup.Instance.vrCameraRig.SetActive(isVR); - - if (CohtmlHud.Instance == null) + catch (Exception) { - MelonLogger.Msg("CohtmlHud Instance not found!!!"); - return; + MelonLogger.Error("Temp creation of VRIK on avatar failed. Is PlayerSetup.Instance invalid?"); + MelonLogger.Msg("PlayerSetup.Instance: " + PlayerSetup.Instance); + throw; } - MelonLogger.Msg("Parented CohtmlHud to active camera."); - CohtmlHud.Instance.gameObject.transform.parent = isVR ? PlayerSetup.Instance.vrCamera.transform : PlayerSetup.Instance.desktopCamera.transform; + } - //i think the VR offset depends on headset... cant find where in the games code it is though so could be wrong... ? - CohtmlHud.Instance.gameObject.transform.localPosition = isVR ? new Vector3(-0.2f, -0.391f, 1.244f) : new Vector3(0f, 0f, 1.3f); - CohtmlHud.Instance.gameObject.transform.localRotation = Quaternion.Euler( new Vector3(0f, 180f, 0f) ); + private static void QuickCalibrate(bool isVR) + { + try + { + //we invoke calibrate to get VRIK and calibrator instance set up, faster than full recalibrate + MelonLogger.Msg("Called CalibrateAvatar() on PlayerSetup.Instance. Expect a few errors from PlayerSetup Update() and LateUpdate()."); + PlayerSetup.Instance.CalibrateAvatar(); + } + catch (Exception) + { + MelonLogger.Error("CalibrateAvatar() failed. Is PlayerSetup.Instance invalid?"); + MelonLogger.Msg("PlayerSetup.Instance: " + PlayerSetup.Instance); + throw; + } + } + + private static void SwitchActiveCameraRigs(bool isVR) + { + try + { + MelonLogger.Msg("Switched active camera rigs."); + PlayerSetup.Instance.desktopCameraRig.SetActive(!isVR); + PlayerSetup.Instance.vrCameraRig.SetActive(isVR); + } + catch (Exception) + { + MelonLogger.Error("Error switching active cameras. Are the camera rigs invalid?"); + MelonLogger.Msg("PlayerSetup.Instance.desktopCameraRig: " + PlayerSetup.Instance.desktopCameraRig); + MelonLogger.Msg("PlayerSetup.Instance.vrCameraRig: " + PlayerSetup.Instance.vrCameraRig); + throw; + } + } + + private static void RepositionCohtmlHud(bool isVR) + { + try + { + MelonLogger.Msg("Parented CohtmlHud to active camera."); + CohtmlHud.Instance.gameObject.transform.parent = isVR ? PlayerSetup.Instance.vrCamera.transform : PlayerSetup.Instance.desktopCamera.transform; + //i think the VR offset may be different between headsets, but i cannot find where in games code they are set + CohtmlHud.Instance.gameObject.transform.localPosition = isVR ? new Vector3(-0.2f, -0.391f, 1.244f) : new Vector3(0f, 0f, 1.3f); + CohtmlHud.Instance.gameObject.transform.localRotation = Quaternion.Euler(new Vector3(0f, 180f, 0f)); + } + catch (Exception) + { + MelonLogger.Error("Error parenting CohtmlHud to active camera. Is CohtmlHud.Instance invalid?"); + MelonLogger.Msg("CohtmlHud.Instance: " + CohtmlHud.Instance); + throw; + } } //hopefully whatever rework was hinted at doesn't immediatly break this private static void SetMovementSystem(bool isVR) { - if (MovementSystem.Instance == null) + try { - MelonLogger.Msg("MovementSystem Instance not found!!!"); - return; + MelonLogger.Msg($"Set MovementSystem instance to {isVR}."); + MovementSystem.Instance.isVr = true; + } + catch (Exception) + { + MelonLogger.Error("Setting MovementSystem isVr failed. Is MovementSystem.Instance invalid?"); + MelonLogger.Msg("MovementSystem.Instance: " + MovementSystem.Instance); + throw; } - MelonLogger.Msg($"Set MovementSystem instance to {isVR}."); - MovementSystem.Instance.isVr = true; } private static void ReloadCVRInputManager() { - if (CVRInputManager.Instance == null) + try { - MelonLogger.Msg("CVRInputManager Instance not found!!!"); - return; + MelonLogger.Msg("Set CVRInputManager reload to True. Input should reload next frame..."); + CVRInputManager.Instance.reload = true; + //just in case + CVRInputManager.Instance.inputEnabled = true; + CVRInputManager.Instance.blockedByUi = false; + //sometimes head can get stuck, so just in case + CVRInputManager.Instance.independentHeadToggle = false; + //just nice to load into desktop with idle gesture + CVRInputManager.Instance.gestureLeft = 0f; + CVRInputManager.Instance.gestureLeftRaw = 0f; + CVRInputManager.Instance.gestureRight = 0f; + CVRInputManager.Instance.gestureRightRaw = 0f; + } + catch (Exception) + { + MelonLogger.Error("CVRInputManager reload failed. Is CVRInputManager.Instance invalid?"); + MelonLogger.Msg("CVRInputManager.Instance: " + CVRInputManager.Instance); + throw; } - MelonLogger.Msg("Set CVRInputManager reload to True. Input should reload next frame..."); - CVRInputManager.Instance.reload = true; - CVRInputManager.Instance.inputEnabled = true; - CVRInputManager.Instance.blockedByUi = false; - CVRInputManager.Instance.independentHeadToggle = false; - CVRInputManager.Instance.gestureLeft = 0f; - CVRInputManager.Instance.gestureLeftRaw = 0f; - CVRInputManager.Instance.gestureRight = 0f; - CVRInputManager.Instance.gestureRightRaw = 0f; } private static void Recalibrate() { - if (PlayerSetup.Instance == null) + try { - MelonLogger.Msg("PlayerSetup Instance not found!!!"); - return; + MelonLogger.Msg("Called ReCalibrateAvatar() on PlayerSetup.Instance. Will take a second..."); + PlayerSetup.Instance.ReCalibrateAvatar(); + } + catch (Exception) + { + MelonLogger.Error("ReCalibrateAvatar() failed. Is PlayerSetup.Instance invalid?"); + MelonLogger.Msg("PlayerSetup.Instance: " + PlayerSetup.Instance); + throw; } - MelonLogger.Msg("Called ReCalibrateAvatar() on PlayerSetup.Instance. Will take a second..."); - PlayerSetup.Instance.ReCalibrateAvatar(); } } \ No newline at end of file From 94ab1bde9747d93742435cfaa64107e18222e0d2 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Mon, 26 Sep 2022 20:09:46 -0500 Subject: [PATCH 11/42] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e84578b..6f61625 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Desktop to VR works enough VR to Desktop works enough -Hud is not positioned correctly once entering VR +Press Control + F6 to switch. https://user-images.githubusercontent.com/37721153/192128515-5630f47b-63ed-45c5-b0eb-0aac46d23731.mp4 From 8db636455a799c97550bd61a11aad2979017cb44 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Mon, 26 Sep 2022 20:12:04 -0500 Subject: [PATCH 12/42] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6f61625..74b40de 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Desktop to VR works enough VR to Desktop works enough -Press Control + F6 to switch. +Press Control + F6 to switch. (this is an old clip attached, its faster and more reliable now) https://user-images.githubusercontent.com/37721153/192128515-5630f47b-63ed-45c5-b0eb-0aac46d23731.mp4 From 43d100f37e0297f81c028a986f8af22d93984ff1 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Tue, 27 Sep 2022 00:44:13 -0500 Subject: [PATCH 13/42] kind of error catch, other fixes --- DesktopVRSwitch/DesktopVRSwitch.csproj | 3 + DesktopVRSwitch/Main.cs | 136 ++++++++++++++++--------- 2 files changed, 93 insertions(+), 46 deletions(-) diff --git a/DesktopVRSwitch/DesktopVRSwitch.csproj b/DesktopVRSwitch/DesktopVRSwitch.csproj index 2251ad3..de3e0bb 100644 --- a/DesktopVRSwitch/DesktopVRSwitch.csproj +++ b/DesktopVRSwitch/DesktopVRSwitch.csproj @@ -33,6 +33,9 @@ C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\SteamVR.dll + + ..\..\..\DakyModsCVR\ManagedLibs\Unity.TextMeshPro.dll + ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.AnimationModule.dll diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index c568a8f..b63bce0 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -2,6 +2,8 @@ using ABI_RC.Core.Player; using ABI_RC.Core.Savior; using ABI_RC.Core.UI; +using ABI_RC.Core; +using ABI_RC.Core.Util.Object_Behaviour; using ABI_RC.Systems.MovementSystem; using MelonLoader; using RootMotion.FinalIK; @@ -17,6 +19,7 @@ public class DesktopVRSwitch : MelonMod { private static bool isAttemptingSwitch = false; private static float timedSwitch = 0f; + private static bool CurrentMode; public override void OnUpdate() { @@ -25,7 +28,8 @@ public class DesktopVRSwitch : MelonMod { //start attempt isAttemptingSwitch = true; - MelonCoroutines.Start(AttemptPlatformSwitch()); + MelonCoroutines.Start( AttemptPlatformSwitch() ); + //how long we wait until we assume an error occured timedSwitch = Time.time + 10f; } @@ -33,21 +37,63 @@ public class DesktopVRSwitch : MelonMod //catch if coroutine just decided to not finish... which happens? if (isAttemptingSwitch && Time.time > timedSwitch) { - isAttemptingSwitch = false; MelonLogger.Error("Timer exceeded. Something is wrong and coroutine failed partway."); + MelonCoroutines.Start( AttemptPlatformSwitch(true) ); } } - private static IEnumerator AttemptPlatformSwitch() + private static IEnumerator AttemptPlatformSwitch(bool forceMode = false) { - bool toVR = !MetaPort.Instance.isUsingVr; - + //forceMode will attempt to backtrack to last working mode + CurrentMode = forceMode ? CurrentMode : MetaPort.Instance.isUsingVr; + bool VRMode = forceMode ? CurrentMode : !CurrentMode; + //load or unload SteamVR - if (toVR) + InitializeSteamVR(VRMode); + + CloseMenuElements(VRMode); + + yield return new WaitForEndOfFrame(); + + SetMetaPort(VRMode); + + yield return new WaitForEndOfFrame(); + + SetPlayerSetup(VRMode); + SwitchActiveCameraRigs(VRMode); + UpdateCameraFacingObject(); + CreateTempVRIK(VRMode); + QuickCalibrate(VRMode); + RepositionCohtmlHud(VRMode); + UpdateHudOperations(VRMode); + + yield return new WaitForEndOfFrame(); + + SetMovementSystem(VRMode); + + yield return new WaitForEndOfFrame(); + + //right here is the fucker most likely to break + ReloadCVRInputManager(); + + //some menus have 0.5s wait(), so to be safe + yield return new WaitForSeconds(1f); + + Recalibrate(); + + yield return null; + isAttemptingSwitch = false; + } + + //shitton of try catch below + + private static void InitializeSteamVR(bool isVR) + { + if (isVR) { //force SteamVR to fully initialize, this does all and more than what i did with LoadDevice() SteamVR.Initialize(true); - + //Just to make sure. Game does this natively when entering VR. SteamVR_Settings.instance.pauseGameWhenDashboardVisible = false; @@ -74,45 +120,9 @@ public class DesktopVRSwitch : MelonMod //what even does this do that is actually important? SteamVR.SafeDispose(); } - - CloseMenuElements(toVR); - - yield return new WaitForEndOfFrame(); - - SetMetaPort(toVR); - - yield return new WaitForEndOfFrame(); - - SetPlayerSetup(toVR); - SwitchActiveCameraRigs(toVR); - CreateTempVRIK(toVR); - QuickCalibrate(toVR); - RepositionCohtmlHud(toVR); - - yield return new WaitForEndOfFrame(); - - SetMovementSystem(toVR); - - yield return new WaitForEndOfFrame(); - - //right here is the fucker most likely to break - ReloadCVRInputManager(); - - //some menus have 0.5s wait(), so to be safe - yield return new WaitForSeconds(1f); - - Recalibrate(); - - yield return null; - isAttemptingSwitch = false; } - - //shitton of try catch below - - - // shouldn't be that important, right? private static void CloseMenuElements(bool isVR) { @@ -234,9 +244,9 @@ public class DesktopVRSwitch : MelonMod { MelonLogger.Msg("Parented CohtmlHud to active camera."); CohtmlHud.Instance.gameObject.transform.parent = isVR ? PlayerSetup.Instance.vrCamera.transform : PlayerSetup.Instance.desktopCamera.transform; - //i think the VR offset may be different between headsets, but i cannot find where in games code they are set - CohtmlHud.Instance.gameObject.transform.localPosition = isVR ? new Vector3(-0.2f, -0.391f, 1.244f) : new Vector3(0f, 0f, 1.3f); - CohtmlHud.Instance.gameObject.transform.localRotation = Quaternion.Euler(new Vector3(0f, 180f, 0f)); + + //sets hud position, rotation, and scale based on MetaPort isUsingVr + CVRTools.ConfigureHudAffinity(); } catch (Exception) { @@ -301,4 +311,38 @@ public class DesktopVRSwitch : MelonMod throw; } } + + //every nameplate canvas uses CameraFacingObject :stare: + //might need to use actual Desktop/VR cam instead of Camera.main + private static void UpdateCameraFacingObject() + { + try + { + CameraFacingObject[] camfaceobjs = Object.FindObjectsOfType(); + + for (int i = 0; i < camfaceobjs.Count(); i++) + { + camfaceobjs[i].m_Camera = Camera.main; + } + } + catch (Exception) + { + MelonLogger.Error("Error updating CameraFacingObject objects! Nameplates will be wonk..."); + throw; + } + } + + private static void UpdateHudOperations(bool isVR) + { + try + { + HudOperations.Instance.worldLoadingItem = isVR ? HudOperations.Instance.worldLoadingItemVr : HudOperations.Instance.worldLoadingItemDesktop; + HudOperations.Instance.worldLoadStatus = isVR ? HudOperations.Instance.worldLoadStatusVr : HudOperations.Instance.worldLoadStatusDesktop; + } + catch (Exception) + { + MelonLogger.Error("Error updating HudOperations LoadingItem & LoadStatus!"); + throw; + } + } } \ No newline at end of file From 50ce525711c3619cd99f52c1731c04c6df422670 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Tue, 27 Sep 2022 17:57:32 -0500 Subject: [PATCH 14/42] Update README.md --- README.md | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 74b40de..a3b6b7d 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,31 @@ # DesktopVRSwitch -kinda shit test to see how resilient the game is when switching between Desktop and VR during runtime +Allows you to switch between Desktop and VR with a keybind. -Desktop to VR works enough +Press Control + F6 to switch. -VR to Desktop works enough +While this mod is a nice convienence feature to have access to, not every chillout system or mod is built to support it. Keep in mind there **will be issues**, so don't get mad if you do end up having to restart. **:stare:** -Press Control + F6 to switch. (this is an old clip attached, its faster and more reliable now) +Please take a look at the table below for what may not function as intended after switch. A lot of them can be remedied by rejoining your current instance. + +| Function | Working | Note | +| ------------- | ------------- | ------------- | +| Discord/Steam RPC | None | Rich Presence will report the first mode you launched in. (might correct on world change) | +| CVRPickupObject | None | Pickups will use the grip origin set during spawn. The game overrides the default VR origin with [Desktop] origin if available, so I cannot revert to VR origins when switching from Desktop. | +| CVRWorld UpdatePostProcessing | Not Implemented | GraphicsAO and other specific post processing settings are not currently set on switch. | +| SceneLoaded worldCamera | Not Implemented | World-set camera settings are not currently set for both Desktop & VR cameras. | +| ControllerRay vrActive | Not Sure | I haven't had any issues with this, so I haven't bothered looking into it. | +| CVRWorld CopyRefCamValues | Not Implemented | This may not cause issues, but farclip is not set on the opposite modes transition effects when you load a world. | +| CameraFacingObject | Maybe | All CameraFacingObject behaviors have their camera changed to the active main camera on switch. Not sure if this is a good solution, but required for nameplates to face your viewpoint. | +| CoHtmlHud | Yes | CoHtmlHud is parented to the active camera on switch. | +| HudOperations | Kind Of | HudOperations is set to use the correct gameobjects to show loading info on the bottom right of the hud, but it seems to not be placed correctly. | +| CheckVR | No | Not needed. We initialize SteamVR ourselves and MetaPort only checks it on Start. | +| MetaPort | Yes | This is the most important as everything checks here for VRMode. Some systems will cache VRMode on start though, which is where issues with switching occur. | +| PlayerSetup | Yes | Also highly important. PlayerSetup caches VRMode from MetaPort to run correct calibration. To prevent errors, a dummy VRIK component is created before running a quick calibration to prevent PlayerSetup from erroring when switching to VR. | +| MovementSystem | Yes | MovementSystem constantly checks MetaPort for VRMode each frame, so while it isn't directly needed I still set the cached VRMode to true. | +| CVRInputManager | Yes..? | We set CVRInputManager.reload to have input & menus reload next frame, but also set independentHeadToggle and others to false to prevent the game from locking head control. | +| GesturePlaneTest | Testing | GestureReconizer will use the original launch camera for reference, which means you cannot pull the camera out with gestures when switched. It is the only part of the game that makes a cached result from VRMode private, so I have to dick around with Traverse/Harmony. :stare: | + +(an old clip from the first few tests, no longer using melonprefs as uiexpansionkit kinda gets nuked on menu reload) https://user-images.githubusercontent.com/37721153/192128515-5630f47b-63ed-45c5-b0eb-0aac46d23731.mp4 From 0f8a23e0e84d969979868091ece752beadf82fdc Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Tue, 27 Sep 2022 18:21:50 -0500 Subject: [PATCH 15/42] CVRMG Submission *attempt*..? --- DesktopVRSwitch/Main.cs | 84 ++++++++++++++++++++++++++++++------- DesktopVRSwitch/format.json | 20 ++++----- 2 files changed, 79 insertions(+), 25 deletions(-) diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index b63bce0..35a7e7b 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -1,17 +1,17 @@ -using ABI_RC.Core.InteractionSystem; +using ABI_RC.Core; +using ABI_RC.Core.InteractionSystem; using ABI_RC.Core.Player; using ABI_RC.Core.Savior; using ABI_RC.Core.UI; -using ABI_RC.Core; using ABI_RC.Core.Util.Object_Behaviour; using ABI_RC.Systems.MovementSystem; using MelonLoader; using RootMotion.FinalIK; using System.Collections; using UnityEngine; -using Object = UnityEngine.Object; using UnityEngine.XR; using Valve.VR; +using Object = UnityEngine.Object; namespace DesktopVRSwitch; @@ -28,7 +28,7 @@ public class DesktopVRSwitch : MelonMod { //start attempt isAttemptingSwitch = true; - MelonCoroutines.Start( AttemptPlatformSwitch() ); + MelonCoroutines.Start(AttemptPlatformSwitch()); //how long we wait until we assume an error occured timedSwitch = Time.time + 10f; @@ -38,26 +38,28 @@ public class DesktopVRSwitch : MelonMod if (isAttemptingSwitch && Time.time > timedSwitch) { MelonLogger.Error("Timer exceeded. Something is wrong and coroutine failed partway."); - MelonCoroutines.Start( AttemptPlatformSwitch(true) ); + MelonCoroutines.Start(AttemptPlatformSwitch(true)); } } private static IEnumerator AttemptPlatformSwitch(bool forceMode = false) { - //forceMode will attempt to backtrack to last working mode + //forceMode will attempt to backtrack to last working mode (if you dont like the mess, fix it yourself thx) CurrentMode = forceMode ? CurrentMode : MetaPort.Instance.isUsingVr; bool VRMode = forceMode ? CurrentMode : !CurrentMode; - + //load or unload SteamVR InitializeSteamVR(VRMode); CloseMenuElements(VRMode); - yield return new WaitForEndOfFrame(); + yield + return new WaitForEndOfFrame(); SetMetaPort(VRMode); - yield return new WaitForEndOfFrame(); + yield + return new WaitForEndOfFrame(); SetPlayerSetup(VRMode); SwitchActiveCameraRigs(VRMode); @@ -67,21 +69,33 @@ public class DesktopVRSwitch : MelonMod RepositionCohtmlHud(VRMode); UpdateHudOperations(VRMode); - yield return new WaitForEndOfFrame(); + yield + return new WaitForEndOfFrame(); SetMovementSystem(VRMode); - yield return new WaitForEndOfFrame(); + yield + return new WaitForEndOfFrame(); + + //needs to come after SetMovementSystem + //UpdateGestureReconizerCam(); //right here is the fucker most likely to break ReloadCVRInputManager(); //some menus have 0.5s wait(), so to be safe - yield return new WaitForSeconds(1f); + yield + return new WaitForSeconds(1f); Recalibrate(); - yield return null; + //tell the game to change VRMode/DesktopMode for Steam/Discord presence + //RichPresence.PopulatePresence(); + + //nvm that resets the RichPresence clock- i want people to know how long ive wasted staring at mirror + + yield + return null; isAttemptingSwitch = false; } @@ -122,7 +136,6 @@ public class DesktopVRSwitch : MelonMod } } - // shouldn't be that important, right? private static void CloseMenuElements(bool isVR) { @@ -244,7 +257,7 @@ public class DesktopVRSwitch : MelonMod { MelonLogger.Msg("Parented CohtmlHud to active camera."); CohtmlHud.Instance.gameObject.transform.parent = isVR ? PlayerSetup.Instance.vrCamera.transform : PlayerSetup.Instance.desktopCamera.transform; - + //sets hud position, rotation, and scale based on MetaPort isUsingVr CVRTools.ConfigureHudAffinity(); } @@ -318,6 +331,7 @@ public class DesktopVRSwitch : MelonMod { try { + MelonLogger.Msg("Updating all CameraFacingObject scripts to face new camera. (this fixes nameplates)"); CameraFacingObject[] camfaceobjs = Object.FindObjectsOfType(); for (int i = 0; i < camfaceobjs.Count(); i++) @@ -332,10 +346,34 @@ public class DesktopVRSwitch : MelonMod } } + //cant fix unless i log the original VR gripOrigins with a patch... + //private static void SetPickupObjectOrigins() + //{ + // try + // { + // CVRPickupObject[] pickups = Object.FindObjectsOfType(); + + // if (pickups.gripOrigin != null) + // { + // Transform x = this.gripOrigin.Find("[Desktop]"); + // if (x != null) + // { + // this.gripOrigin = x; + // } + // } + // } + // catch (Exception) + // { + // MelonLogger.Error("Error updating CameraFacingObject objects! Nameplates will be wonk..."); + // throw; + // } + //} + private static void UpdateHudOperations(bool isVR) { try { + MelonLogger.Msg("Set HudOperations worldLoadingItem and worldLoadStatus to their respective Desktop/Vr parent."); HudOperations.Instance.worldLoadingItem = isVR ? HudOperations.Instance.worldLoadingItemVr : HudOperations.Instance.worldLoadingItemDesktop; HudOperations.Instance.worldLoadStatus = isVR ? HudOperations.Instance.worldLoadStatusVr : HudOperations.Instance.worldLoadStatusDesktop; } @@ -345,4 +383,20 @@ public class DesktopVRSwitch : MelonMod throw; } } + + //i suck at traverse + //private static void UpdateGestureReconizerCam() + //{ + // try + // { + // MelonLogger.Msg("Set GestureReconizerCam camera to Camera.main."); + // Camera _camera = Traverse.Create(CVRGestureRecognizer.Instance).Field("_camera").GetValue(); + // _camera = Camera.main; + // } + // catch (Exception) + // { + // MelonLogger.Error("Error updating CVRGestureRecognizer camera!"); + // throw; + // } + //} } \ No newline at end of file diff --git a/DesktopVRSwitch/format.json b/DesktopVRSwitch/format.json index cca5e49..258d342 100644 --- a/DesktopVRSwitch/format.json +++ b/DesktopVRSwitch/format.json @@ -1,23 +1,23 @@ { - "_id": 95, + "_id": -1, "name": "DesktopVRSwitch", - "modversion": "1.1.0", + "modversion": "1.0.0", "gameversion": "2022r168", "loaderversion": "0.5.4", "modtype": "Mod", "author": "NotAKidoS", - "description": "Corrects MM and QM position when avatar is scaled.\nAdditional option to scale player collision.", + "description": "Allows you to switch between Desktop and VR with a keybind.\n**Press Control + F6 to switch.**\n\nWhile this mod is a nice convienence feature to have access to, not every chillout system or mod is built to support it. I cannot possibly cover every edge case or mitigate issues with every mod. **Use at your own discretion.**", "searchtags": [ - "menu", - "scale", - "avatarscale", - "slider" + "desktop", + "vr", + "switch", + "hotswap" ], "requirements": [ "None" ], - "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/r2/DesktopVRSwitch.dll", + "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/r1/DesktopVRSwitch.dll", "sourcelink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/", - "changelog": "Added option to scale player collision. Fixed some VR specific issues.", - "embedcolor": "804221" + "changelog": "Initial Release", + "embedcolor": "3498db" } \ No newline at end of file From 4d42c670490cd3ef62a03f8965addb5c44b4d5f1 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sun, 9 Oct 2022 07:49:44 -0500 Subject: [PATCH 16/42] WIP update --- DesktopVRSwitch/Main.cs | 118 +++++++++++++++++++++++++--------------- 1 file changed, 74 insertions(+), 44 deletions(-) diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index 35a7e7b..274e9bb 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -5,14 +5,24 @@ using ABI_RC.Core.Savior; using ABI_RC.Core.UI; using ABI_RC.Core.Util.Object_Behaviour; using ABI_RC.Systems.MovementSystem; +using ABI_RC.Core.EventSystem; using MelonLoader; using RootMotion.FinalIK; using System.Collections; using UnityEngine; using UnityEngine.XR; using Valve.VR; +using HarmonyLib; using Object = UnityEngine.Object; +//Remove VRIK on VR to Desktop +//Remove LookAtIK on Desktop to VR + +//Set Desktop camera to head again...? +//Recenter collision position (in VR it shifts around) + + + namespace DesktopVRSwitch; public class DesktopVRSwitch : MelonMod @@ -64,30 +74,51 @@ public class DesktopVRSwitch : MelonMod SetPlayerSetup(VRMode); SwitchActiveCameraRigs(VRMode); UpdateCameraFacingObject(); - CreateTempVRIK(VRMode); - QuickCalibrate(VRMode); RepositionCohtmlHud(VRMode); UpdateHudOperations(VRMode); yield return new WaitForEndOfFrame(); + RemoveComponents(VRMode); + + yield + return new WaitForEndOfFrame(); + SetMovementSystem(VRMode); yield return new WaitForEndOfFrame(); //needs to come after SetMovementSystem - //UpdateGestureReconizerCam(); + UpdateGestureReconizerCam(); + + yield + return new WaitForSeconds(0.5f); //right here is the fucker most likely to break ReloadCVRInputManager(); //some menus have 0.5s wait(), so to be safe yield - return new WaitForSeconds(1f); + return new WaitForSeconds(0.5f); - Recalibrate(); + //I am setting the collision center to the avatars position so the collision is set in the same place as where it was after the player moved roomscale in VR + + //need to recenter player avatar as VRIK locomotion moves that directly + Vector3 roomscalePos = PlayerSetup.Instance._avatar.transform.position; + Quaternion roomscaleRot = PlayerSetup.Instance._avatar.transform.rotation; + + MovementSystem.Instance.enabled = false; + MovementSystem.Instance.transform.position = roomscalePos; + MovementSystem.Instance.transform.rotation = roomscaleRot; + MovementSystem.Instance.enabled = true; + + //collision center is set to match headpos in VR, but desktop doesnt reset it + //MovementSystem.Instance.proxyCollider.center = Vector3.zero; //not sure why UpdateColliderCenter doesnt do this + MovementSystem.Instance.UpdateColliderCenter(roomscalePos); + + //AssetManagement.Instance.LoadLocalAvatar(this.avatarId); //tell the game to change VRMode/DesktopMode for Steam/Discord presence //RichPresence.PopulatePresence(); @@ -190,24 +221,39 @@ public class DesktopVRSwitch : MelonMod } } - private static void CreateTempVRIK(bool isVR) + private static void RemoveComponents(bool isVR) { try { - if (isVR) + if (!isVR) { - MelonLogger.Msg("Creating temp VRIK component."); + MelonLogger.Msg("VRIK component is not needed. Removing."); VRIK ik = (VRIK)PlayerSetup.Instance._avatar.GetComponent(typeof(VRIK)); - if (ik == null) + if (ik != null) { - ik = PlayerSetup.Instance._avatar.AddComponent(); + UnityEngine.Object.Destroy(ik); } - ik.solver.IKPositionWeight = 0f; - ik.enabled = false; } else { - MelonLogger.Msg("Temp VRIK component is not needed. Ignoring."); + MelonLogger.Msg("LookIK component is not needed. Removing."); + LookAtIK ik = (LookAtIK)PlayerSetup.Instance._avatar.GetComponent(typeof(LookAtIK)); + if (ik != null) + { + UnityEngine.Object.Destroy(ik); + } + } + + MelonLogger.Msg("Removing Viseme and Eye controllers."); + CVRVisemeController cvrvisemeController = (CVRVisemeController)PlayerSetup.Instance._avatar.GetComponent(typeof(CVRVisemeController)); + if (cvrvisemeController != null) + { + UnityEngine.Object.Destroy(cvrvisemeController); + } + CVREyeController cvreyeController = (CVREyeController)PlayerSetup.Instance._avatar.GetComponent(typeof(CVREyeController)); + if (cvreyeController != null) + { + UnityEngine.Object.Destroy(cvreyeController); } } catch (Exception) @@ -218,22 +264,6 @@ public class DesktopVRSwitch : MelonMod } } - private static void QuickCalibrate(bool isVR) - { - try - { - //we invoke calibrate to get VRIK and calibrator instance set up, faster than full recalibrate - MelonLogger.Msg("Called CalibrateAvatar() on PlayerSetup.Instance. Expect a few errors from PlayerSetup Update() and LateUpdate()."); - PlayerSetup.Instance.CalibrateAvatar(); - } - catch (Exception) - { - MelonLogger.Error("CalibrateAvatar() failed. Is PlayerSetup.Instance invalid?"); - MelonLogger.Msg("PlayerSetup.Instance: " + PlayerSetup.Instance); - throw; - } - } - private static void SwitchActiveCameraRigs(bool isVR) { try @@ -315,7 +345,7 @@ public class DesktopVRSwitch : MelonMod try { MelonLogger.Msg("Called ReCalibrateAvatar() on PlayerSetup.Instance. Will take a second..."); - PlayerSetup.Instance.ReCalibrateAvatar(); + PlayerSetup.Instance.CalibrateAvatar(); } catch (Exception) { @@ -385,18 +415,18 @@ public class DesktopVRSwitch : MelonMod } //i suck at traverse - //private static void UpdateGestureReconizerCam() - //{ - // try - // { - // MelonLogger.Msg("Set GestureReconizerCam camera to Camera.main."); - // Camera _camera = Traverse.Create(CVRGestureRecognizer.Instance).Field("_camera").GetValue(); - // _camera = Camera.main; - // } - // catch (Exception) - // { - // MelonLogger.Error("Error updating CVRGestureRecognizer camera!"); - // throw; - // } - //} + private static void UpdateGestureReconizerCam() + { + try + { + MelonLogger.Msg("Set GestureReconizerCam camera to Camera.main."); + Camera cam = Traverse.Create(CVRGestureRecognizer.Instance).Field("_camera").GetValue() as Camera; + cam = Camera.main; + } + catch (Exception) + { + MelonLogger.Error("Error updating CVRGestureRecognizer camera!"); + throw; + } + } } \ No newline at end of file From 485eb7fd794d89e9074b780b39f64a541814eb86 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Mon, 10 Oct 2022 19:31:51 -0500 Subject: [PATCH 17/42] "fix" avatar position flying away really fucked fix but its temp until i have time to redo --- DesktopVRSwitch/Main.cs | 192 +++++++++++++--------------------------- 1 file changed, 60 insertions(+), 132 deletions(-) diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index 274e9bb..497f2cf 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -6,6 +6,7 @@ using ABI_RC.Core.UI; using ABI_RC.Core.Util.Object_Behaviour; using ABI_RC.Systems.MovementSystem; using ABI_RC.Core.EventSystem; +using ABI_RC.Systems.IK.SubSystems; using MelonLoader; using RootMotion.FinalIK; using System.Collections; @@ -21,15 +22,34 @@ using Object = UnityEngine.Object; //Set Desktop camera to head again...? //Recenter collision position (in VR it shifts around) +//tell the game to change VRMode/DesktopMode for Steam/Discord presence +//RichPresence.PopulatePresence(); + +//nvm that resets the RichPresence clock- i want people to know how long ive wasted staring at mirror + namespace DesktopVRSwitch; public class DesktopVRSwitch : MelonMod { + private static MelonPreferences_Category m_categoryDesktopVRSwitch; + private static MelonPreferences_Entry m_entryReloadInstance; + private static MelonPreferences_Entry m_entryTimedErrorCatch; + public override void OnApplicationStart() + { + m_categoryDesktopVRSwitch = MelonPreferences.CreateCategory(nameof(DesktopVRSwitch)); + //m_entryReloadInstance = m_categoryDesktopVRSwitch.CreateEntry("Rejoin Instance", false, description: "Rejoin instance on switch."); + m_entryTimedErrorCatch = m_categoryDesktopVRSwitch.CreateEntry("Timed Error Catch", true, description: "Attempt to switch back if an error is found after 10 seconds."); + + m_categoryDesktopVRSwitch.SaveToFile(false); + } + private static bool isAttemptingSwitch = false; private static float timedSwitch = 0f; private static bool CurrentMode; + private static Vector3 avatarPos; + private static Quaternion avatarRot; public override void OnUpdate() { @@ -50,6 +70,13 @@ public class DesktopVRSwitch : MelonMod MelonLogger.Error("Timer exceeded. Something is wrong and coroutine failed partway."); MelonCoroutines.Start(AttemptPlatformSwitch(true)); } + + //correct player position + if (isAttemptingSwitch && !MovementSystem.Instance.canMove) + { + MovementSystem.Instance.TeleportToPosRot(avatarPos, avatarRot, false); + MovementSystem.Instance.UpdateColliderCenter(avatarPos); + } } private static IEnumerator AttemptPlatformSwitch(bool forceMode = false) @@ -58,7 +85,15 @@ public class DesktopVRSwitch : MelonMod CurrentMode = forceMode ? CurrentMode : MetaPort.Instance.isUsingVr; bool VRMode = forceMode ? CurrentMode : !CurrentMode; - //load or unload SteamVR + //store current player position/rotation to correct VR/Desktop offsets + avatarPos = PlayerSetup.Instance._avatar.transform.position; + avatarRot = PlayerSetup.Instance._avatar.transform.rotation; + + //prevent player from any movement while transitioning + MovementSystem.Instance.canMove = false; + BodySystem.TrackingEnabled = false; + + //load SteamVR InitializeSteamVR(VRMode); CloseMenuElements(VRMode); @@ -80,21 +115,11 @@ public class DesktopVRSwitch : MelonMod yield return new WaitForEndOfFrame(); - RemoveComponents(VRMode); - - yield - return new WaitForEndOfFrame(); - - SetMovementSystem(VRMode); - - yield - return new WaitForEndOfFrame(); - //needs to come after SetMovementSystem - UpdateGestureReconizerCam(); + //UpdateGestureReconizerCam(); yield - return new WaitForSeconds(0.5f); + return new WaitForEndOfFrame(); //right here is the fucker most likely to break ReloadCVRInputManager(); @@ -103,27 +128,21 @@ public class DesktopVRSwitch : MelonMod yield return new WaitForSeconds(0.5f); - //I am setting the collision center to the avatars position so the collision is set in the same place as where it was after the player moved roomscale in VR + //reload current avatar + AssetManagement.Instance.LoadLocalAvatar(MetaPort.Instance.currentAvatarGuid); - //need to recenter player avatar as VRIK locomotion moves that directly - Vector3 roomscalePos = PlayerSetup.Instance._avatar.transform.position; - Quaternion roomscaleRot = PlayerSetup.Instance._avatar.transform.rotation; + yield + return new WaitForSeconds(2f); - MovementSystem.Instance.enabled = false; - MovementSystem.Instance.transform.position = roomscalePos; - MovementSystem.Instance.transform.rotation = roomscaleRot; - MovementSystem.Instance.enabled = true; + if (!VRMode) + //collision center is set to match headpos in VR, but desktop doesnt reset it + MovementSystem.Instance.UpdateColliderCenter(PlayerSetup.Instance._avatar.transform.position); - //collision center is set to match headpos in VR, but desktop doesnt reset it - //MovementSystem.Instance.proxyCollider.center = Vector3.zero; //not sure why UpdateColliderCenter doesnt do this - MovementSystem.Instance.UpdateColliderCenter(roomscalePos); + //gonna try doing this last + DisposeSteamVR(VRMode); - //AssetManagement.Instance.LoadLocalAvatar(this.avatarId); - - //tell the game to change VRMode/DesktopMode for Steam/Discord presence - //RichPresence.PopulatePresence(); - - //nvm that resets the RichPresence clock- i want people to know how long ive wasted staring at mirror + MovementSystem.Instance.canMove = true; + BodySystem.TrackingEnabled = true; yield return null; @@ -153,7 +172,11 @@ public class DesktopVRSwitch : MelonMod //Combinations of all of these.. //Its probably really simple, but I just cannot figure out how. } - else + } + + private static void DisposeSteamVR(bool isVR) + { + if (!isVR) { //force SteamVR to let go of Chillout XRSettings.LoadDeviceByName("None"); @@ -189,6 +212,9 @@ public class DesktopVRSwitch : MelonMod { MelonLogger.Msg("QuickMenu Instance not found!!!"); } + + //disable input during switch + CVRInputManager.Instance.inputEnabled = false; } private static void SetMetaPort(bool isVR) @@ -221,49 +247,6 @@ public class DesktopVRSwitch : MelonMod } } - private static void RemoveComponents(bool isVR) - { - try - { - if (!isVR) - { - MelonLogger.Msg("VRIK component is not needed. Removing."); - VRIK ik = (VRIK)PlayerSetup.Instance._avatar.GetComponent(typeof(VRIK)); - if (ik != null) - { - UnityEngine.Object.Destroy(ik); - } - } - else - { - MelonLogger.Msg("LookIK component is not needed. Removing."); - LookAtIK ik = (LookAtIK)PlayerSetup.Instance._avatar.GetComponent(typeof(LookAtIK)); - if (ik != null) - { - UnityEngine.Object.Destroy(ik); - } - } - - MelonLogger.Msg("Removing Viseme and Eye controllers."); - CVRVisemeController cvrvisemeController = (CVRVisemeController)PlayerSetup.Instance._avatar.GetComponent(typeof(CVRVisemeController)); - if (cvrvisemeController != null) - { - UnityEngine.Object.Destroy(cvrvisemeController); - } - CVREyeController cvreyeController = (CVREyeController)PlayerSetup.Instance._avatar.GetComponent(typeof(CVREyeController)); - if (cvreyeController != null) - { - UnityEngine.Object.Destroy(cvreyeController); - } - } - catch (Exception) - { - MelonLogger.Error("Temp creation of VRIK on avatar failed. Is PlayerSetup.Instance invalid?"); - MelonLogger.Msg("PlayerSetup.Instance: " + PlayerSetup.Instance); - throw; - } - } - private static void SwitchActiveCameraRigs(bool isVR) { try @@ -299,22 +282,6 @@ public class DesktopVRSwitch : MelonMod } } - //hopefully whatever rework was hinted at doesn't immediatly break this - private static void SetMovementSystem(bool isVR) - { - try - { - MelonLogger.Msg($"Set MovementSystem instance to {isVR}."); - MovementSystem.Instance.isVr = true; - } - catch (Exception) - { - MelonLogger.Error("Setting MovementSystem isVr failed. Is MovementSystem.Instance invalid?"); - MelonLogger.Msg("MovementSystem.Instance: " + MovementSystem.Instance); - throw; - } - } - private static void ReloadCVRInputManager() { try @@ -340,23 +307,7 @@ public class DesktopVRSwitch : MelonMod } } - private static void Recalibrate() - { - try - { - MelonLogger.Msg("Called ReCalibrateAvatar() on PlayerSetup.Instance. Will take a second..."); - PlayerSetup.Instance.CalibrateAvatar(); - } - catch (Exception) - { - MelonLogger.Error("ReCalibrateAvatar() failed. Is PlayerSetup.Instance invalid?"); - MelonLogger.Msg("PlayerSetup.Instance: " + PlayerSetup.Instance); - throw; - } - } - //every nameplate canvas uses CameraFacingObject :stare: - //might need to use actual Desktop/VR cam instead of Camera.main private static void UpdateCameraFacingObject() { try @@ -366,7 +317,7 @@ public class DesktopVRSwitch : MelonMod for (int i = 0; i < camfaceobjs.Count(); i++) { - camfaceobjs[i].m_Camera = Camera.main; + camfaceobjs[i].m_Camera = PlayerSetup.Instance.GetActiveCamera().GetComponent(); } } catch (Exception) @@ -376,29 +327,6 @@ public class DesktopVRSwitch : MelonMod } } - //cant fix unless i log the original VR gripOrigins with a patch... - //private static void SetPickupObjectOrigins() - //{ - // try - // { - // CVRPickupObject[] pickups = Object.FindObjectsOfType(); - - // if (pickups.gripOrigin != null) - // { - // Transform x = this.gripOrigin.Find("[Desktop]"); - // if (x != null) - // { - // this.gripOrigin = x; - // } - // } - // } - // catch (Exception) - // { - // MelonLogger.Error("Error updating CameraFacingObject objects! Nameplates will be wonk..."); - // throw; - // } - //} - private static void UpdateHudOperations(bool isVR) { try @@ -414,14 +342,14 @@ public class DesktopVRSwitch : MelonMod } } - //i suck at traverse + //this doesnt seem to work private static void UpdateGestureReconizerCam() { try { MelonLogger.Msg("Set GestureReconizerCam camera to Camera.main."); Camera cam = Traverse.Create(CVRGestureRecognizer.Instance).Field("_camera").GetValue() as Camera; - cam = Camera.main; + cam = PlayerSetup.Instance.GetActiveCamera().GetComponent(); } catch (Exception) { From 9fee74f5873cd6b6e082f9be3f64873d9eb3ef06 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 29 Oct 2022 06:34:11 -0500 Subject: [PATCH 18/42] fix hud scale --- DesktopVRSwitch/Main.cs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index 497f2cf..d0f2cd7 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -16,11 +16,6 @@ using Valve.VR; using HarmonyLib; using Object = UnityEngine.Object; -//Remove VRIK on VR to Desktop -//Remove LookAtIK on Desktop to VR - -//Set Desktop camera to head again...? -//Recenter collision position (in VR it shifts around) //tell the game to change VRMode/DesktopMode for Steam/Discord presence //RichPresence.PopulatePresence(); @@ -61,7 +56,8 @@ public class DesktopVRSwitch : MelonMod MelonCoroutines.Start(AttemptPlatformSwitch()); //how long we wait until we assume an error occured - timedSwitch = Time.time + 10f; + if (m_entryTimedErrorCatch.Value) + timedSwitch = Time.time + 10f; } //catch if coroutine just decided to not finish... which happens? @@ -71,7 +67,7 @@ public class DesktopVRSwitch : MelonMod MelonCoroutines.Start(AttemptPlatformSwitch(true)); } - //correct player position + //correct player position while switching if (isAttemptingSwitch && !MovementSystem.Instance.canMove) { MovementSystem.Instance.TeleportToPosRot(avatarPos, avatarRot, false); @@ -273,6 +269,7 @@ public class DesktopVRSwitch : MelonMod //sets hud position, rotation, and scale based on MetaPort isUsingVr CVRTools.ConfigureHudAffinity(); + CohtmlHud.Instance.gameObject.transform.localScale = new Vector3(1.2f, 1f, 1.2f); } catch (Exception) { From 7f860f4fc22e83540f085a114342bc9492ec41f0 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 29 Oct 2022 09:07:27 -0500 Subject: [PATCH 19/42] prop origin fixes, version 2 --- DesktopVRSwitch/Main.cs | 66 +++++++++++++------ .../Patches/CVRPickupObjectTracker.cs | 59 +++++++++++++++++ DesktopVRSwitch/Properties/AssemblyInfo.cs | 2 +- 3 files changed, 107 insertions(+), 20 deletions(-) create mode 100644 DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index d0f2cd7..c8e1910 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -1,42 +1,37 @@ using ABI_RC.Core; +using ABI_RC.Core.EventSystem; using ABI_RC.Core.InteractionSystem; using ABI_RC.Core.Player; using ABI_RC.Core.Savior; using ABI_RC.Core.UI; using ABI_RC.Core.Util.Object_Behaviour; -using ABI_RC.Systems.MovementSystem; -using ABI_RC.Core.EventSystem; +using ABI_RC.Systems.Camera; using ABI_RC.Systems.IK.SubSystems; +using ABI_RC.Systems.MovementSystem; +using DesktopVRSwitch.Patches; +using HarmonyLib; using MelonLoader; -using RootMotion.FinalIK; using System.Collections; using UnityEngine; using UnityEngine.XR; using Valve.VR; -using HarmonyLib; using Object = UnityEngine.Object; - //tell the game to change VRMode/DesktopMode for Steam/Discord presence //RichPresence.PopulatePresence(); //nvm that resets the RichPresence clock- i want people to know how long ive wasted staring at mirror - - namespace DesktopVRSwitch; public class DesktopVRSwitch : MelonMod { private static MelonPreferences_Category m_categoryDesktopVRSwitch; - private static MelonPreferences_Entry m_entryReloadInstance; private static MelonPreferences_Entry m_entryTimedErrorCatch; - public override void OnApplicationStart() + public override void OnInitializeMelon() { m_categoryDesktopVRSwitch = MelonPreferences.CreateCategory(nameof(DesktopVRSwitch)); - //m_entryReloadInstance = m_categoryDesktopVRSwitch.CreateEntry("Rejoin Instance", false, description: "Rejoin instance on switch."); m_entryTimedErrorCatch = m_categoryDesktopVRSwitch.CreateEntry("Timed Error Catch", true, description: "Attempt to switch back if an error is found after 10 seconds."); - m_categoryDesktopVRSwitch.SaveToFile(false); } @@ -93,6 +88,7 @@ public class DesktopVRSwitch : MelonMod InitializeSteamVR(VRMode); CloseMenuElements(VRMode); + DisableMirrorCanvas(); yield return new WaitForEndOfFrame(); @@ -107,12 +103,13 @@ public class DesktopVRSwitch : MelonMod UpdateCameraFacingObject(); RepositionCohtmlHud(VRMode); UpdateHudOperations(VRMode); + SwitchPickupOrigins(); yield return new WaitForEndOfFrame(); //needs to come after SetMovementSystem - //UpdateGestureReconizerCam(); + UpdateGestureReconizerCam(); yield return new WaitForEndOfFrame(); @@ -193,7 +190,6 @@ public class DesktopVRSwitch : MelonMod { MelonLogger.Msg("Closed MainMenu Instance."); ViewManager.Instance.UiStateToggle(false); - ViewManager.Instance.VrInputChanged(isVR); } else { @@ -267,7 +263,7 @@ public class DesktopVRSwitch : MelonMod MelonLogger.Msg("Parented CohtmlHud to active camera."); CohtmlHud.Instance.gameObject.transform.parent = isVR ? PlayerSetup.Instance.vrCamera.transform : PlayerSetup.Instance.desktopCamera.transform; - //sets hud position, rotation, and scale based on MetaPort isUsingVr + //sets hud position, rotation, ~~and scale~~ based on MetaPort isUsingVr CVRTools.ConfigureHudAffinity(); CohtmlHud.Instance.gameObject.transform.localScale = new Vector3(1.2f, 1f, 1.2f); } @@ -339,14 +335,13 @@ public class DesktopVRSwitch : MelonMod } } - //this doesnt seem to work - private static void UpdateGestureReconizerCam() + private static void DisableMirrorCanvas() { try { - MelonLogger.Msg("Set GestureReconizerCam camera to Camera.main."); - Camera cam = Traverse.Create(CVRGestureRecognizer.Instance).Field("_camera").GetValue() as Camera; - cam = PlayerSetup.Instance.GetActiveCamera().GetComponent(); + //tell the game we are in mirror mode so itll disable it (if enabled) + PortableCamera.Instance.mode = MirroringMode.Mirror; + PortableCamera.Instance.ChangeMirroring(); } catch (Exception) { @@ -354,4 +349,37 @@ public class DesktopVRSwitch : MelonMod throw; } } + + private static void UpdateGestureReconizerCam() + { + try + { + MelonLogger.Msg("Set GestureReconizerCam camera to active camera."); + Traverse.Create(CVRGestureRecognizer.Instance).Field("_camera").SetValue(PlayerSetup.Instance.GetActiveCamera().GetComponent()); + } + catch (Exception) + { + MelonLogger.Error("Error updating CVRGestureRecognizer camera!"); + throw; + } + } + + private static void SwitchPickupOrigins() + { + try + { + MelonLogger.Msg("Switched pickup origins."); + CVRPickupObjectTracker[] pickups = Object.FindObjectsOfType(); + + for (int i = 0; i < pickups.Count(); i++) + { + pickups[i].OnSwitch(); + } + } + catch (Exception) + { + MelonLogger.Error("Error switching pickup origins!"); + throw; + } + } } \ No newline at end of file diff --git a/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs b/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs new file mode 100644 index 0000000..36cac6d --- /dev/null +++ b/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs @@ -0,0 +1,59 @@ +using ABI.CCK.Components; +using ABI_RC.Core.Savior; +using HarmonyLib; +using MelonLoader; +using UnityEngine; + +//Thanks Ben! I was scared of transpiler so I reworked a bit... + +namespace DesktopVRSwitch.Patches; + +[HarmonyPatch] +internal class CVRPickupObject_Patch +{ + [HarmonyPrefix] + [HarmonyPatch(typeof(CVRPickupObject), "Start")] + private static void CVRPickupObject_Start_Prefix(ref CVRPickupObject __instance) + { + Transform desktopOrigin = __instance.gripOrigin.Find("[Desktop]"); + if (desktopOrigin == null) return; + + var pickupTracker = __instance.GetComponent(); + if (pickupTracker != null) return; + + __instance.gameObject.AddComponent(); + + StorePreviousPosition(__instance, (!MetaPort.Instance.isUsingVr) ? __instance.gripOrigin : desktopOrigin); + } + + private static void StorePreviousPosition(CVRPickupObject pickupObject, Transform gripOrigin) + { + MelonLogger.Msg("Storing previous gripOrigin."); + CVRPickupObjectTracker.previousGripOrigin[pickupObject] = gripOrigin; + } +} + +public class CVRPickupObjectTracker : MonoBehaviour +{ + //maybe i should store both transforms instead and getcomponent for CVRPickupObject..? + public static Dictionary previousGripOrigin = new(); + + public void OnSwitch() + { + var pickupObject = GetComponent(); + + if (pickupObject != null) + { + if (pickupObject.IsGrabbedByMe()) pickupObject.Drop(); + (previousGripOrigin[pickupObject], pickupObject.gripOrigin) = (pickupObject.gripOrigin, previousGripOrigin[pickupObject]); + } + } + + private void OnDestroy() + { + var pickupObject = GetComponent(); + + if (pickupObject != null) + previousGripOrigin.Remove(pickupObject); + } +} diff --git a/DesktopVRSwitch/Properties/AssemblyInfo.cs b/DesktopVRSwitch/Properties/AssemblyInfo.cs index 6795fe7..03ba712 100644 --- a/DesktopVRSwitch/Properties/AssemblyInfo.cs +++ b/DesktopVRSwitch/Properties/AssemblyInfo.cs @@ -25,6 +25,6 @@ using System.Reflection; namespace DesktopVRSwitch.Properties; internal static class AssemblyInfoParams { - public const string Version = "1.0.0"; + public const string Version = "2.0.0"; public const string Author = "NotAKidoS"; } \ No newline at end of file From 73762e7241a122a88c1262c9078724ab2254a9e2 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 29 Oct 2022 09:45:17 -0500 Subject: [PATCH 20/42] fix held objects not dropping correctly --- DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs | 4 +++- DesktopVRSwitch/format.json | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs b/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs index 36cac6d..5bb7943 100644 --- a/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs +++ b/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs @@ -15,6 +15,8 @@ internal class CVRPickupObject_Patch [HarmonyPatch(typeof(CVRPickupObject), "Start")] private static void CVRPickupObject_Start_Prefix(ref CVRPickupObject __instance) { + if (__instance.gripOrigin == null) return; + Transform desktopOrigin = __instance.gripOrigin.Find("[Desktop]"); if (desktopOrigin == null) return; @@ -44,7 +46,7 @@ public class CVRPickupObjectTracker : MonoBehaviour if (pickupObject != null) { - if (pickupObject.IsGrabbedByMe()) pickupObject.Drop(); + if (pickupObject.IsGrabbedByMe() && pickupObject._controllerRay != null) pickupObject._controllerRay.DropObject(true); (previousGripOrigin[pickupObject], pickupObject.gripOrigin) = (pickupObject.gripOrigin, previousGripOrigin[pickupObject]); } } diff --git a/DesktopVRSwitch/format.json b/DesktopVRSwitch/format.json index 258d342..6f77ed3 100644 --- a/DesktopVRSwitch/format.json +++ b/DesktopVRSwitch/format.json @@ -1,7 +1,7 @@ { "_id": -1, "name": "DesktopVRSwitch", - "modversion": "1.0.0", + "modversion": "2.0.0", "gameversion": "2022r168", "loaderversion": "0.5.4", "modtype": "Mod", @@ -16,7 +16,7 @@ "requirements": [ "None" ], - "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/r1/DesktopVRSwitch.dll", + "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/r2/DesktopVRSwitch.dll", "sourcelink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/", "changelog": "Initial Release", "embedcolor": "3498db" From 933913bb11d3eab4382319160d9737dcaaa82e91 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Thu, 15 Dec 2022 11:29:06 -0600 Subject: [PATCH 21/42] i dont remember --- DesktopVRSwitch/DesktopVRSwitch.csproj | 9 + DesktopVRSwitch/DesktopVRSwitchHelper.cs | 416 ++++++++++++++++++ DesktopVRSwitch/Main.cs | 376 ++-------------- DesktopVRSwitch/Patches/ReferenceCameraFix.cs | 127 ++++++ DesktopVRSwitch/Properties/AssemblyInfo.cs | 2 +- DesktopVRSwitch/UIExpansionKitAddon.cs | 14 + DesktopVRSwitch/format.json | 12 +- 7 files changed, 606 insertions(+), 350 deletions(-) create mode 100644 DesktopVRSwitch/DesktopVRSwitchHelper.cs create mode 100644 DesktopVRSwitch/Patches/ReferenceCameraFix.cs create mode 100644 DesktopVRSwitch/UIExpansionKitAddon.cs diff --git a/DesktopVRSwitch/DesktopVRSwitch.csproj b/DesktopVRSwitch/DesktopVRSwitch.csproj index de3e0bb..adb74e4 100644 --- a/DesktopVRSwitch/DesktopVRSwitch.csproj +++ b/DesktopVRSwitch/DesktopVRSwitch.csproj @@ -18,6 +18,9 @@ ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Assembly-CSharp-firstpass.dll + + ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Aura2_Core.dll + ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\cohtml.Net.dll @@ -33,6 +36,12 @@ C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\SteamVR.dll + + ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\Mods\UIExpansionKit.dll + + + ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Unity.Postprocessing.Runtime.dll + ..\..\..\DakyModsCVR\ManagedLibs\Unity.TextMeshPro.dll diff --git a/DesktopVRSwitch/DesktopVRSwitchHelper.cs b/DesktopVRSwitch/DesktopVRSwitchHelper.cs new file mode 100644 index 0000000..72c873c --- /dev/null +++ b/DesktopVRSwitch/DesktopVRSwitchHelper.cs @@ -0,0 +1,416 @@ +using ABI_RC.Core; +using ABI_RC.Core.EventSystem; +using ABI_RC.Core.InteractionSystem; +using ABI_RC.Core.Player; +using ABI_RC.Core.Savior; +using ABI_RC.Core.UI; +using ABI_RC.Core.Util.Object_Behaviour; +using ABI_RC.Systems.Camera; +using ABI_RC.Systems.IK; +using ABI_RC.Systems.IK.SubSystems; +using ABI_RC.Systems.IK.TrackingModules; +using ABI_RC.Systems.MovementSystem; +using ABI_RC.Core.Networking; +using DesktopVRSwitch.Patches; +using HarmonyLib; +using MelonLoader; +using System.Collections; +using UnityEngine; +using UnityEngine.XR; +using Valve.VR; +using Object = UnityEngine.Object; + +namespace DesktopVRSwitch; + +public class DesktopVRSwitchHelper : MonoBehaviour +{ + public static DesktopVRSwitchHelper Instance; + + //settings + public bool SettingTimedErrorCatch = true; + public float SettingTimedErrorTimer = 10f; + + //internal shit + internal static bool isAttemptingSwitch = false; + internal static float timedSwitch = 0f; + internal static bool CurrentMode; + internal static Vector3 avatarWorldPos; + internal static Quaternion avatarWorldRot; + + public void SwitchMode(bool isTimedSwitch = false) + { + if (isAttemptingSwitch) return; + + isAttemptingSwitch = true; + MelonCoroutines.Start(AttemptPlatformSwitch()); + + //how long we wait until we assume an error occured + if (isTimedSwitch) + timedSwitch = Time.time + SettingTimedErrorTimer; + } + + public void Start() + { + Instance = this; + } + + public void Update() + { + // assuming CVRInputManager.switchMode button was originally for desktop/vr switching before being left to do literally nothing in rootlogic + if (Input.GetKeyDown(KeyCode.F6) && (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && !isAttemptingSwitch) + { + SwitchMode(true); + } + + if (!isAttemptingSwitch) return; + + //catch if coroutine just decided to not finish... which happens? + if (Time.time > timedSwitch) + { + MelonLogger.Error("Timer exceeded. Something is wrong and coroutine failed partway."); + isAttemptingSwitch = false; + if (SettingTimedErrorCatch) + SwitchMode(); + } + } + + //disables VRIK if it was on the current avatar during switch + //absolutely bruteforcing the stupid vr playspace offset issue + public void LateUpdate() + { + if (!isAttemptingSwitch) return; + BodySystem.TrackingEnabled = false; + BodySystem.TrackingPositionWeight = 0f; + PlayerSetup.Instance._avatar.transform.position = avatarWorldPos; + PlayerSetup.Instance._avatar.transform.rotation = avatarWorldRot; + MovementSystem.Instance.TeleportToPosRot(avatarWorldPos, avatarWorldRot, false); + MovementSystem.Instance.UpdateColliderCenter(avatarWorldPos); + } + + internal static IEnumerator AttemptPlatformSwitch(bool forceMode = false) + { + //forceMode will attempt to backtrack to last working mode (if you dont like the mess, fix it yourself thx) + CurrentMode = forceMode ? CurrentMode : MetaPort.Instance.isUsingVr; + bool VRMode = forceMode ? CurrentMode : !CurrentMode; + + CloseMenuElements(VRMode); + ToggleInputInteractions(false); + DisableMirrorCanvas(); + + //store current player position/rotation to correct VR/Desktop offsets + avatarWorldPos = PlayerSetup.Instance._avatar.transform.position; + avatarWorldRot = PlayerSetup.Instance._avatar.transform.rotation; + + //exit all movement states + MovementSystem.Instance.ChangeCrouch(false); + MovementSystem.Instance.ChangeProne(false); + MovementSystem.Instance.canMove = false; + MovementSystem.Instance.canRot = false; + + //load SteamVR + InitializeSteamVR(VRMode); + + yield + return new WaitForEndOfFrame(); + + SetMetaPort(VRMode); + + //reset rich presence + if (MetaPort.Instance.settings.GetSettingsBool("ImplementationRichPresenceDiscordEnabled", true)) + { + MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceDiscordEnabled", false); + MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceDiscordEnabled", true); + } + if (MetaPort.Instance.settings.GetSettingsBool("ImplementationRichPresenceSteamEnabled", true)) + { + MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceSteamEnabled", false); + MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceSteamEnabled", true); + } + + yield + return new WaitForEndOfFrame(); + + SwitchActiveCameraRigs(VRMode); + UpdateCameraFacingObject(); + RepositionCohtmlHud(VRMode); + UpdateHudOperations(VRMode); + SwitchPickupOrigins(); + + yield + return new WaitForEndOfFrame(); + + //needs to come after SetMovementSystem + UpdateGestureReconizerCam(); + + ResetCVRInputManager(); + + //gonna try doing this last + DisposeSteamVR(VRMode); + + ToggleInputInteractions(true); + + //reload current avatar + AssetManagement.Instance.LoadLocalAvatar(MetaPort.Instance.currentAvatarGuid); + + yield return new WaitUntil(() => !PlayerSetup.Instance.avatarIsLoading); + + isAttemptingSwitch = false; + + BodySystem.TrackingEnabled = true; + BodySystem.TrackingPositionWeight = 1f; + MovementSystem.Instance.canMove = true; + MovementSystem.Instance.canRot = true; + + if (!VRMode) + //collision center is set to match headpos in VR, but desktop doesnt reset it + MovementSystem.Instance.UpdateColliderCenter(PlayerSetup.Instance._avatar.transform.position); + + yield + return new WaitForEndOfFrame(); + + //one last teleport to correct VR offset + MovementSystem.Instance.TeleportToPosRot(avatarWorldPos, avatarWorldRot, false); + + yield + return null; + } + + //shitton of try catch below + + internal static void InitializeSteamVR(bool isVR) + { + if (isVR) + { + //force SteamVR to fully initialize, this does all and more than what i did with LoadDevice() + SteamVR.Initialize(true); + + //Just to make sure. Game does this natively when entering VR. + SteamVR_Settings.instance.pauseGameWhenDashboardVisible = false; + + //TODO: something needs to be done to reinitialize SteamVR_Input or SteamVR_Actions + //If you restart SteamVR after already have been in VRMode, the steamvr action handles break + //ive tried: + //SteamVR_Input.Initialize(true) + //SteamVR_Actions.PreInitialize() + //Destroying SteamVR_Settings on DesktopMode + //Destroying SteamVR_Behavior on DesktopMode + //Destroying SteamVR_Render on DesktopMode + //Combinations of all of these.. + //Its probably really simple, but I just cannot figure out how. + } + } + + internal static void DisposeSteamVR(bool isVR) + { + if (!isVR) + { + //force SteamVR to let go of Chillout + XRSettings.LoadDeviceByName("None"); + XRSettings.enabled = false; + + //destroy [SteamVR] gameobject as next SteamVR.Initialize creates a new one + Object.Destroy(SteamVR_Behaviour.instance.gameObject); + + //what even does this do that is actually important? + SteamVR.SafeDispose(); + } + } + + // shouldn't be that important, right? + internal static void CloseMenuElements(bool isVR) + { + if (ViewManager.Instance != null) + { + MelonLogger.Msg("Closed MainMenu Instance."); + ViewManager.Instance.UiStateToggle(false); + } + else + { + MelonLogger.Msg("MainMenu Instance not found!!!"); + } + if (ViewManager.Instance != null) + { + MelonLogger.Msg("Closed QuickMenu Instance."); + CVR_MenuManager.Instance.ToggleQuickMenu(false); + } + else + { + MelonLogger.Msg("QuickMenu Instance not found!!!"); + } + } + + internal static void ToggleInputInteractions(bool toggle) + { + //disable input during switch + try + { + MelonLogger.Msg($"Toggling input & interactions to " + toggle); + CVRInputManager.Instance.inputEnabled = toggle; + CVR_InteractableManager.enableInteractions = toggle; + } + catch + { + MelonLogger.Error("Toggling input & interactions failed. Is something invalid?"); + MelonLogger.Msg("CVRInputManager.Instance: " + CVRInputManager.Instance); + MelonLogger.Msg("CVR_InteractableManager: " + CVR_InteractableManager.enableInteractions); + throw; + } + } + internal static void SetMetaPort(bool isVR) + { + try + { + MelonLogger.Msg($"Set MetaPort isUsingVr to {isVR}."); + MetaPort.Instance.isUsingVr = isVR; + } + catch + { + MelonLogger.Error("Setting MetaPort isUsingVr failed. Is MetaPort.Instance invalid?"); + MelonLogger.Msg("MetaPort.Instance: " + MetaPort.Instance); + throw; + } + } + + internal static void SwitchActiveCameraRigs(bool isVR) + { + try + { + MelonLogger.Msg("Switched active camera rigs."); + PlayerSetup.Instance.desktopCameraRig.SetActive(!isVR); + PlayerSetup.Instance.vrCameraRig.SetActive(isVR); + } + catch + { + MelonLogger.Error("Error switching active cameras. Are the camera rigs invalid?"); + MelonLogger.Msg("PlayerSetup.Instance.desktopCameraRig: " + PlayerSetup.Instance.desktopCameraRig); + MelonLogger.Msg("PlayerSetup.Instance.vrCameraRig: " + PlayerSetup.Instance.vrCameraRig); + throw; + } + } + + internal static void RepositionCohtmlHud(bool isVR) + { + try + { + MelonLogger.Msg("Parented CohtmlHud to active camera."); + CohtmlHud.Instance.gameObject.transform.parent = isVR ? PlayerSetup.Instance.vrCamera.transform : PlayerSetup.Instance.desktopCamera.transform; + + //sets hud position, rotation, ~~and scale~~ based on MetaPort isUsingVr + CVRTools.ConfigureHudAffinity(); + CohtmlHud.Instance.gameObject.transform.localScale = new Vector3(1.2f, 1f, 1.2f); + } + catch + { + MelonLogger.Error("Error parenting CohtmlHud to active camera. Is CohtmlHud.Instance invalid?"); + MelonLogger.Msg("CohtmlHud.Instance: " + CohtmlHud.Instance); + throw; + } + } + + internal static void ResetCVRInputManager() + { + try + { + MelonLogger.Msg("Enabling CVRInputManager inputEnabled & disabling blockedByUi!"); + //CVRInputManager.Instance.reload = true; + //just in case + CVRInputManager.Instance.inputEnabled = true; + CVRInputManager.Instance.blockedByUi = false; + //sometimes head can get stuck, so just in case + CVRInputManager.Instance.independentHeadToggle = false; + //just nice to load into desktop with idle gesture + CVRInputManager.Instance.gestureLeft = 0f; + CVRInputManager.Instance.gestureLeftRaw = 0f; + CVRInputManager.Instance.gestureRight = 0f; + CVRInputManager.Instance.gestureRightRaw = 0f; + } + catch + { + MelonLogger.Error("CVRInputManager reload failed. Is CVRInputManager.Instance invalid?"); + MelonLogger.Msg("CVRInputManager.Instance: " + CVRInputManager.Instance); + throw; + } + } + + //every nameplate canvas uses CameraFacingObject :stare: + internal static void UpdateCameraFacingObject() + { + try + { + MelonLogger.Msg("Updating all CameraFacingObject scripts to face new camera. (this fixes nameplates)"); + CameraFacingObject[] camfaceobjs = Object.FindObjectsOfType(); + + for (int i = 0; i < camfaceobjs.Count(); i++) + { + camfaceobjs[i].m_Camera = PlayerSetup.Instance.GetActiveCamera().GetComponent(); + } + } + catch + { + MelonLogger.Error("Error updating CameraFacingObject objects! Nameplates will be wonk..."); + throw; + } + } + + internal static void UpdateHudOperations(bool isVR) + { + try + { + MelonLogger.Msg("Set HudOperations worldLoadingItem and worldLoadStatus to their respective Desktop/Vr parent."); + HudOperations.Instance.worldLoadingItem = isVR ? HudOperations.Instance.worldLoadingItemVr : HudOperations.Instance.worldLoadingItemDesktop; + HudOperations.Instance.worldLoadStatus = isVR ? HudOperations.Instance.worldLoadStatusVr : HudOperations.Instance.worldLoadStatusDesktop; + } + catch + { + MelonLogger.Error("Error updating HudOperations LoadingItem & LoadStatus!"); + throw; + } + } + + internal static void DisableMirrorCanvas() + { + try + { + //tell the game we are in mirror mode so itll disable it (if enabled) + PortableCamera.Instance.mode = MirroringMode.Mirror; + PortableCamera.Instance.ChangeMirroring(); + } + catch + { + MelonLogger.Error("Error updating CVRGestureRecognizer camera!"); + throw; + } + } + + internal static void UpdateGestureReconizerCam() + { + try + { + MelonLogger.Msg("Set GestureReconizerCam camera to active camera."); + Traverse.Create(CVRGestureRecognizer.Instance).Field("_camera").SetValue(PlayerSetup.Instance.GetActiveCamera().GetComponent()); + } + catch + { + MelonLogger.Error("Error updating CVRGestureRecognizer camera!"); + throw; + } + } + + internal static void SwitchPickupOrigins() + { + try + { + MelonLogger.Msg("Switched pickup origins."); + CVRPickupObjectTracker[] pickups = Object.FindObjectsOfType(); + for (int i = 0; i < pickups.Count(); i++) + { + pickups[i].OnSwitch(); + } + } + catch + { + MelonLogger.Error("Error switching pickup origins!"); + throw; + } + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index c8e1910..9d69fba 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -26,360 +26,50 @@ namespace DesktopVRSwitch; public class DesktopVRSwitch : MelonMod { - private static MelonPreferences_Category m_categoryDesktopVRSwitch; - private static MelonPreferences_Entry m_entryTimedErrorCatch; + internal const string SettingsCategory = "DesktopVRSwitch"; + internal static MelonPreferences_Category m_categoryDesktopVRSwitch; + internal static MelonPreferences_Entry m_entryTimedErrorCatch; + internal static MelonPreferences_Entry m_entryTimedErrorTimer; + public override void OnInitializeMelon() { - m_categoryDesktopVRSwitch = MelonPreferences.CreateCategory(nameof(DesktopVRSwitch)); - m_entryTimedErrorCatch = m_categoryDesktopVRSwitch.CreateEntry("Timed Error Catch", true, description: "Attempt to switch back if an error is found after 10 seconds."); + m_categoryDesktopVRSwitch = MelonPreferences.CreateCategory(SettingsCategory); + m_entryTimedErrorCatch = m_categoryDesktopVRSwitch.CreateEntry("Timed Error Catch", true, description: "Attempt to switch back if an error is found after n seconds."); + m_entryTimedErrorTimer = m_categoryDesktopVRSwitch.CreateEntry("Timed Error Timer", 10f, description: "Amount of seconds to wait before assuming there was an error."); + m_categoryDesktopVRSwitch.SaveToFile(false); + foreach (var setting in m_categoryDesktopVRSwitch.Entries) + { + setting.OnEntryValueChangedUntyped.Subscribe(OnUpdateSettings); + } + + //UIExpansionKit addon + if (MelonMod.RegisteredMelons.Any(it => it.Info.Name == "UI Expansion Kit")) + { + MelonLogger.Msg("Initializing UIExpansionKit support."); + UiExtensionsAddon.Init(); + } + MelonLoader.MelonCoroutines.Start(WaitForLocalPlayer()); } - private static bool isAttemptingSwitch = false; - private static float timedSwitch = 0f; - private static bool CurrentMode; - private static Vector3 avatarPos; - private static Quaternion avatarRot; - - public override void OnUpdate() + System.Collections.IEnumerator WaitForLocalPlayer() { - // assuming CVRInputManager.switchMode button was originally for desktop/vr switching before being left to do literally nothing in rootlogic - if (Input.GetKeyDown(KeyCode.F6) && (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && !isAttemptingSwitch) - { - //start attempt - isAttemptingSwitch = true; - MelonCoroutines.Start(AttemptPlatformSwitch()); + while (PlayerSetup.Instance == null) + yield return null; - //how long we wait until we assume an error occured - if (m_entryTimedErrorCatch.Value) - timedSwitch = Time.time + 10f; - } + PlayerSetup.Instance.gameObject.AddComponent(); - //catch if coroutine just decided to not finish... which happens? - if (isAttemptingSwitch && Time.time > timedSwitch) - { - MelonLogger.Error("Timer exceeded. Something is wrong and coroutine failed partway."); - MelonCoroutines.Start(AttemptPlatformSwitch(true)); - } + while (DesktopVRSwitchHelper.Instance == null) + yield return null; - //correct player position while switching - if (isAttemptingSwitch && !MovementSystem.Instance.canMove) - { - MovementSystem.Instance.TeleportToPosRot(avatarPos, avatarRot, false); - MovementSystem.Instance.UpdateColliderCenter(avatarPos); - } + UpdateAllSettings(); } - private static IEnumerator AttemptPlatformSwitch(bool forceMode = false) + private void OnUpdateSettings(object arg1, object arg2) => UpdateAllSettings(); + private void UpdateAllSettings() { - //forceMode will attempt to backtrack to last working mode (if you dont like the mess, fix it yourself thx) - CurrentMode = forceMode ? CurrentMode : MetaPort.Instance.isUsingVr; - bool VRMode = forceMode ? CurrentMode : !CurrentMode; - - //store current player position/rotation to correct VR/Desktop offsets - avatarPos = PlayerSetup.Instance._avatar.transform.position; - avatarRot = PlayerSetup.Instance._avatar.transform.rotation; - - //prevent player from any movement while transitioning - MovementSystem.Instance.canMove = false; - BodySystem.TrackingEnabled = false; - - //load SteamVR - InitializeSteamVR(VRMode); - - CloseMenuElements(VRMode); - DisableMirrorCanvas(); - - yield - return new WaitForEndOfFrame(); - - SetMetaPort(VRMode); - - yield - return new WaitForEndOfFrame(); - - SetPlayerSetup(VRMode); - SwitchActiveCameraRigs(VRMode); - UpdateCameraFacingObject(); - RepositionCohtmlHud(VRMode); - UpdateHudOperations(VRMode); - SwitchPickupOrigins(); - - yield - return new WaitForEndOfFrame(); - - //needs to come after SetMovementSystem - UpdateGestureReconizerCam(); - - yield - return new WaitForEndOfFrame(); - - //right here is the fucker most likely to break - ReloadCVRInputManager(); - - //some menus have 0.5s wait(), so to be safe - yield - return new WaitForSeconds(0.5f); - - //reload current avatar - AssetManagement.Instance.LoadLocalAvatar(MetaPort.Instance.currentAvatarGuid); - - yield - return new WaitForSeconds(2f); - - if (!VRMode) - //collision center is set to match headpos in VR, but desktop doesnt reset it - MovementSystem.Instance.UpdateColliderCenter(PlayerSetup.Instance._avatar.transform.position); - - //gonna try doing this last - DisposeSteamVR(VRMode); - - MovementSystem.Instance.canMove = true; - BodySystem.TrackingEnabled = true; - - yield - return null; - isAttemptingSwitch = false; - } - - //shitton of try catch below - - private static void InitializeSteamVR(bool isVR) - { - if (isVR) - { - //force SteamVR to fully initialize, this does all and more than what i did with LoadDevice() - SteamVR.Initialize(true); - - //Just to make sure. Game does this natively when entering VR. - SteamVR_Settings.instance.pauseGameWhenDashboardVisible = false; - - //TODO: something needs to be done to reinitialize SteamVR_Input or SteamVR_Actions - //If you restart SteamVR after already have been in VRMode, the steamvr action handles break - //ive tried: - //SteamVR_Input.Initialize(true) - //SteamVR_Actions.PreInitialize() - //Destroying SteamVR_Settings on DesktopMode - //Destroying SteamVR_Behavior on DesktopMode - //Destroying SteamVR_Render on DesktopMode - //Combinations of all of these.. - //Its probably really simple, but I just cannot figure out how. - } - } - - private static void DisposeSteamVR(bool isVR) - { - if (!isVR) - { - //force SteamVR to let go of Chillout - XRSettings.LoadDeviceByName("None"); - XRSettings.enabled = false; - - //destroy [SteamVR] gameobject as next SteamVR.Initialize creates a new one - Object.Destroy(SteamVR_Behaviour.instance.gameObject); - - //what even does this do that is actually important? - SteamVR.SafeDispose(); - } - } - - // shouldn't be that important, right? - private static void CloseMenuElements(bool isVR) - { - if (ViewManager.Instance != null) - { - MelonLogger.Msg("Closed MainMenu Instance."); - ViewManager.Instance.UiStateToggle(false); - } - else - { - MelonLogger.Msg("MainMenu Instance not found!!!"); - } - if (ViewManager.Instance != null) - { - MelonLogger.Msg("Closed QuickMenu Instance."); - CVR_MenuManager.Instance.ToggleQuickMenu(false); - } - else - { - MelonLogger.Msg("QuickMenu Instance not found!!!"); - } - - //disable input during switch - CVRInputManager.Instance.inputEnabled = false; - } - - private static void SetMetaPort(bool isVR) - { - try - { - MelonLogger.Msg($"Set MetaPort isUsingVr to {isVR}."); - MetaPort.Instance.isUsingVr = isVR; - } - catch (Exception) - { - MelonLogger.Error("Setting MetaPort isUsingVr failed. Is MetaPort.Instance invalid?"); - MelonLogger.Msg("MetaPort.Instance: " + MetaPort.Instance); - throw; - } - } - - private static void SetPlayerSetup(bool isVR) - { - try - { - MelonLogger.Msg($"Set PlayerSetup instance to {isVR}."); - PlayerSetup.Instance._inVr = isVR; - } - catch (Exception) - { - MelonLogger.Error("Setting PlayerSetup _inVr failed. Is PlayerSetup.Instance invalid?"); - MelonLogger.Msg("PlayerSetup.Instance: " + PlayerSetup.Instance); - throw; - } - } - - private static void SwitchActiveCameraRigs(bool isVR) - { - try - { - MelonLogger.Msg("Switched active camera rigs."); - PlayerSetup.Instance.desktopCameraRig.SetActive(!isVR); - PlayerSetup.Instance.vrCameraRig.SetActive(isVR); - } - catch (Exception) - { - MelonLogger.Error("Error switching active cameras. Are the camera rigs invalid?"); - MelonLogger.Msg("PlayerSetup.Instance.desktopCameraRig: " + PlayerSetup.Instance.desktopCameraRig); - MelonLogger.Msg("PlayerSetup.Instance.vrCameraRig: " + PlayerSetup.Instance.vrCameraRig); - throw; - } - } - - private static void RepositionCohtmlHud(bool isVR) - { - try - { - MelonLogger.Msg("Parented CohtmlHud to active camera."); - CohtmlHud.Instance.gameObject.transform.parent = isVR ? PlayerSetup.Instance.vrCamera.transform : PlayerSetup.Instance.desktopCamera.transform; - - //sets hud position, rotation, ~~and scale~~ based on MetaPort isUsingVr - CVRTools.ConfigureHudAffinity(); - CohtmlHud.Instance.gameObject.transform.localScale = new Vector3(1.2f, 1f, 1.2f); - } - catch (Exception) - { - MelonLogger.Error("Error parenting CohtmlHud to active camera. Is CohtmlHud.Instance invalid?"); - MelonLogger.Msg("CohtmlHud.Instance: " + CohtmlHud.Instance); - throw; - } - } - - private static void ReloadCVRInputManager() - { - try - { - MelonLogger.Msg("Set CVRInputManager reload to True. Input should reload next frame..."); - CVRInputManager.Instance.reload = true; - //just in case - CVRInputManager.Instance.inputEnabled = true; - CVRInputManager.Instance.blockedByUi = false; - //sometimes head can get stuck, so just in case - CVRInputManager.Instance.independentHeadToggle = false; - //just nice to load into desktop with idle gesture - CVRInputManager.Instance.gestureLeft = 0f; - CVRInputManager.Instance.gestureLeftRaw = 0f; - CVRInputManager.Instance.gestureRight = 0f; - CVRInputManager.Instance.gestureRightRaw = 0f; - } - catch (Exception) - { - MelonLogger.Error("CVRInputManager reload failed. Is CVRInputManager.Instance invalid?"); - MelonLogger.Msg("CVRInputManager.Instance: " + CVRInputManager.Instance); - throw; - } - } - - //every nameplate canvas uses CameraFacingObject :stare: - private static void UpdateCameraFacingObject() - { - try - { - MelonLogger.Msg("Updating all CameraFacingObject scripts to face new camera. (this fixes nameplates)"); - CameraFacingObject[] camfaceobjs = Object.FindObjectsOfType(); - - for (int i = 0; i < camfaceobjs.Count(); i++) - { - camfaceobjs[i].m_Camera = PlayerSetup.Instance.GetActiveCamera().GetComponent(); - } - } - catch (Exception) - { - MelonLogger.Error("Error updating CameraFacingObject objects! Nameplates will be wonk..."); - throw; - } - } - - private static void UpdateHudOperations(bool isVR) - { - try - { - MelonLogger.Msg("Set HudOperations worldLoadingItem and worldLoadStatus to their respective Desktop/Vr parent."); - HudOperations.Instance.worldLoadingItem = isVR ? HudOperations.Instance.worldLoadingItemVr : HudOperations.Instance.worldLoadingItemDesktop; - HudOperations.Instance.worldLoadStatus = isVR ? HudOperations.Instance.worldLoadStatusVr : HudOperations.Instance.worldLoadStatusDesktop; - } - catch (Exception) - { - MelonLogger.Error("Error updating HudOperations LoadingItem & LoadStatus!"); - throw; - } - } - - private static void DisableMirrorCanvas() - { - try - { - //tell the game we are in mirror mode so itll disable it (if enabled) - PortableCamera.Instance.mode = MirroringMode.Mirror; - PortableCamera.Instance.ChangeMirroring(); - } - catch (Exception) - { - MelonLogger.Error("Error updating CVRGestureRecognizer camera!"); - throw; - } - } - - private static void UpdateGestureReconizerCam() - { - try - { - MelonLogger.Msg("Set GestureReconizerCam camera to active camera."); - Traverse.Create(CVRGestureRecognizer.Instance).Field("_camera").SetValue(PlayerSetup.Instance.GetActiveCamera().GetComponent()); - } - catch (Exception) - { - MelonLogger.Error("Error updating CVRGestureRecognizer camera!"); - throw; - } - } - - private static void SwitchPickupOrigins() - { - try - { - MelonLogger.Msg("Switched pickup origins."); - CVRPickupObjectTracker[] pickups = Object.FindObjectsOfType(); - - for (int i = 0; i < pickups.Count(); i++) - { - pickups[i].OnSwitch(); - } - } - catch (Exception) - { - MelonLogger.Error("Error switching pickup origins!"); - throw; - } + if (!DesktopVRSwitchHelper.Instance) return; + DesktopVRSwitchHelper.Instance.SettingTimedErrorCatch = m_entryTimedErrorCatch.Value; + DesktopVRSwitchHelper.Instance.SettingTimedErrorTimer = m_entryTimedErrorTimer.Value; } } \ No newline at end of file diff --git a/DesktopVRSwitch/Patches/ReferenceCameraFix.cs b/DesktopVRSwitch/Patches/ReferenceCameraFix.cs new file mode 100644 index 0000000..d1bc27b --- /dev/null +++ b/DesktopVRSwitch/Patches/ReferenceCameraFix.cs @@ -0,0 +1,127 @@ +using ABI.CCK.Components; +using ABI_RC.Core.Base; +using ABI_RC.Core.Player; +using ABI_RC.Core.Savior; +using Aura2API; +using BeautifyEffect; +using HarmonyLib; +using UnityEngine; +using UnityEngine.AzureSky; +using UnityEngine.Rendering.PostProcessing; +using Object = UnityEngine.Object; + +namespace DesktopVRSwitch.Patches; + +[HarmonyPatch] +internal class ReferenceCameraFix +{ + [HarmonyPostfix] + [HarmonyPatch(typeof(CVRWorld), "SetDefaultCamValues")] + private static void CVRWorld_SetDefaultCamValues_Postfix(ref CVRWorld __instance) + { + Camera active; + Camera nonActive; + if (MetaPort.Instance.isUsingVr) + { + active = PlayerSetup.Instance.vrCamera.GetComponent(); + nonActive = PlayerSetup.Instance.desktopCamera.GetComponent(); + } + else + { + active = PlayerSetup.Instance.desktopCamera.GetComponent(); + nonActive = PlayerSetup.Instance.vrCamera.GetComponent(); + } + CopyActiveCamera(active, nonActive); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(CVRWorld), "CopyRefCamValues")] + private static void CVRWorld_CopyRefCamValues_Postfix(ref CVRWorld __instance) + { + Camera active; + Camera nonActive; + if (MetaPort.Instance.isUsingVr) + { + active = PlayerSetup.Instance.vrCamera.GetComponent(); + nonActive = PlayerSetup.Instance.desktopCamera.GetComponent(); + } + else + { + active = PlayerSetup.Instance.desktopCamera.GetComponent(); + nonActive = PlayerSetup.Instance.vrCamera.GetComponent(); + } + CopyActiveCamera(active, nonActive); + } + + private static void CopyActiveCamera(Camera activeCamera, Camera inactiveCamera) + { + //steal basic settings + inactiveCamera.farClipPlane = activeCamera.farClipPlane; + inactiveCamera.nearClipPlane = activeCamera.nearClipPlane; + inactiveCamera.cullingMask = activeCamera.cullingMask; + inactiveCamera.depthTextureMode = activeCamera.depthTextureMode; + + //steal post processing if added + PostProcessLayer ppLayerActive = activeCamera.GetComponent(); + PostProcessLayer ppLayerNonActive = inactiveCamera.GetComponent(); + if (ppLayerActive != null && ppLayerNonActive != null) + { + ppLayerNonActive.enabled = ppLayerActive.enabled; + ppLayerNonActive.volumeLayer = ppLayerActive.volumeLayer; + } + + //what even is this aura camera stuff + AuraCamera auraActive = activeCamera.GetComponent(); + AuraCamera auraNonActive = inactiveCamera.AddComponentIfMissing(); + if (auraActive != null && auraNonActive != null) + { + auraNonActive.enabled = auraActive.enabled; + auraNonActive.frustumSettings = auraActive.frustumSettings; + } + else + { + auraNonActive.enabled = false; + } + + //flare layer thing? the sun :_:_:_:_:_: + FlareLayer flareActive = activeCamera.GetComponent(); + FlareLayer flareNonActive = inactiveCamera.AddComponentIfMissing(); + if (flareActive != null && flareNonActive != null) + { + flareNonActive.enabled = flareActive.enabled; + } + else + { + flareNonActive.enabled = false; + } + + //set correct farclipplane so effect is correct on switching world after switch + PlayerSetup.Instance.transitionEffectVr.material.SetFloat("ClippingPlane", activeCamera.farClipPlane); + PlayerSetup.Instance.transitionEffectDesktop.material.SetFloat("ClippingPlane", activeCamera.farClipPlane); + + //and now what the fuck is fog scattering + AzureFogScattering azureFogActive = activeCamera.GetComponent(); + AzureFogScattering azureFogNonActive = inactiveCamera.AddComponentIfMissing(); + if (azureFogActive != null && azureFogNonActive != null) + { + azureFogNonActive.fogScatteringMaterial = azureFogActive.fogScatteringMaterial; + } + else + { + Object.Destroy(inactiveCamera.GetComponent()); + } + + //why is there so many thingsssssssss + Beautify beautifyActive = activeCamera.GetComponent(); + Beautify beautifyNonActive = inactiveCamera.AddComponentIfMissing(); + if (beautifyActive != null && beautifyNonActive != null) + { + beautifyNonActive.quality = beautifyActive.quality; + beautifyNonActive.profile = beautifyActive.profile; + } + else + { + Object.Destroy(inactiveCamera.gameObject.GetComponent()); + } + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Properties/AssemblyInfo.cs b/DesktopVRSwitch/Properties/AssemblyInfo.cs index 03ba712..b051b24 100644 --- a/DesktopVRSwitch/Properties/AssemblyInfo.cs +++ b/DesktopVRSwitch/Properties/AssemblyInfo.cs @@ -25,6 +25,6 @@ using System.Reflection; namespace DesktopVRSwitch.Properties; internal static class AssemblyInfoParams { - public const string Version = "2.0.0"; + public const string Version = "3.0.0"; public const string Author = "NotAKidoS"; } \ No newline at end of file diff --git a/DesktopVRSwitch/UIExpansionKitAddon.cs b/DesktopVRSwitch/UIExpansionKitAddon.cs new file mode 100644 index 0000000..de9e9d7 --- /dev/null +++ b/DesktopVRSwitch/UIExpansionKitAddon.cs @@ -0,0 +1,14 @@ +using System.Runtime.CompilerServices; +using UIExpansionKit.API; + +namespace DesktopVRSwitch; +public static class UiExtensionsAddon +{ + [MethodImpl(MethodImplOptions.NoInlining)] + public static void Init() + { + var settings = ExpansionKitApi.GetSettingsCategory(DesktopVRSwitch.SettingsCategory); + settings.AddSimpleButton("Switch VRMode", SwitchModeButton); + } + internal static void SwitchModeButton() => DesktopVRSwitchHelper.Instance.SwitchMode(true); +} \ No newline at end of file diff --git a/DesktopVRSwitch/format.json b/DesktopVRSwitch/format.json index 6f77ed3..df073eb 100644 --- a/DesktopVRSwitch/format.json +++ b/DesktopVRSwitch/format.json @@ -1,9 +1,9 @@ { - "_id": -1, + "_id": 103, "name": "DesktopVRSwitch", - "modversion": "2.0.0", - "gameversion": "2022r168", - "loaderversion": "0.5.4", + "modversion": "3.0.0", + "gameversion": "2022r169p1", + "loaderversion": "0.5.7", "modtype": "Mod", "author": "NotAKidoS", "description": "Allows you to switch between Desktop and VR with a keybind.\n**Press Control + F6 to switch.**\n\nWhile this mod is a nice convienence feature to have access to, not every chillout system or mod is built to support it. I cannot possibly cover every edge case or mitigate issues with every mod. **Use at your own discretion.**", @@ -16,8 +16,8 @@ "requirements": [ "None" ], - "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/r2/DesktopVRSwitch.dll", + "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/r3/DesktopVRSwitch.dll", "sourcelink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/", - "changelog": "Initial Release", + "changelog": "Initial CVRMG Release", "embedcolor": "3498db" } \ No newline at end of file From 68716a912d3214e6f8a3871497723887ee4f490b Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Fri, 20 Jan 2023 02:56:13 -0600 Subject: [PATCH 22/42] fix AMT compatability, fix error spam Avatar Motion Tweaker looks for CheckVR bool instead of MetaPort. Only center & disable VRIK on avatar if it is not actively loading. --- DesktopVRSwitch/DesktopVRSwitchHelper.cs | 33 +++++++++++++++++++----- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/DesktopVRSwitch/DesktopVRSwitchHelper.cs b/DesktopVRSwitch/DesktopVRSwitchHelper.cs index 72c873c..5c022ce 100644 --- a/DesktopVRSwitch/DesktopVRSwitchHelper.cs +++ b/DesktopVRSwitch/DesktopVRSwitchHelper.cs @@ -79,12 +79,16 @@ public class DesktopVRSwitchHelper : MonoBehaviour public void LateUpdate() { if (!isAttemptingSwitch) return; - BodySystem.TrackingEnabled = false; - BodySystem.TrackingPositionWeight = 0f; - PlayerSetup.Instance._avatar.transform.position = avatarWorldPos; - PlayerSetup.Instance._avatar.transform.rotation = avatarWorldRot; - MovementSystem.Instance.TeleportToPosRot(avatarWorldPos, avatarWorldRot, false); - MovementSystem.Instance.UpdateColliderCenter(avatarWorldPos); + + if (!PlayerSetup.Instance.avatarIsLoading && PlayerSetup.Instance._avatar != null) + { + BodySystem.TrackingEnabled = false; + BodySystem.TrackingPositionWeight = 0f; + PlayerSetup.Instance._avatar.transform.position = avatarWorldPos; + PlayerSetup.Instance._avatar.transform.rotation = avatarWorldRot; + MovementSystem.Instance.TeleportToPosRot(avatarWorldPos, avatarWorldRot, false); + MovementSystem.Instance.UpdateColliderCenter(avatarWorldPos); + } } internal static IEnumerator AttemptPlatformSwitch(bool forceMode = false) @@ -113,6 +117,7 @@ public class DesktopVRSwitchHelper : MonoBehaviour yield return new WaitForEndOfFrame(); + SetCheckVR(VRMode); SetMetaPort(VRMode); //reset rich presence @@ -256,6 +261,22 @@ public class DesktopVRSwitchHelper : MonoBehaviour throw; } } + + internal static void SetCheckVR(bool isVR) + { + try + { + MelonLogger.Msg($"Set CheckVR hasVrDeviceLoaded to {isVR}."); + CheckVR.Instance.hasVrDeviceLoaded = isVR; + } + catch + { + MelonLogger.Error("Setting CheckVR hasVrDeviceLoaded failed. Is CheckVR.Instance invalid?"); + MelonLogger.Msg("CheckVR.Instance: " + CheckVR.Instance); + throw; + } + } + internal static void SetMetaPort(bool isVR) { try From db83ce8348e5f714521e5b577f0f4b3c338c3228 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Fri, 20 Jan 2023 03:00:59 -0600 Subject: [PATCH 23/42] buimp --- DesktopVRSwitch/DesktopVRSwitchHelper.cs | 3 --- DesktopVRSwitch/Main.cs | 18 +----------------- DesktopVRSwitch/Properties/AssemblyInfo.cs | 2 +- 3 files changed, 2 insertions(+), 21 deletions(-) diff --git a/DesktopVRSwitch/DesktopVRSwitchHelper.cs b/DesktopVRSwitch/DesktopVRSwitchHelper.cs index 5c022ce..ee7949d 100644 --- a/DesktopVRSwitch/DesktopVRSwitchHelper.cs +++ b/DesktopVRSwitch/DesktopVRSwitchHelper.cs @@ -6,11 +6,8 @@ using ABI_RC.Core.Savior; using ABI_RC.Core.UI; using ABI_RC.Core.Util.Object_Behaviour; using ABI_RC.Systems.Camera; -using ABI_RC.Systems.IK; using ABI_RC.Systems.IK.SubSystems; -using ABI_RC.Systems.IK.TrackingModules; using ABI_RC.Systems.MovementSystem; -using ABI_RC.Core.Networking; using DesktopVRSwitch.Patches; using HarmonyLib; using MelonLoader; diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index 9d69fba..a6ca2f9 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -1,21 +1,5 @@ -using ABI_RC.Core; -using ABI_RC.Core.EventSystem; -using ABI_RC.Core.InteractionSystem; -using ABI_RC.Core.Player; -using ABI_RC.Core.Savior; -using ABI_RC.Core.UI; -using ABI_RC.Core.Util.Object_Behaviour; -using ABI_RC.Systems.Camera; -using ABI_RC.Systems.IK.SubSystems; -using ABI_RC.Systems.MovementSystem; -using DesktopVRSwitch.Patches; -using HarmonyLib; +using ABI_RC.Core.Player; using MelonLoader; -using System.Collections; -using UnityEngine; -using UnityEngine.XR; -using Valve.VR; -using Object = UnityEngine.Object; //tell the game to change VRMode/DesktopMode for Steam/Discord presence //RichPresence.PopulatePresence(); diff --git a/DesktopVRSwitch/Properties/AssemblyInfo.cs b/DesktopVRSwitch/Properties/AssemblyInfo.cs index b051b24..743b703 100644 --- a/DesktopVRSwitch/Properties/AssemblyInfo.cs +++ b/DesktopVRSwitch/Properties/AssemblyInfo.cs @@ -25,6 +25,6 @@ using System.Reflection; namespace DesktopVRSwitch.Properties; internal static class AssemblyInfoParams { - public const string Version = "3.0.0"; + public const string Version = "3.0.5"; public const string Author = "NotAKidoS"; } \ No newline at end of file From 8a3523539b631d220bc42958443082103dcfa3c6 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Thu, 9 Feb 2023 23:01:14 -0600 Subject: [PATCH 24/42] Update README.md --- README.md | 20 +++----------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index a3b6b7d..4137184 100644 --- a/README.md +++ b/README.md @@ -34,22 +34,8 @@ https://user-images.githubusercontent.com/37721153/192128515-5630f47b-63ed-45c5- Here is the block of text where I tell you this mod is not affiliated or endorsed by ABI. https://documentation.abinteractive.net/official/legal/tos/#7-modding-our-games -> I am not affiliated with ABI in any official capacity, these mods are not endorsed or outright permitted by ABI and are subject to scrutiny. +> This mod is an independent creation and is not affiliated with, supported by or approved by Alpha Blend Interactive. -> Neither I nor these mods are in any way affiliated with Alpha Blend Interactive and/or ChilloutVR. Using these modifications might cause issues with the performance, security or stability of the game. Use at your own risk. +> Use of this mod is done so at the user's own risk and the creator cannot be held responsible for any issues arising from its use. -> Any modifications that are not approved can get your ABI account terminated and such this modification is following the "modding guidelines" at the best it could be. -> They reserve the right to punish users using my mod. -> If you are scared of using modifications in your game do not install mods. - -> I do not affiliate ABI and the mod is not supported by ABI. - -> Me and this modification are in no affiliation with ABI and not supported by ABI. - -> This mod is not affiliated with Alpha Blend Interactive. The mod comes with no warranty. Use at your own risk, as I am not responsible for any misuse. - -> I'm not affiliated with Alpha Blend Interactive and this mod is not officially supported by the game. - -> When releasing mods to the public, it is required to state, that the mod authors and modification are in no affiliation with ABI and not supported by ABI. :trollface: - -> i ran out of places to steal disclaimers from +> To the best of my knowledge, I have adhered to the Modding Guidelines established by Alpha Blend Interactive. From 1e636e3395d8fcabadb02d194c40ddc9eeef3623 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Fri, 17 Feb 2023 06:10:49 -0600 Subject: [PATCH 25/42] backport --- DesktopVRSwitch/DesktopVRSwitch.cs | 125 +++++++++++++ DesktopVRSwitch/DesktopVRSwitch.csproj | 4 + DesktopVRSwitch/DesktopVRSwitch.sln | 14 +- DesktopVRSwitch/HarmonyPatches.cs | 92 ++++++++++ DesktopVRSwitch/Main.cs | 37 ++++ .../Patches/CVRPickupObjectTracker.cs | 32 ++++ .../Patches/CameraFacingObjectTracker.cs | 24 +++ DesktopVRSwitch/Patches/IKSystemTracker.cs | 57 ++++++ .../Patches/MovementSystemTracker.cs | 39 ++++ .../Patches/ReferenceCameraPatch.cs | 91 ++++++++++ .../Patches/VRModeSwitchTracker.cs | 33 ++++ DesktopVRSwitch/Properties/AssemblyInfo.cs | 22 +++ DesktopVRSwitch/TryCatchHell.cs | 167 ++++++++++++++++++ 13 files changed, 732 insertions(+), 5 deletions(-) create mode 100644 DesktopVRSwitch/DesktopVRSwitch.cs create mode 100644 DesktopVRSwitch/HarmonyPatches.cs create mode 100644 DesktopVRSwitch/Patches/CameraFacingObjectTracker.cs create mode 100644 DesktopVRSwitch/Patches/IKSystemTracker.cs create mode 100644 DesktopVRSwitch/Patches/MovementSystemTracker.cs create mode 100644 DesktopVRSwitch/Patches/ReferenceCameraPatch.cs create mode 100644 DesktopVRSwitch/Patches/VRModeSwitchTracker.cs create mode 100644 DesktopVRSwitch/TryCatchHell.cs diff --git a/DesktopVRSwitch/DesktopVRSwitch.cs b/DesktopVRSwitch/DesktopVRSwitch.cs new file mode 100644 index 0000000..593d475 --- /dev/null +++ b/DesktopVRSwitch/DesktopVRSwitch.cs @@ -0,0 +1,125 @@ +using NAK.Melons.DesktopVRSwitch.Patches; +using System.Collections; +using UnityEngine; +using UnityEngine.XR; +using Valve.VR; + +namespace NAK.Melons.DesktopVRSwitch; + +public class DesktopVRSwitch : MonoBehaviour +{ + //Settings + public bool _reloadLocalAvatar = true; + + //Internal Stuff + private bool _switchInProgress = false; + + void Start() + { + //do not pause game, this breaks dynbones & trackers + SteamVR_Settings.instance.pauseGameWhenDashboardVisible = false; + } + + void Update() + { + if (Input.GetKeyDown(KeyCode.F6) && Input.GetKey(KeyCode.LeftControl)) + { + SwitchXRMode(); + } + } + + public void SwitchXRMode() + { + if (_switchInProgress) return; + if (!IsInXR()) + { + StartCoroutine(StartXRSystem()); + } + else + { + StartCoroutine(StopXR()); + } + } + + public bool IsInXR() => XRSettings.enabled; + + private IEnumerator StartXRSystem() + { + BeforeXRModeSwitch(true); + XRSettings.LoadDeviceByName("OpenVR"); + yield return null; + if (string.IsNullOrEmpty(XRSettings.loadedDeviceName)) + { + DesktopVRSwitchMod.Logger.Error("Initializing VR Failed. Is there no VR device connected?"); + } + else + { + DesktopVRSwitchMod.Logger.Msg("Starting SteamVR..."); + XRSettings.enabled = true; + //force steamvr to reinitialize input + //this does SteamVR_Input.actionSets[0].Activate() for us (we deactivate in StopVR()) + //but only if SteamVR_Settings.instance.activateFirstActionSetOnStart is enabled + //which in ChilloutVR, it is, because all those settings are default + SteamVR_Input.Initialize(true); + yield return null; + AfterXRModeSwitch(true); + } + yield break; + } + + private IEnumerator StopXR() + { + BeforeXRModeSwitch(false); + yield return null; + if (!string.IsNullOrEmpty(XRSettings.loadedDeviceName)) + { + //deactivate the action set so SteamVR_Input.Initialize can reactivate + SteamVR_Input.actionSets[0].Deactivate(SteamVR_Input_Sources.Any); + SteamVR.SafeDispose(); //idk + XRSettings.LoadDeviceByName(""); + XRSettings.enabled = false; + yield return null; + AfterXRModeSwitch(false); + } + yield break; + } + + //one frame before switch attempt + public void BeforeXRModeSwitch(bool enterXR) + { + //let tracked objects know we are attempting to switch + VRModeSwitchTracker.PreVRModeSwitch(enterXR); + } + + //one frame after switch attempt + public void AfterXRModeSwitch(bool enterXR) + { + //reset physics time to Desktop default + Time.fixedDeltaTime = 0.02f; + + //these two must come first + TryCatchHell.SetCheckVR(enterXR); + TryCatchHell.SetMetaPort(enterXR); + + //the bulk of funni changes + TryCatchHell.RepositionCohtmlHud(enterXR); + TryCatchHell.UpdateHudOperations(enterXR); + TryCatchHell.DisableMirrorCanvas(); + TryCatchHell.SwitchActiveCameraRigs(enterXR); + TryCatchHell.ResetCVRInputManager(); + TryCatchHell.UpdateRichPresence(); + TryCatchHell.UpdateGestureReconizerCam(); + + //let tracked objects know we switched + VRModeSwitchTracker.PostVRModeSwitch(enterXR); + + //reload avatar by default, optional for debugging + if (_reloadLocalAvatar) + { + TryCatchHell.ReloadLocalAvatar(); + } + + _switchInProgress = false; + } +} + diff --git a/DesktopVRSwitch/DesktopVRSwitch.csproj b/DesktopVRSwitch/DesktopVRSwitch.csproj index adb74e4..57841c7 100644 --- a/DesktopVRSwitch/DesktopVRSwitch.csproj +++ b/DesktopVRSwitch/DesktopVRSwitch.csproj @@ -43,7 +43,11 @@ ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Unity.Postprocessing.Runtime.dll +<<<<<<< Updated upstream ..\..\..\DakyModsCVR\ManagedLibs\Unity.TextMeshPro.dll +======= + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Unity.TextMeshPro.dll +>>>>>>> Stashed changes ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.AnimationModule.dll diff --git a/DesktopVRSwitch/DesktopVRSwitch.sln b/DesktopVRSwitch/DesktopVRSwitch.sln index 758488c..8d77157 100644 --- a/DesktopVRSwitch/DesktopVRSwitch.sln +++ b/DesktopVRSwitch/DesktopVRSwitch.sln @@ -3,7 +3,11 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.2.32630.192 MinimumVisualStudioVersion = 10.0.40219.1 +<<<<<<< Updated upstream Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DesktopVRSwitch", "DesktopVRSwitch.csproj", "{4008E6D1-32F9-449B-8820-80ACF0ED8233}" +======= +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DesktopVRSwitch", "DesktopVRSwitch.csproj", "{D8B326EF-AC8E-4D71-AFC9-0658831B059B}" +>>>>>>> Stashed changes EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -11,15 +15,15 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {4008E6D1-32F9-449B-8820-80ACF0ED8233}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4008E6D1-32F9-449B-8820-80ACF0ED8233}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4008E6D1-32F9-449B-8820-80ACF0ED8233}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4008E6D1-32F9-449B-8820-80ACF0ED8233}.Release|Any CPU.Build.0 = Release|Any CPU + {D8B326EF-AC8E-4D71-AFC9-0658831B059B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D8B326EF-AC8E-4D71-AFC9-0658831B059B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D8B326EF-AC8E-4D71-AFC9-0658831B059B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D8B326EF-AC8E-4D71-AFC9-0658831B059B}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {3C86465A-87F5-49EF-915C-5B5F568A8815} + SolutionGuid = {9F6A1F88-B3D1-46F3-9370-9DDAE1F707C3} EndGlobalSection EndGlobal diff --git a/DesktopVRSwitch/HarmonyPatches.cs b/DesktopVRSwitch/HarmonyPatches.cs new file mode 100644 index 0000000..6790699 --- /dev/null +++ b/DesktopVRSwitch/HarmonyPatches.cs @@ -0,0 +1,92 @@ +using ABI.CCK.Components; +using ABI_RC.Core.Player; +using ABI_RC.Core.Savior; +using ABI_RC.Core.Util.Object_Behaviour; +using ABI_RC.Systems.IK; +using ABI_RC.Systems.MovementSystem; +using HarmonyLib; +using NAK.Melons.DesktopVRSwitch.Patches; +using UnityEngine; + +namespace NAK.Melons.DesktopVRSwitch.HarmonyPatches; + +internal class PlayerSetupPatches +{ + [HarmonyPostfix] + [HarmonyPatch(typeof(PlayerSetup), "Start")] + private static void Postfix_PlayerSetup_Start(ref PlayerSetup __instance) + { + if (CheckVR.Instance != null) + { + CheckVR.Instance.gameObject.AddComponent(); + return; + } + __instance.gameObject.AddComponent(); + DesktopVRSwitchMod.Logger.Error("CheckVR not found. Reverting to fallback method. This should never happen!"); + } +} + +internal class MovementSystemPatches +{ + [HarmonyPostfix] + [HarmonyPatch(typeof(MovementSystem), "Start")] + private static void Postfix_MovementSystem_Start(ref MovementSystem __instance) + { + __instance.gameObject.AddComponent(); + } +} + +internal class CVRPickupObjectPatches +{ + [HarmonyPrefix] + [HarmonyPatch(typeof(CVRPickupObject), "Start")] + private static void Prefix_CVRPickupObject_Start(ref CVRPickupObject __instance) + { + if (__instance.gripType == CVRPickupObject.GripType.Free) return; + Transform vrOrigin = __instance.gripOrigin; + Transform desktopOrigin = __instance.gripOrigin.Find("[Desktop]"); + if (vrOrigin != null && desktopOrigin != null) + { + var tracker = __instance.gameObject.AddComponent(); + tracker.pickupObject = __instance; + tracker.storedGripOrigin = (!MetaPort.Instance.isUsingVr ? vrOrigin : desktopOrigin); + } + } +} + +internal class CVRWorldPatches +{ + [HarmonyPostfix] + [HarmonyPatch(typeof(CVRWorld), "SetDefaultCamValues")] + private static void CVRWorld_SetDefaultCamValues_Postfix() + { + ReferenceCameraPatch.OnWorldLoad(); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(CVRWorld), "CopyRefCamValues")] + private static void CVRWorld_CopyRefCamValues_Postfix() + { + ReferenceCameraPatch.OnWorldLoad(); + } +} + +internal class CameraFacingObjectPatches +{ + [HarmonyPostfix] + [HarmonyPatch(typeof(CameraFacingObject), "Start")] + private static void Postfix_CameraFacingObject_Start(ref CameraFacingObject __instance) + { + __instance.gameObject.AddComponent(); + } +} + +internal class IKSystemPatches +{ + [HarmonyPostfix] + [HarmonyPatch(typeof(IKSystem), "Start")] + private static void Postfix_IKSystem_Start(ref IKSystem __instance) + { + __instance.gameObject.AddComponent(); + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index a6ca2f9..092c575 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -1,3 +1,4 @@ +<<<<<<< Updated upstream using ABI_RC.Core.Player; using MelonLoader; @@ -55,5 +56,41 @@ public class DesktopVRSwitch : MelonMod if (!DesktopVRSwitchHelper.Instance) return; DesktopVRSwitchHelper.Instance.SettingTimedErrorCatch = m_entryTimedErrorCatch.Value; DesktopVRSwitchHelper.Instance.SettingTimedErrorTimer = m_entryTimedErrorTimer.Value; +======= +using MelonLoader; + +namespace NAK.Melons.DesktopVRSwitch; + +public class DesktopVRSwitchMod : MelonMod +{ + internal const string SettingsCategory = "DesktopVRSwitch"; + internal static MelonPreferences_Category m_categoryDesktopVRSwitch; + internal static MelonLogger.Instance Logger; + + public override void OnInitializeMelon() + { + Logger = LoggerInstance; + m_categoryDesktopVRSwitch = MelonPreferences.CreateCategory(SettingsCategory); + + ApplyPatches(typeof(HarmonyPatches.PlayerSetupPatches)); + ApplyPatches(typeof(HarmonyPatches.CVRPickupObjectPatches)); + ApplyPatches(typeof(HarmonyPatches.CVRWorldPatches)); + ApplyPatches(typeof(HarmonyPatches.CameraFacingObjectPatches)); + ApplyPatches(typeof(HarmonyPatches.IKSystemPatches)); + ApplyPatches(typeof(HarmonyPatches.MovementSystemPatches)); + } + + private void ApplyPatches(Type type) + { + try + { + HarmonyInstance.PatchAll(type); + } + catch (Exception e) + { + Logger.Msg($"Failed while patching {type.Name}!"); + Logger.Error(e); + } +>>>>>>> Stashed changes } } \ No newline at end of file diff --git a/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs b/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs index 5bb7943..71615cf 100644 --- a/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs +++ b/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs @@ -1,11 +1,15 @@ using ABI.CCK.Components; +<<<<<<< Updated upstream using ABI_RC.Core.Savior; using HarmonyLib; using MelonLoader; +======= +>>>>>>> Stashed changes using UnityEngine; //Thanks Ben! I was scared of transpiler so I reworked a bit... +<<<<<<< Updated upstream namespace DesktopVRSwitch.Patches; [HarmonyPatch] @@ -59,3 +63,31 @@ public class CVRPickupObjectTracker : MonoBehaviour previousGripOrigin.Remove(pickupObject); } } +======= +namespace NAK.Melons.DesktopVRSwitch.Patches; + +public class CVRPickupObjectTracker : MonoBehaviour +{ + public CVRPickupObject pickupObject; + public Transform storedGripOrigin; + + void Start() + { + VRModeSwitchTracker.OnPostVRModeSwitch += PostVRModeSwitch; + } + + void OnDestroy() + { + VRModeSwitchTracker.OnPostVRModeSwitch -= PostVRModeSwitch; + } + + public void PostVRModeSwitch(bool enterXR, Camera activeCamera) + { + if (pickupObject != null) + { + if (pickupObject._controllerRay != null) pickupObject._controllerRay.DropObject(true); + (storedGripOrigin, pickupObject.gripOrigin) = (pickupObject.gripOrigin, storedGripOrigin); + } + } +} +>>>>>>> Stashed changes diff --git a/DesktopVRSwitch/Patches/CameraFacingObjectTracker.cs b/DesktopVRSwitch/Patches/CameraFacingObjectTracker.cs new file mode 100644 index 0000000..b99dd7f --- /dev/null +++ b/DesktopVRSwitch/Patches/CameraFacingObjectTracker.cs @@ -0,0 +1,24 @@ +using ABI_RC.Core.Util.Object_Behaviour; +using UnityEngine; + +namespace NAK.Melons.DesktopVRSwitch.Patches; + +public class CameraFacingObjectTracker : MonoBehaviour +{ + public CameraFacingObject cameraFacingObject; + void Start() + { + cameraFacingObject = GetComponent(); + VRModeSwitchTracker.OnPostVRModeSwitch += PostVRModeSwitch; + } + + void OnDestroy() + { + VRModeSwitchTracker.OnPostVRModeSwitch -= PostVRModeSwitch; + } + + public void PostVRModeSwitch(bool enterXR, Camera activeCamera) + { + cameraFacingObject.m_Camera = activeCamera; + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Patches/IKSystemTracker.cs b/DesktopVRSwitch/Patches/IKSystemTracker.cs new file mode 100644 index 0000000..2bd535d --- /dev/null +++ b/DesktopVRSwitch/Patches/IKSystemTracker.cs @@ -0,0 +1,57 @@ +using ABI_RC.Systems.IK; +using ABI_RC.Systems.IK.SubSystems; +using ABI_RC.Systems.IK.TrackingModules; +using HarmonyLib; +using UnityEngine; +using System.Reflection; + +namespace NAK.Melons.DesktopVRSwitch.Patches; + +public class IKSystemTracker : MonoBehaviour +{ + public IKSystem ikSystem; + public Traverse _traverseModules; + + void Start() + { + ikSystem = GetComponent(); + _traverseModules = Traverse.Create(ikSystem).Field("_trackingModules"); + VRModeSwitchTracker.OnPostVRModeSwitch += PostVRModeSwitch; + } + void OnDestroy() + { + VRModeSwitchTracker.OnPostVRModeSwitch -= PostVRModeSwitch; + } + + public void PostVRModeSwitch(bool enterXR, Camera activeCamera) + { + var _trackingModules = _traverseModules.GetValue>(); + SteamVRTrackingModule openXRTrackingModule = _trackingModules.FirstOrDefault(m => m is SteamVRTrackingModule) as SteamVRTrackingModule; + if (openXRTrackingModule != null) + { + if (enterXR) + { + openXRTrackingModule.ModuleStart(); + } + else + { + //why named destroy when it doesnt ? + openXRTrackingModule.ModuleDestroy(); + } + } + else + { + var steamVRTrackingModule = CreateSteamVRTrackingModule(); + ikSystem.AddTrackingModule(steamVRTrackingModule); + } + } + + //thanks for marking the constructor as internal + private SteamVRTrackingModule CreateSteamVRTrackingModule() + { + var steamVRTrackingModuleType = typeof(SteamVRTrackingModule); + var constructor = steamVRTrackingModuleType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); + var instance = constructor.Invoke(null); + return (SteamVRTrackingModule)instance; + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Patches/MovementSystemTracker.cs b/DesktopVRSwitch/Patches/MovementSystemTracker.cs new file mode 100644 index 0000000..54bfaf6 --- /dev/null +++ b/DesktopVRSwitch/Patches/MovementSystemTracker.cs @@ -0,0 +1,39 @@ +using ABI_RC.Systems.MovementSystem; +using UnityEngine; + +namespace NAK.Melons.DesktopVRSwitch.Patches; + +public class MovementSystemTracker : MonoBehaviour +{ + public MovementSystem movementSystem; + + public Vector3 preSwitchWorldPosition; + public Quaternion preSwitchWorldRotation; + + void Start() + { + movementSystem = GetComponent(); + VRModeSwitchTracker.OnPostVRModeSwitch += PreVRModeSwitch; + VRModeSwitchTracker.OnPostVRModeSwitch += PostVRModeSwitch; + } + + void OnDestroy() + { + VRModeSwitchTracker.OnPostVRModeSwitch -= PreVRModeSwitch; + VRModeSwitchTracker.OnPostVRModeSwitch -= PostVRModeSwitch; + } + + public void PreVRModeSwitch(bool enterXR, Camera activeCamera) + { + preSwitchWorldPosition = movementSystem.rotationPivot.transform.position; + preSwitchWorldRotation = movementSystem.rotationPivot.transform.rotation; + } + + public void PostVRModeSwitch(bool enterXR, Camera activeCamera) + { + //lazy way of correcting Desktop & VR offset issue (game does the maths) + movementSystem.TeleportToPosRot(preSwitchWorldPosition, preSwitchWorldRotation, false); + //recenter desktop collision to player object + if (!enterXR) movementSystem.UpdateColliderCenter(movementSystem.transform.position); + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Patches/ReferenceCameraPatch.cs b/DesktopVRSwitch/Patches/ReferenceCameraPatch.cs new file mode 100644 index 0000000..9681873 --- /dev/null +++ b/DesktopVRSwitch/Patches/ReferenceCameraPatch.cs @@ -0,0 +1,91 @@ +using ABI_RC.Core.Base; +using ABI_RC.Core.Player; +using ABI_RC.Core.Savior; +using Aura2API; +using BeautifyEffect; +using UnityEngine; +using UnityEngine.AzureSky; +using UnityEngine.Rendering.PostProcessing; +using Object = UnityEngine.Object; + +namespace NAK.Melons.DesktopVRSwitch.Patches; + +internal class ReferenceCameraPatch +{ + internal static void OnWorldLoad() + { + Camera activeCamera = (MetaPort.Instance.isUsingVr ? PlayerSetup.Instance.vrCamera : PlayerSetup.Instance.desktopCamera).GetComponent(); + Camera inactiveCamera = (MetaPort.Instance.isUsingVr ? PlayerSetup.Instance.desktopCamera : PlayerSetup.Instance.vrCamera).GetComponent(); + CopyToInactiveCam(activeCamera, inactiveCamera); + } + + internal static void CopyToInactiveCam(Camera activeCam, Camera inactiveCam) + { + DesktopVRSwitchMod.Logger.Msg("Copying active camera settings & components to inactive camera."); + + //steal basic settings + inactiveCam.farClipPlane = activeCam.farClipPlane; + inactiveCam.nearClipPlane = activeCam.nearClipPlane; + inactiveCam.cullingMask = activeCam.cullingMask; + inactiveCam.depthTextureMode = activeCam.depthTextureMode; + + //steal post processing if added + PostProcessLayer ppLayerActiveCam = activeCam.GetComponent(); + PostProcessLayer ppLayerInactiveCam = inactiveCam.AddComponentIfMissing(); + if (ppLayerActiveCam != null && ppLayerInactiveCam != null) + { + ppLayerInactiveCam.enabled = ppLayerActiveCam.enabled; + ppLayerInactiveCam.volumeLayer = ppLayerActiveCam.volumeLayer; + } + + //what even is this aura camera stuff + AuraCamera auraActiveCam = activeCam.GetComponent(); + AuraCamera auraInactiveCam = inactiveCam.AddComponentIfMissing(); + if (auraActiveCam != null && auraInactiveCam != null) + { + auraInactiveCam.enabled = auraActiveCam.enabled; + auraInactiveCam.frustumSettings = auraActiveCam.frustumSettings; + } + else + { + auraInactiveCam.enabled = false; + } + + //flare layer thing? the sun :_:_:_:_:_: + FlareLayer flareActiveCam = activeCam.GetComponent(); + FlareLayer flareInactiveCam = inactiveCam.AddComponentIfMissing(); + if (flareActiveCam != null && flareInactiveCam != null) + { + flareInactiveCam.enabled = flareActiveCam.enabled; + } + else + { + flareInactiveCam.enabled = false; + } + + //and now what the fuck is fog scattering + AzureFogScattering azureFogActiveCam = activeCam.GetComponent(); + AzureFogScattering azureFogInactiveCam = inactiveCam.AddComponentIfMissing(); + if (azureFogActiveCam != null && azureFogInactiveCam != null) + { + azureFogInactiveCam.fogScatteringMaterial = azureFogActiveCam.fogScatteringMaterial; + } + else + { + Object.Destroy(inactiveCam.GetComponent()); + } + + //why is there so many thingsssssssss + Beautify beautifyActiveCam = activeCam.GetComponent(); + Beautify beautifyInactiveCam = inactiveCam.AddComponentIfMissing(); + if (beautifyActiveCam != null && beautifyInactiveCam != null) + { + beautifyInactiveCam.quality = beautifyActiveCam.quality; + beautifyInactiveCam.profile = beautifyActiveCam.profile; + } + else + { + Object.Destroy(inactiveCam.gameObject.GetComponent()); + } + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Patches/VRModeSwitchTracker.cs b/DesktopVRSwitch/Patches/VRModeSwitchTracker.cs new file mode 100644 index 0000000..e6cb2c9 --- /dev/null +++ b/DesktopVRSwitch/Patches/VRModeSwitchTracker.cs @@ -0,0 +1,33 @@ +using ABI_RC.Core.Player; +using UnityEngine; +using UnityEngine.Events; + +namespace NAK.Melons.DesktopVRSwitch.Patches; + +public class VRModeSwitchTracker +{ + public static event UnityAction OnPreVRModeSwitch; + public static event UnityAction OnPostVRModeSwitch; + + public static void PreVRModeSwitch(bool enterXR) + { + TryCatchHell.TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Invoking VRModeSwitchTracker.OnPreVRModeSwitch."); + Camera activeCamera = PlayerSetup.Instance.GetActiveCamera().GetComponent(); + VRModeSwitchTracker.OnPreVRModeSwitch?.Invoke(enterXR, activeCamera); + }, + "Error while invoking VRModeSwitchTracker.OnPreVRModeSwitch. Did someone do a fucky?"); + } + + public static void PostVRModeSwitch(bool enterXR) + { + TryCatchHell.TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Invoking VRModeSwitchTracker.OnPostVRModeSwitch."); + Camera activeCamera = PlayerSetup.Instance.GetActiveCamera().GetComponent(); + VRModeSwitchTracker.OnPostVRModeSwitch?.Invoke(enterXR, activeCamera); + }, + "Error while invoking VRModeSwitchTracker.OnPostVRModeSwitch. Did someone do a fucky?"); + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Properties/AssemblyInfo.cs b/DesktopVRSwitch/Properties/AssemblyInfo.cs index 743b703..2ff0727 100644 --- a/DesktopVRSwitch/Properties/AssemblyInfo.cs +++ b/DesktopVRSwitch/Properties/AssemblyInfo.cs @@ -1,11 +1,17 @@ +<<<<<<< Updated upstream using DesktopVRSwitch.Properties; using MelonLoader; +======= +using MelonLoader; +using NAK.Melons.DesktopVRSwitch.Properties; +>>>>>>> Stashed changes using System.Reflection; [assembly: AssemblyVersion(AssemblyInfoParams.Version)] [assembly: AssemblyFileVersion(AssemblyInfoParams.Version)] [assembly: AssemblyInformationalVersion(AssemblyInfoParams.Version)] +<<<<<<< Updated upstream [assembly: AssemblyTitle(nameof(DesktopVRSwitch))] [assembly: AssemblyCompany(AssemblyInfoParams.Author)] [assembly: AssemblyProduct(nameof(DesktopVRSwitch))] @@ -13,6 +19,15 @@ using System.Reflection; [assembly: MelonInfo( typeof(DesktopVRSwitch.DesktopVRSwitch), nameof(DesktopVRSwitch), +======= +[assembly: AssemblyTitle(nameof(NAK.Melons.DesktopVRSwitch))] +[assembly: AssemblyCompany(AssemblyInfoParams.Author)] +[assembly: AssemblyProduct(nameof(NAK.Melons.DesktopVRSwitch))] + +[assembly: MelonInfo( + typeof(NAK.Melons.DesktopVRSwitch.DesktopVRSwitchMod), + nameof(NAK.Melons.DesktopVRSwitch), +>>>>>>> Stashed changes AssemblyInfoParams.Version, AssemblyInfoParams.Author, downloadLink: "https://github.com/NotAKidOnSteam/DesktopVRSwitch" @@ -22,9 +37,16 @@ using System.Reflection; [assembly: MelonPlatform(MelonPlatformAttribute.CompatiblePlatforms.WINDOWS_X64)] [assembly: MelonPlatformDomain(MelonPlatformDomainAttribute.CompatibleDomains.MONO)] +<<<<<<< Updated upstream namespace DesktopVRSwitch.Properties; internal static class AssemblyInfoParams { public const string Version = "3.0.5"; +======= +namespace NAK.Melons.DesktopVRSwitch.Properties; +internal static class AssemblyInfoParams +{ + public const string Version = "4.2.4"; +>>>>>>> Stashed changes public const string Author = "NotAKidoS"; } \ No newline at end of file diff --git a/DesktopVRSwitch/TryCatchHell.cs b/DesktopVRSwitch/TryCatchHell.cs new file mode 100644 index 0000000..ad3313b --- /dev/null +++ b/DesktopVRSwitch/TryCatchHell.cs @@ -0,0 +1,167 @@ +using ABI_RC.Core; +using ABI_RC.Core.EventSystem; +using ABI_RC.Core.InteractionSystem; +using ABI_RC.Core.Player; +using ABI_RC.Core.Savior; +using ABI_RC.Core.UI; +using ABI_RC.Systems.Camera; +using HarmonyLib; +using UnityEngine; + +namespace NAK.Melons.DesktopVRSwitch; + +internal class TryCatchHell +{ + internal static void TryCatchWrapper(Action action, string errorMsg, params object[] msgArgs) + { + try + { + action(); + } + catch (Exception ex) + { + DesktopVRSwitchMod.Logger.Error(string.Format(errorMsg, msgArgs)); + DesktopVRSwitchMod.Logger.Msg(ex.Message); + } + } + + internal static void SetCheckVR(bool isVR) + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg($"Setting CheckVR hasVrDeviceLoaded to {isVR}."); + CheckVR.Instance.hasVrDeviceLoaded = isVR; + }, + "Setting CheckVR hasVrDeviceLoaded failed."); + } + + internal static void SetMetaPort(bool isVR) + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg($"Setting MetaPort isUsingVr to {isVR}."); + MetaPort.Instance.isUsingVr = isVR; + }, + "Setting MetaPort isUsingVr failed."); + } + + internal static void RepositionCohtmlHud(bool isVR) + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Configuring new hud affinity for CohtmlHud."); + CohtmlHud.Instance.gameObject.transform.parent = isVR ? PlayerSetup.Instance.vrCamera.transform : PlayerSetup.Instance.desktopCamera.transform; + CVRTools.ConfigureHudAffinity(); + CohtmlHud.Instance.gameObject.transform.localScale = new Vector3(1.2f, 1f, 1.2f); + }, + "Error parenting CohtmlHud to active camera."); + } + + internal static void UpdateHudOperations(bool isVR) + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Switching HudOperations worldLoadingItem & worldLoadStatus."); + HudOperations.Instance.worldLoadingItem = isVR ? HudOperations.Instance.worldLoadingItemVr : HudOperations.Instance.worldLoadingItemDesktop; + HudOperations.Instance.worldLoadStatus = isVR ? HudOperations.Instance.worldLoadStatusVr : HudOperations.Instance.worldLoadStatusDesktop; + }, + "Failed switching HudOperations objects."); + } + + internal static void DisableMirrorCanvas() + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Forcing PortableCamera canvas mirroring off."); + //tell the game we are in mirror mode so itll disable it (if enabled) + PortableCamera.Instance.mode = MirroringMode.Mirror; + PortableCamera.Instance.ChangeMirroring(); + }, + "Failed to disable PortableCamera canvas mirroring."); + } + + internal static void SwitchActiveCameraRigs(bool isVR) + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Switching active PlayerSetup camera rigs. Updating Desktop camera FOV."); + PlayerSetup.Instance.desktopCameraRig.SetActive(!isVR); + PlayerSetup.Instance.vrCameraRig.SetActive(isVR); + CVR_DesktopCameraController.UpdateFov(); + //uicamera has script that copies fov from desktop cam + //toggling the cameras on/off resets aspect ratio + //so when rigs switch, that is already handled + }, + "Failed to switch active camera rigs or update Desktop camera FOV."); + } + + internal static void PauseInputInteractions(bool toggle) + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg($"Setting CVRInputManager inputEnabled & CVR_InteractableManager enableInteractions to {!toggle}"); + CVRInputManager.Instance.inputEnabled = !toggle; + CVR_InteractableManager.enableInteractions = !toggle; + }, + "Failed to toggle CVRInputManager inputEnabled & CVR_InteractableManager enableInteractions."); + } + + internal static void ResetCVRInputManager() + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Resetting CVRInputManager inputs."); + //just in case + CVRInputManager.Instance.blockedByUi = false; + //sometimes head can get stuck, so just in case + CVRInputManager.Instance.independentHeadToggle = false; + //just nice to load into desktop with idle gesture + CVRInputManager.Instance.gestureLeft = 0f; + CVRInputManager.Instance.gestureLeftRaw = 0f; + CVRInputManager.Instance.gestureRight = 0f; + CVRInputManager.Instance.gestureRightRaw = 0f; + }, + "Failed to reset CVRInputManager inputs."); + } + + internal static void ReloadLocalAvatar() + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Attempting to reload current local avatar from GUID."); + AssetManagement.Instance.LoadLocalAvatar(MetaPort.Instance.currentAvatarGuid); + }, + "Failed to reload local avatar."); + } + + internal static void UpdateRichPresence() + { + TryCatchWrapper(() => + { + if (MetaPort.Instance.settings.GetSettingsBool("ImplementationRichPresenceDiscordEnabled", true)) + { + DesktopVRSwitchMod.Logger.Msg("Forcing Discord Rich Presence update."); + MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceDiscordEnabled", false); + MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceDiscordEnabled", true); + } + if (MetaPort.Instance.settings.GetSettingsBool("ImplementationRichPresenceSteamEnabled", true)) + { + DesktopVRSwitchMod.Logger.Msg("Forcing Steam Rich Presence update."); + MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceSteamEnabled", false); + MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceSteamEnabled", true); + } + }, + "Failed to update Discord & Steam Rich Presence."); + } + + internal static void UpdateGestureReconizerCam() + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Updating CVRGestureRecognizer _camera to active camera."); + Traverse.Create(CVRGestureRecognizer.Instance).Field("_camera").SetValue(PlayerSetup.Instance.GetActiveCamera().GetComponent()); + }, + "Failed to update CVRGestureRecognizer camera."); + } +} + From 5fd8e3d4d61f904c9da071e20ae2aca9bbdbfbff Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Fri, 17 Feb 2023 06:24:46 -0600 Subject: [PATCH 26/42] backport from experimental --- DesktopVRSwitch/DesktopVRSwitch.cs | 124 +++++ DesktopVRSwitch/DesktopVRSwitch.csproj | 28 +- DesktopVRSwitch/DesktopVRSwitchHelper.cs | 434 ------------------ DesktopVRSwitch/HarmonyPatches.cs | 92 ++++ DesktopVRSwitch/Main.cs | 65 +-- .../Patches/CVRPickupObjectTracker.cs | 60 +-- .../Patches/CameraFacingObjectTracker.cs | 24 + DesktopVRSwitch/Patches/IKSystemTracker.cs | 57 +++ .../Patches/MovementSystemTracker.cs | 39 ++ .../Patches/ReferenceCameraPatch.cs | 91 ++++ .../Patches/VRModeSwitchTracker.cs | 33 ++ DesktopVRSwitch/Properties/AssemblyInfo.cs | 18 +- DesktopVRSwitch/TryCatchHell.cs | 167 +++++++ DesktopVRSwitch/UIExpansionKitAddon.cs | 14 - 14 files changed, 686 insertions(+), 560 deletions(-) create mode 100644 DesktopVRSwitch/DesktopVRSwitch.cs delete mode 100644 DesktopVRSwitch/DesktopVRSwitchHelper.cs create mode 100644 DesktopVRSwitch/HarmonyPatches.cs create mode 100644 DesktopVRSwitch/Patches/CameraFacingObjectTracker.cs create mode 100644 DesktopVRSwitch/Patches/IKSystemTracker.cs create mode 100644 DesktopVRSwitch/Patches/MovementSystemTracker.cs create mode 100644 DesktopVRSwitch/Patches/ReferenceCameraPatch.cs create mode 100644 DesktopVRSwitch/Patches/VRModeSwitchTracker.cs create mode 100644 DesktopVRSwitch/TryCatchHell.cs delete mode 100644 DesktopVRSwitch/UIExpansionKitAddon.cs diff --git a/DesktopVRSwitch/DesktopVRSwitch.cs b/DesktopVRSwitch/DesktopVRSwitch.cs new file mode 100644 index 0000000..7da6495 --- /dev/null +++ b/DesktopVRSwitch/DesktopVRSwitch.cs @@ -0,0 +1,124 @@ +using NAK.Melons.DesktopVRSwitch.Patches; +using System.Collections; +using UnityEngine; +using UnityEngine.XR; +using Valve.VR; + +namespace NAK.Melons.DesktopVRSwitch; + +public class DesktopVRSwitch : MonoBehaviour +{ + //Settings + public bool _reloadLocalAvatar = true; + + //Internal Stuff + private bool _switchInProgress = false; + + void Start() + { + //do not pause game, this breaks dynbones & trackers + SteamVR_Settings.instance.pauseGameWhenDashboardVisible = false; + } + + void Update() + { + if (Input.GetKeyDown(KeyCode.F6) && Input.GetKey(KeyCode.LeftControl)) + { + SwitchVRMode(); + } + } + + public void SwitchVRMode() + { + if (_switchInProgress) return; + if (!IsInVR()) + { + StartCoroutine(StartVRSystem()); + } + else + { + StartCoroutine(StopVR()); + } + } + + public bool IsInVR() => XRSettings.enabled; + + private IEnumerator StartVRSystem() + { + BeforeVRModeSwitch(true); + XRSettings.LoadDeviceByName("OpenVR"); + yield return null; + if (string.IsNullOrEmpty(XRSettings.loadedDeviceName)) + { + DesktopVRSwitchMod.Logger.Error("Initializing VR Failed. Is there no VR device connected?"); + } + else + { + DesktopVRSwitchMod.Logger.Msg("Starting SteamVR..."); + XRSettings.enabled = true; + //force steamvr to reinitialize input + //this does SteamVR_Input.actionSets[0].Activate() for us (we deactivate in StopVR()) + //but only if SteamVR_Settings.instance.activateFirstActionSetOnStart is enabled + //which in ChilloutVR, it is, because all those settings are default + SteamVR_Input.Initialize(true); + yield return null; + AfterVRModeSwitch(true); + } + yield break; + } + + private IEnumerator StopVR() + { + BeforeVRModeSwitch(false); + yield return null; + if (!string.IsNullOrEmpty(XRSettings.loadedDeviceName)) + { + //deactivate the action set so SteamVR_Input.Initialize can reactivate + SteamVR_Input.actionSets[0].Deactivate(SteamVR_Input_Sources.Any); + SteamVR.SafeDispose(); //idk + XRSettings.LoadDeviceByName(""); + XRSettings.enabled = false; + yield return null; + //reset physics time to Desktop default + Time.fixedDeltaTime = 0.02f; + AfterVRModeSwitch(false); + } + yield break; + } + + //one frame before switch attempt + public void BeforeVRModeSwitch(bool enterVR) + { + //let tracked objects know we are attempting to switch + VRModeSwitchTracker.PreVRModeSwitch(enterVR); + } + + //one frame after switch attempt + public void AfterVRModeSwitch(bool enterVR) + { + //these two must come first + TryCatchHell.SetCheckVR(enterVR); + TryCatchHell.SetMetaPort(enterVR); + + //the bulk of funni changes + TryCatchHell.RepositionCohtmlHud(enterVR); + TryCatchHell.UpdateHudOperations(enterVR); + TryCatchHell.DisableMirrorCanvas(); + TryCatchHell.SwitchActiveCameraRigs(enterVR); + TryCatchHell.ResetCVRInputManager(); + TryCatchHell.UpdateRichPresence(); + TryCatchHell.UpdateGestureReconizerCam(); + + //let tracked objects know we switched + VRModeSwitchTracker.PostVRModeSwitch(enterVR); + + //reload avatar by default, optional for debugging + if (_reloadLocalAvatar) + { + TryCatchHell.ReloadLocalAvatar(); + } + + _switchInProgress = false; + } +} + diff --git a/DesktopVRSwitch/DesktopVRSwitch.csproj b/DesktopVRSwitch/DesktopVRSwitch.csproj index adb74e4..0e61fd5 100644 --- a/DesktopVRSwitch/DesktopVRSwitch.csproj +++ b/DesktopVRSwitch/DesktopVRSwitch.csproj @@ -16,19 +16,16 @@ C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Assembly-CSharp.dll - ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Assembly-CSharp-firstpass.dll + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Assembly-CSharp-firstpass.dll - ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Aura2_Core.dll + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Aura2_Core.dll - ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\cohtml.Net.dll + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\cohtml.Net.dll - ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Cohtml.Runtime.dll - - - ..\..\Giamoz\Giamoz\bin\Debug\net472\Giamoz.dll + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Cohtml.Runtime.dll C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\MelonLoader\MelonLoader.dll @@ -37,16 +34,16 @@ C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\SteamVR.dll - ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\Mods\UIExpansionKit.dll + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\Mods\UIExpansionKit.dll - ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Unity.Postprocessing.Runtime.dll + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Unity.Postprocessing.Runtime.dll - ..\..\..\DakyModsCVR\ManagedLibs\Unity.TextMeshPro.dll + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\Unity.TextMeshPro.dll - ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.AnimationModule.dll + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.AnimationModule.dll C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.CoreModule.dll @@ -55,13 +52,16 @@ C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.InputLegacyModule.dll - ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.PhysicsModule.dll + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.PhysicsModule.dll - ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.VRModule.dll + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.VRModule.dll + + + C:\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.VRModule.dll - ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.XRModule.dll + ..\..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\ChilloutVR\ChilloutVR_Data\Managed\UnityEngine.XRModule.dll diff --git a/DesktopVRSwitch/DesktopVRSwitchHelper.cs b/DesktopVRSwitch/DesktopVRSwitchHelper.cs deleted file mode 100644 index ee7949d..0000000 --- a/DesktopVRSwitch/DesktopVRSwitchHelper.cs +++ /dev/null @@ -1,434 +0,0 @@ -using ABI_RC.Core; -using ABI_RC.Core.EventSystem; -using ABI_RC.Core.InteractionSystem; -using ABI_RC.Core.Player; -using ABI_RC.Core.Savior; -using ABI_RC.Core.UI; -using ABI_RC.Core.Util.Object_Behaviour; -using ABI_RC.Systems.Camera; -using ABI_RC.Systems.IK.SubSystems; -using ABI_RC.Systems.MovementSystem; -using DesktopVRSwitch.Patches; -using HarmonyLib; -using MelonLoader; -using System.Collections; -using UnityEngine; -using UnityEngine.XR; -using Valve.VR; -using Object = UnityEngine.Object; - -namespace DesktopVRSwitch; - -public class DesktopVRSwitchHelper : MonoBehaviour -{ - public static DesktopVRSwitchHelper Instance; - - //settings - public bool SettingTimedErrorCatch = true; - public float SettingTimedErrorTimer = 10f; - - //internal shit - internal static bool isAttemptingSwitch = false; - internal static float timedSwitch = 0f; - internal static bool CurrentMode; - internal static Vector3 avatarWorldPos; - internal static Quaternion avatarWorldRot; - - public void SwitchMode(bool isTimedSwitch = false) - { - if (isAttemptingSwitch) return; - - isAttemptingSwitch = true; - MelonCoroutines.Start(AttemptPlatformSwitch()); - - //how long we wait until we assume an error occured - if (isTimedSwitch) - timedSwitch = Time.time + SettingTimedErrorTimer; - } - - public void Start() - { - Instance = this; - } - - public void Update() - { - // assuming CVRInputManager.switchMode button was originally for desktop/vr switching before being left to do literally nothing in rootlogic - if (Input.GetKeyDown(KeyCode.F6) && (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && !isAttemptingSwitch) - { - SwitchMode(true); - } - - if (!isAttemptingSwitch) return; - - //catch if coroutine just decided to not finish... which happens? - if (Time.time > timedSwitch) - { - MelonLogger.Error("Timer exceeded. Something is wrong and coroutine failed partway."); - isAttemptingSwitch = false; - if (SettingTimedErrorCatch) - SwitchMode(); - } - } - - //disables VRIK if it was on the current avatar during switch - //absolutely bruteforcing the stupid vr playspace offset issue - public void LateUpdate() - { - if (!isAttemptingSwitch) return; - - if (!PlayerSetup.Instance.avatarIsLoading && PlayerSetup.Instance._avatar != null) - { - BodySystem.TrackingEnabled = false; - BodySystem.TrackingPositionWeight = 0f; - PlayerSetup.Instance._avatar.transform.position = avatarWorldPos; - PlayerSetup.Instance._avatar.transform.rotation = avatarWorldRot; - MovementSystem.Instance.TeleportToPosRot(avatarWorldPos, avatarWorldRot, false); - MovementSystem.Instance.UpdateColliderCenter(avatarWorldPos); - } - } - - internal static IEnumerator AttemptPlatformSwitch(bool forceMode = false) - { - //forceMode will attempt to backtrack to last working mode (if you dont like the mess, fix it yourself thx) - CurrentMode = forceMode ? CurrentMode : MetaPort.Instance.isUsingVr; - bool VRMode = forceMode ? CurrentMode : !CurrentMode; - - CloseMenuElements(VRMode); - ToggleInputInteractions(false); - DisableMirrorCanvas(); - - //store current player position/rotation to correct VR/Desktop offsets - avatarWorldPos = PlayerSetup.Instance._avatar.transform.position; - avatarWorldRot = PlayerSetup.Instance._avatar.transform.rotation; - - //exit all movement states - MovementSystem.Instance.ChangeCrouch(false); - MovementSystem.Instance.ChangeProne(false); - MovementSystem.Instance.canMove = false; - MovementSystem.Instance.canRot = false; - - //load SteamVR - InitializeSteamVR(VRMode); - - yield - return new WaitForEndOfFrame(); - - SetCheckVR(VRMode); - SetMetaPort(VRMode); - - //reset rich presence - if (MetaPort.Instance.settings.GetSettingsBool("ImplementationRichPresenceDiscordEnabled", true)) - { - MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceDiscordEnabled", false); - MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceDiscordEnabled", true); - } - if (MetaPort.Instance.settings.GetSettingsBool("ImplementationRichPresenceSteamEnabled", true)) - { - MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceSteamEnabled", false); - MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceSteamEnabled", true); - } - - yield - return new WaitForEndOfFrame(); - - SwitchActiveCameraRigs(VRMode); - UpdateCameraFacingObject(); - RepositionCohtmlHud(VRMode); - UpdateHudOperations(VRMode); - SwitchPickupOrigins(); - - yield - return new WaitForEndOfFrame(); - - //needs to come after SetMovementSystem - UpdateGestureReconizerCam(); - - ResetCVRInputManager(); - - //gonna try doing this last - DisposeSteamVR(VRMode); - - ToggleInputInteractions(true); - - //reload current avatar - AssetManagement.Instance.LoadLocalAvatar(MetaPort.Instance.currentAvatarGuid); - - yield return new WaitUntil(() => !PlayerSetup.Instance.avatarIsLoading); - - isAttemptingSwitch = false; - - BodySystem.TrackingEnabled = true; - BodySystem.TrackingPositionWeight = 1f; - MovementSystem.Instance.canMove = true; - MovementSystem.Instance.canRot = true; - - if (!VRMode) - //collision center is set to match headpos in VR, but desktop doesnt reset it - MovementSystem.Instance.UpdateColliderCenter(PlayerSetup.Instance._avatar.transform.position); - - yield - return new WaitForEndOfFrame(); - - //one last teleport to correct VR offset - MovementSystem.Instance.TeleportToPosRot(avatarWorldPos, avatarWorldRot, false); - - yield - return null; - } - - //shitton of try catch below - - internal static void InitializeSteamVR(bool isVR) - { - if (isVR) - { - //force SteamVR to fully initialize, this does all and more than what i did with LoadDevice() - SteamVR.Initialize(true); - - //Just to make sure. Game does this natively when entering VR. - SteamVR_Settings.instance.pauseGameWhenDashboardVisible = false; - - //TODO: something needs to be done to reinitialize SteamVR_Input or SteamVR_Actions - //If you restart SteamVR after already have been in VRMode, the steamvr action handles break - //ive tried: - //SteamVR_Input.Initialize(true) - //SteamVR_Actions.PreInitialize() - //Destroying SteamVR_Settings on DesktopMode - //Destroying SteamVR_Behavior on DesktopMode - //Destroying SteamVR_Render on DesktopMode - //Combinations of all of these.. - //Its probably really simple, but I just cannot figure out how. - } - } - - internal static void DisposeSteamVR(bool isVR) - { - if (!isVR) - { - //force SteamVR to let go of Chillout - XRSettings.LoadDeviceByName("None"); - XRSettings.enabled = false; - - //destroy [SteamVR] gameobject as next SteamVR.Initialize creates a new one - Object.Destroy(SteamVR_Behaviour.instance.gameObject); - - //what even does this do that is actually important? - SteamVR.SafeDispose(); - } - } - - // shouldn't be that important, right? - internal static void CloseMenuElements(bool isVR) - { - if (ViewManager.Instance != null) - { - MelonLogger.Msg("Closed MainMenu Instance."); - ViewManager.Instance.UiStateToggle(false); - } - else - { - MelonLogger.Msg("MainMenu Instance not found!!!"); - } - if (ViewManager.Instance != null) - { - MelonLogger.Msg("Closed QuickMenu Instance."); - CVR_MenuManager.Instance.ToggleQuickMenu(false); - } - else - { - MelonLogger.Msg("QuickMenu Instance not found!!!"); - } - } - - internal static void ToggleInputInteractions(bool toggle) - { - //disable input during switch - try - { - MelonLogger.Msg($"Toggling input & interactions to " + toggle); - CVRInputManager.Instance.inputEnabled = toggle; - CVR_InteractableManager.enableInteractions = toggle; - } - catch - { - MelonLogger.Error("Toggling input & interactions failed. Is something invalid?"); - MelonLogger.Msg("CVRInputManager.Instance: " + CVRInputManager.Instance); - MelonLogger.Msg("CVR_InteractableManager: " + CVR_InteractableManager.enableInteractions); - throw; - } - } - - internal static void SetCheckVR(bool isVR) - { - try - { - MelonLogger.Msg($"Set CheckVR hasVrDeviceLoaded to {isVR}."); - CheckVR.Instance.hasVrDeviceLoaded = isVR; - } - catch - { - MelonLogger.Error("Setting CheckVR hasVrDeviceLoaded failed. Is CheckVR.Instance invalid?"); - MelonLogger.Msg("CheckVR.Instance: " + CheckVR.Instance); - throw; - } - } - - internal static void SetMetaPort(bool isVR) - { - try - { - MelonLogger.Msg($"Set MetaPort isUsingVr to {isVR}."); - MetaPort.Instance.isUsingVr = isVR; - } - catch - { - MelonLogger.Error("Setting MetaPort isUsingVr failed. Is MetaPort.Instance invalid?"); - MelonLogger.Msg("MetaPort.Instance: " + MetaPort.Instance); - throw; - } - } - - internal static void SwitchActiveCameraRigs(bool isVR) - { - try - { - MelonLogger.Msg("Switched active camera rigs."); - PlayerSetup.Instance.desktopCameraRig.SetActive(!isVR); - PlayerSetup.Instance.vrCameraRig.SetActive(isVR); - } - catch - { - MelonLogger.Error("Error switching active cameras. Are the camera rigs invalid?"); - MelonLogger.Msg("PlayerSetup.Instance.desktopCameraRig: " + PlayerSetup.Instance.desktopCameraRig); - MelonLogger.Msg("PlayerSetup.Instance.vrCameraRig: " + PlayerSetup.Instance.vrCameraRig); - throw; - } - } - - internal static void RepositionCohtmlHud(bool isVR) - { - try - { - MelonLogger.Msg("Parented CohtmlHud to active camera."); - CohtmlHud.Instance.gameObject.transform.parent = isVR ? PlayerSetup.Instance.vrCamera.transform : PlayerSetup.Instance.desktopCamera.transform; - - //sets hud position, rotation, ~~and scale~~ based on MetaPort isUsingVr - CVRTools.ConfigureHudAffinity(); - CohtmlHud.Instance.gameObject.transform.localScale = new Vector3(1.2f, 1f, 1.2f); - } - catch - { - MelonLogger.Error("Error parenting CohtmlHud to active camera. Is CohtmlHud.Instance invalid?"); - MelonLogger.Msg("CohtmlHud.Instance: " + CohtmlHud.Instance); - throw; - } - } - - internal static void ResetCVRInputManager() - { - try - { - MelonLogger.Msg("Enabling CVRInputManager inputEnabled & disabling blockedByUi!"); - //CVRInputManager.Instance.reload = true; - //just in case - CVRInputManager.Instance.inputEnabled = true; - CVRInputManager.Instance.blockedByUi = false; - //sometimes head can get stuck, so just in case - CVRInputManager.Instance.independentHeadToggle = false; - //just nice to load into desktop with idle gesture - CVRInputManager.Instance.gestureLeft = 0f; - CVRInputManager.Instance.gestureLeftRaw = 0f; - CVRInputManager.Instance.gestureRight = 0f; - CVRInputManager.Instance.gestureRightRaw = 0f; - } - catch - { - MelonLogger.Error("CVRInputManager reload failed. Is CVRInputManager.Instance invalid?"); - MelonLogger.Msg("CVRInputManager.Instance: " + CVRInputManager.Instance); - throw; - } - } - - //every nameplate canvas uses CameraFacingObject :stare: - internal static void UpdateCameraFacingObject() - { - try - { - MelonLogger.Msg("Updating all CameraFacingObject scripts to face new camera. (this fixes nameplates)"); - CameraFacingObject[] camfaceobjs = Object.FindObjectsOfType(); - - for (int i = 0; i < camfaceobjs.Count(); i++) - { - camfaceobjs[i].m_Camera = PlayerSetup.Instance.GetActiveCamera().GetComponent(); - } - } - catch - { - MelonLogger.Error("Error updating CameraFacingObject objects! Nameplates will be wonk..."); - throw; - } - } - - internal static void UpdateHudOperations(bool isVR) - { - try - { - MelonLogger.Msg("Set HudOperations worldLoadingItem and worldLoadStatus to their respective Desktop/Vr parent."); - HudOperations.Instance.worldLoadingItem = isVR ? HudOperations.Instance.worldLoadingItemVr : HudOperations.Instance.worldLoadingItemDesktop; - HudOperations.Instance.worldLoadStatus = isVR ? HudOperations.Instance.worldLoadStatusVr : HudOperations.Instance.worldLoadStatusDesktop; - } - catch - { - MelonLogger.Error("Error updating HudOperations LoadingItem & LoadStatus!"); - throw; - } - } - - internal static void DisableMirrorCanvas() - { - try - { - //tell the game we are in mirror mode so itll disable it (if enabled) - PortableCamera.Instance.mode = MirroringMode.Mirror; - PortableCamera.Instance.ChangeMirroring(); - } - catch - { - MelonLogger.Error("Error updating CVRGestureRecognizer camera!"); - throw; - } - } - - internal static void UpdateGestureReconizerCam() - { - try - { - MelonLogger.Msg("Set GestureReconizerCam camera to active camera."); - Traverse.Create(CVRGestureRecognizer.Instance).Field("_camera").SetValue(PlayerSetup.Instance.GetActiveCamera().GetComponent()); - } - catch - { - MelonLogger.Error("Error updating CVRGestureRecognizer camera!"); - throw; - } - } - - internal static void SwitchPickupOrigins() - { - try - { - MelonLogger.Msg("Switched pickup origins."); - CVRPickupObjectTracker[] pickups = Object.FindObjectsOfType(); - for (int i = 0; i < pickups.Count(); i++) - { - pickups[i].OnSwitch(); - } - } - catch - { - MelonLogger.Error("Error switching pickup origins!"); - throw; - } - } -} \ No newline at end of file diff --git a/DesktopVRSwitch/HarmonyPatches.cs b/DesktopVRSwitch/HarmonyPatches.cs new file mode 100644 index 0000000..6790699 --- /dev/null +++ b/DesktopVRSwitch/HarmonyPatches.cs @@ -0,0 +1,92 @@ +using ABI.CCK.Components; +using ABI_RC.Core.Player; +using ABI_RC.Core.Savior; +using ABI_RC.Core.Util.Object_Behaviour; +using ABI_RC.Systems.IK; +using ABI_RC.Systems.MovementSystem; +using HarmonyLib; +using NAK.Melons.DesktopVRSwitch.Patches; +using UnityEngine; + +namespace NAK.Melons.DesktopVRSwitch.HarmonyPatches; + +internal class PlayerSetupPatches +{ + [HarmonyPostfix] + [HarmonyPatch(typeof(PlayerSetup), "Start")] + private static void Postfix_PlayerSetup_Start(ref PlayerSetup __instance) + { + if (CheckVR.Instance != null) + { + CheckVR.Instance.gameObject.AddComponent(); + return; + } + __instance.gameObject.AddComponent(); + DesktopVRSwitchMod.Logger.Error("CheckVR not found. Reverting to fallback method. This should never happen!"); + } +} + +internal class MovementSystemPatches +{ + [HarmonyPostfix] + [HarmonyPatch(typeof(MovementSystem), "Start")] + private static void Postfix_MovementSystem_Start(ref MovementSystem __instance) + { + __instance.gameObject.AddComponent(); + } +} + +internal class CVRPickupObjectPatches +{ + [HarmonyPrefix] + [HarmonyPatch(typeof(CVRPickupObject), "Start")] + private static void Prefix_CVRPickupObject_Start(ref CVRPickupObject __instance) + { + if (__instance.gripType == CVRPickupObject.GripType.Free) return; + Transform vrOrigin = __instance.gripOrigin; + Transform desktopOrigin = __instance.gripOrigin.Find("[Desktop]"); + if (vrOrigin != null && desktopOrigin != null) + { + var tracker = __instance.gameObject.AddComponent(); + tracker.pickupObject = __instance; + tracker.storedGripOrigin = (!MetaPort.Instance.isUsingVr ? vrOrigin : desktopOrigin); + } + } +} + +internal class CVRWorldPatches +{ + [HarmonyPostfix] + [HarmonyPatch(typeof(CVRWorld), "SetDefaultCamValues")] + private static void CVRWorld_SetDefaultCamValues_Postfix() + { + ReferenceCameraPatch.OnWorldLoad(); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(CVRWorld), "CopyRefCamValues")] + private static void CVRWorld_CopyRefCamValues_Postfix() + { + ReferenceCameraPatch.OnWorldLoad(); + } +} + +internal class CameraFacingObjectPatches +{ + [HarmonyPostfix] + [HarmonyPatch(typeof(CameraFacingObject), "Start")] + private static void Postfix_CameraFacingObject_Start(ref CameraFacingObject __instance) + { + __instance.gameObject.AddComponent(); + } +} + +internal class IKSystemPatches +{ + [HarmonyPostfix] + [HarmonyPatch(typeof(IKSystem), "Start")] + private static void Postfix_IKSystem_Start(ref IKSystem __instance) + { + __instance.gameObject.AddComponent(); + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index a6ca2f9..4e61e12 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -1,59 +1,36 @@ -using ABI_RC.Core.Player; -using MelonLoader; +using MelonLoader; -//tell the game to change VRMode/DesktopMode for Steam/Discord presence -//RichPresence.PopulatePresence(); +namespace NAK.Melons.DesktopVRSwitch; -//nvm that resets the RichPresence clock- i want people to know how long ive wasted staring at mirror - -namespace DesktopVRSwitch; - -public class DesktopVRSwitch : MelonMod +public class DesktopVRSwitchMod : MelonMod { internal const string SettingsCategory = "DesktopVRSwitch"; internal static MelonPreferences_Category m_categoryDesktopVRSwitch; - internal static MelonPreferences_Entry m_entryTimedErrorCatch; - internal static MelonPreferences_Entry m_entryTimedErrorTimer; + internal static MelonLogger.Instance Logger; public override void OnInitializeMelon() { + Logger = LoggerInstance; m_categoryDesktopVRSwitch = MelonPreferences.CreateCategory(SettingsCategory); - m_entryTimedErrorCatch = m_categoryDesktopVRSwitch.CreateEntry("Timed Error Catch", true, description: "Attempt to switch back if an error is found after n seconds."); - m_entryTimedErrorTimer = m_categoryDesktopVRSwitch.CreateEntry("Timed Error Timer", 10f, description: "Amount of seconds to wait before assuming there was an error."); - m_categoryDesktopVRSwitch.SaveToFile(false); - foreach (var setting in m_categoryDesktopVRSwitch.Entries) - { - setting.OnEntryValueChangedUntyped.Subscribe(OnUpdateSettings); - } - - //UIExpansionKit addon - if (MelonMod.RegisteredMelons.Any(it => it.Info.Name == "UI Expansion Kit")) - { - MelonLogger.Msg("Initializing UIExpansionKit support."); - UiExtensionsAddon.Init(); - } - MelonLoader.MelonCoroutines.Start(WaitForLocalPlayer()); + ApplyPatches(typeof(HarmonyPatches.PlayerSetupPatches)); + ApplyPatches(typeof(HarmonyPatches.CVRPickupObjectPatches)); + ApplyPatches(typeof(HarmonyPatches.CVRWorldPatches)); + ApplyPatches(typeof(HarmonyPatches.CameraFacingObjectPatches)); + ApplyPatches(typeof(HarmonyPatches.IKSystemPatches)); + ApplyPatches(typeof(HarmonyPatches.MovementSystemPatches)); } - System.Collections.IEnumerator WaitForLocalPlayer() + private void ApplyPatches(Type type) { - while (PlayerSetup.Instance == null) - yield return null; - - PlayerSetup.Instance.gameObject.AddComponent(); - - while (DesktopVRSwitchHelper.Instance == null) - yield return null; - - UpdateAllSettings(); - } - - private void OnUpdateSettings(object arg1, object arg2) => UpdateAllSettings(); - private void UpdateAllSettings() - { - if (!DesktopVRSwitchHelper.Instance) return; - DesktopVRSwitchHelper.Instance.SettingTimedErrorCatch = m_entryTimedErrorCatch.Value; - DesktopVRSwitchHelper.Instance.SettingTimedErrorTimer = m_entryTimedErrorTimer.Value; + try + { + HarmonyInstance.PatchAll(type); + } + catch (Exception e) + { + Logger.Msg($"Failed while patching {type.Name}!"); + Logger.Error(e); + } } } \ No newline at end of file diff --git a/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs b/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs index 5bb7943..3f73d51 100644 --- a/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs +++ b/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs @@ -1,61 +1,31 @@ using ABI.CCK.Components; -using ABI_RC.Core.Savior; -using HarmonyLib; -using MelonLoader; using UnityEngine; //Thanks Ben! I was scared of transpiler so I reworked a bit... -namespace DesktopVRSwitch.Patches; - -[HarmonyPatch] -internal class CVRPickupObject_Patch -{ - [HarmonyPrefix] - [HarmonyPatch(typeof(CVRPickupObject), "Start")] - private static void CVRPickupObject_Start_Prefix(ref CVRPickupObject __instance) - { - if (__instance.gripOrigin == null) return; - - Transform desktopOrigin = __instance.gripOrigin.Find("[Desktop]"); - if (desktopOrigin == null) return; - - var pickupTracker = __instance.GetComponent(); - if (pickupTracker != null) return; - - __instance.gameObject.AddComponent(); - - StorePreviousPosition(__instance, (!MetaPort.Instance.isUsingVr) ? __instance.gripOrigin : desktopOrigin); - } - - private static void StorePreviousPosition(CVRPickupObject pickupObject, Transform gripOrigin) - { - MelonLogger.Msg("Storing previous gripOrigin."); - CVRPickupObjectTracker.previousGripOrigin[pickupObject] = gripOrigin; - } -} +namespace NAK.Melons.DesktopVRSwitch.Patches; public class CVRPickupObjectTracker : MonoBehaviour { - //maybe i should store both transforms instead and getcomponent for CVRPickupObject..? - public static Dictionary previousGripOrigin = new(); + public CVRPickupObject pickupObject; + public Transform storedGripOrigin; - public void OnSwitch() + void Start() { - var pickupObject = GetComponent(); + VRModeSwitchTracker.OnPostVRModeSwitch += PostVRModeSwitch; + } + void OnDestroy() + { + VRModeSwitchTracker.OnPostVRModeSwitch -= PostVRModeSwitch; + } + + public void PostVRModeSwitch(bool enterVR, Camera activeCamera) + { if (pickupObject != null) { - if (pickupObject.IsGrabbedByMe() && pickupObject._controllerRay != null) pickupObject._controllerRay.DropObject(true); - (previousGripOrigin[pickupObject], pickupObject.gripOrigin) = (pickupObject.gripOrigin, previousGripOrigin[pickupObject]); + if (pickupObject._controllerRay != null) pickupObject._controllerRay.DropObject(true); + (storedGripOrigin, pickupObject.gripOrigin) = (pickupObject.gripOrigin, storedGripOrigin); } } - - private void OnDestroy() - { - var pickupObject = GetComponent(); - - if (pickupObject != null) - previousGripOrigin.Remove(pickupObject); - } } diff --git a/DesktopVRSwitch/Patches/CameraFacingObjectTracker.cs b/DesktopVRSwitch/Patches/CameraFacingObjectTracker.cs new file mode 100644 index 0000000..918e925 --- /dev/null +++ b/DesktopVRSwitch/Patches/CameraFacingObjectTracker.cs @@ -0,0 +1,24 @@ +using ABI_RC.Core.Util.Object_Behaviour; +using UnityEngine; + +namespace NAK.Melons.DesktopVRSwitch.Patches; + +public class CameraFacingObjectTracker : MonoBehaviour +{ + public CameraFacingObject cameraFacingObject; + void Start() + { + cameraFacingObject = GetComponent(); + VRModeSwitchTracker.OnPostVRModeSwitch += PostVRModeSwitch; + } + + void OnDestroy() + { + VRModeSwitchTracker.OnPostVRModeSwitch -= PostVRModeSwitch; + } + + public void PostVRModeSwitch(bool enterVR, Camera activeCamera) + { + cameraFacingObject.m_Camera = activeCamera; + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Patches/IKSystemTracker.cs b/DesktopVRSwitch/Patches/IKSystemTracker.cs new file mode 100644 index 0000000..f64acea --- /dev/null +++ b/DesktopVRSwitch/Patches/IKSystemTracker.cs @@ -0,0 +1,57 @@ +using ABI_RC.Systems.IK; +using ABI_RC.Systems.IK.SubSystems; +using ABI_RC.Systems.IK.TrackingModules; +using HarmonyLib; +using UnityEngine; +using System.Reflection; + +namespace NAK.Melons.DesktopVRSwitch.Patches; + +public class IKSystemTracker : MonoBehaviour +{ + public IKSystem ikSystem; + public Traverse _traverseModules; + + void Start() + { + ikSystem = GetComponent(); + _traverseModules = Traverse.Create(ikSystem).Field("_trackingModules"); + VRModeSwitchTracker.OnPostVRModeSwitch += PostVRModeSwitch; + } + void OnDestroy() + { + VRModeSwitchTracker.OnPostVRModeSwitch -= PostVRModeSwitch; + } + + public void PostVRModeSwitch(bool enterVR, Camera activeCamera) + { + var _trackingModules = _traverseModules.GetValue>(); + SteamVRTrackingModule openVRTrackingModule = _trackingModules.FirstOrDefault(m => m is SteamVRTrackingModule) as SteamVRTrackingModule; + if (openVRTrackingModule != null) + { + if (enterVR) + { + openVRTrackingModule.ModuleStart(); + } + else + { + //why named destroy when it doesnt ? + openVRTrackingModule.ModuleDestroy(); + } + } + else + { + var steamVRTrackingModule = CreateSteamVRTrackingModule(); + ikSystem.AddTrackingModule(steamVRTrackingModule); + } + } + + //thanks for marking the constructor as internal + private SteamVRTrackingModule CreateSteamVRTrackingModule() + { + var steamVRTrackingModuleType = typeof(SteamVRTrackingModule); + var constructor = steamVRTrackingModuleType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); + var instance = constructor.Invoke(null); + return (SteamVRTrackingModule)instance; + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Patches/MovementSystemTracker.cs b/DesktopVRSwitch/Patches/MovementSystemTracker.cs new file mode 100644 index 0000000..7aea4c9 --- /dev/null +++ b/DesktopVRSwitch/Patches/MovementSystemTracker.cs @@ -0,0 +1,39 @@ +using ABI_RC.Systems.MovementSystem; +using UnityEngine; + +namespace NAK.Melons.DesktopVRSwitch.Patches; + +public class MovementSystemTracker : MonoBehaviour +{ + public MovementSystem movementSystem; + + public Vector3 preSwitchWorldPosition; + public Quaternion preSwitchWorldRotation; + + void Start() + { + movementSystem = GetComponent(); + VRModeSwitchTracker.OnPostVRModeSwitch += PreVRModeSwitch; + VRModeSwitchTracker.OnPostVRModeSwitch += PostVRModeSwitch; + } + + void OnDestroy() + { + VRModeSwitchTracker.OnPostVRModeSwitch -= PreVRModeSwitch; + VRModeSwitchTracker.OnPostVRModeSwitch -= PostVRModeSwitch; + } + + public void PreVRModeSwitch(bool enterVR, Camera activeCamera) + { + preSwitchWorldPosition = movementSystem.rotationPivot.transform.position; + preSwitchWorldRotation = movementSystem.rotationPivot.transform.rotation; + } + + public void PostVRModeSwitch(bool enterVR, Camera activeCamera) + { + //lazy way of correcting Desktop & VR offset issue (game does the maths) + movementSystem.TeleportToPosRot(preSwitchWorldPosition, preSwitchWorldRotation, false); + //recenter desktop collision to player object + if (!enterVR) movementSystem.UpdateColliderCenter(movementSystem.transform.position); + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Patches/ReferenceCameraPatch.cs b/DesktopVRSwitch/Patches/ReferenceCameraPatch.cs new file mode 100644 index 0000000..9681873 --- /dev/null +++ b/DesktopVRSwitch/Patches/ReferenceCameraPatch.cs @@ -0,0 +1,91 @@ +using ABI_RC.Core.Base; +using ABI_RC.Core.Player; +using ABI_RC.Core.Savior; +using Aura2API; +using BeautifyEffect; +using UnityEngine; +using UnityEngine.AzureSky; +using UnityEngine.Rendering.PostProcessing; +using Object = UnityEngine.Object; + +namespace NAK.Melons.DesktopVRSwitch.Patches; + +internal class ReferenceCameraPatch +{ + internal static void OnWorldLoad() + { + Camera activeCamera = (MetaPort.Instance.isUsingVr ? PlayerSetup.Instance.vrCamera : PlayerSetup.Instance.desktopCamera).GetComponent(); + Camera inactiveCamera = (MetaPort.Instance.isUsingVr ? PlayerSetup.Instance.desktopCamera : PlayerSetup.Instance.vrCamera).GetComponent(); + CopyToInactiveCam(activeCamera, inactiveCamera); + } + + internal static void CopyToInactiveCam(Camera activeCam, Camera inactiveCam) + { + DesktopVRSwitchMod.Logger.Msg("Copying active camera settings & components to inactive camera."); + + //steal basic settings + inactiveCam.farClipPlane = activeCam.farClipPlane; + inactiveCam.nearClipPlane = activeCam.nearClipPlane; + inactiveCam.cullingMask = activeCam.cullingMask; + inactiveCam.depthTextureMode = activeCam.depthTextureMode; + + //steal post processing if added + PostProcessLayer ppLayerActiveCam = activeCam.GetComponent(); + PostProcessLayer ppLayerInactiveCam = inactiveCam.AddComponentIfMissing(); + if (ppLayerActiveCam != null && ppLayerInactiveCam != null) + { + ppLayerInactiveCam.enabled = ppLayerActiveCam.enabled; + ppLayerInactiveCam.volumeLayer = ppLayerActiveCam.volumeLayer; + } + + //what even is this aura camera stuff + AuraCamera auraActiveCam = activeCam.GetComponent(); + AuraCamera auraInactiveCam = inactiveCam.AddComponentIfMissing(); + if (auraActiveCam != null && auraInactiveCam != null) + { + auraInactiveCam.enabled = auraActiveCam.enabled; + auraInactiveCam.frustumSettings = auraActiveCam.frustumSettings; + } + else + { + auraInactiveCam.enabled = false; + } + + //flare layer thing? the sun :_:_:_:_:_: + FlareLayer flareActiveCam = activeCam.GetComponent(); + FlareLayer flareInactiveCam = inactiveCam.AddComponentIfMissing(); + if (flareActiveCam != null && flareInactiveCam != null) + { + flareInactiveCam.enabled = flareActiveCam.enabled; + } + else + { + flareInactiveCam.enabled = false; + } + + //and now what the fuck is fog scattering + AzureFogScattering azureFogActiveCam = activeCam.GetComponent(); + AzureFogScattering azureFogInactiveCam = inactiveCam.AddComponentIfMissing(); + if (azureFogActiveCam != null && azureFogInactiveCam != null) + { + azureFogInactiveCam.fogScatteringMaterial = azureFogActiveCam.fogScatteringMaterial; + } + else + { + Object.Destroy(inactiveCam.GetComponent()); + } + + //why is there so many thingsssssssss + Beautify beautifyActiveCam = activeCam.GetComponent(); + Beautify beautifyInactiveCam = inactiveCam.AddComponentIfMissing(); + if (beautifyActiveCam != null && beautifyInactiveCam != null) + { + beautifyInactiveCam.quality = beautifyActiveCam.quality; + beautifyInactiveCam.profile = beautifyActiveCam.profile; + } + else + { + Object.Destroy(inactiveCam.gameObject.GetComponent()); + } + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Patches/VRModeSwitchTracker.cs b/DesktopVRSwitch/Patches/VRModeSwitchTracker.cs new file mode 100644 index 0000000..d6f20c3 --- /dev/null +++ b/DesktopVRSwitch/Patches/VRModeSwitchTracker.cs @@ -0,0 +1,33 @@ +using ABI_RC.Core.Player; +using UnityEngine; +using UnityEngine.Events; + +namespace NAK.Melons.DesktopVRSwitch.Patches; + +public class VRModeSwitchTracker +{ + public static event UnityAction OnPreVRModeSwitch; + public static event UnityAction OnPostVRModeSwitch; + + public static void PreVRModeSwitch(bool enterVR) + { + TryCatchHell.TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Invoking VRModeSwitchTracker.OnPreVRModeSwitch."); + Camera activeCamera = PlayerSetup.Instance.GetActiveCamera().GetComponent(); + VRModeSwitchTracker.OnPreVRModeSwitch?.Invoke(enterVR, activeCamera); + }, + "Error while invoking VRModeSwitchTracker.OnPreVRModeSwitch. Did someone do a fucky?"); + } + + public static void PostVRModeSwitch(bool enterVR) + { + TryCatchHell.TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Invoking VRModeSwitchTracker.OnPostVRModeSwitch."); + Camera activeCamera = PlayerSetup.Instance.GetActiveCamera().GetComponent(); + VRModeSwitchTracker.OnPostVRModeSwitch?.Invoke(enterVR, activeCamera); + }, + "Error while invoking VRModeSwitchTracker.OnPostVRModeSwitch. Did someone do a fucky?"); + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Properties/AssemblyInfo.cs b/DesktopVRSwitch/Properties/AssemblyInfo.cs index 743b703..35df6ca 100644 --- a/DesktopVRSwitch/Properties/AssemblyInfo.cs +++ b/DesktopVRSwitch/Properties/AssemblyInfo.cs @@ -1,18 +1,17 @@ -using DesktopVRSwitch.Properties; -using MelonLoader; +using MelonLoader; +using NAK.Melons.DesktopVRSwitch.Properties; using System.Reflection; - [assembly: AssemblyVersion(AssemblyInfoParams.Version)] [assembly: AssemblyFileVersion(AssemblyInfoParams.Version)] [assembly: AssemblyInformationalVersion(AssemblyInfoParams.Version)] -[assembly: AssemblyTitle(nameof(DesktopVRSwitch))] +[assembly: AssemblyTitle(nameof(NAK.Melons.DesktopVRSwitch))] [assembly: AssemblyCompany(AssemblyInfoParams.Author)] -[assembly: AssemblyProduct(nameof(DesktopVRSwitch))] +[assembly: AssemblyProduct(nameof(NAK.Melons.DesktopVRSwitch))] [assembly: MelonInfo( - typeof(DesktopVRSwitch.DesktopVRSwitch), - nameof(DesktopVRSwitch), + typeof(NAK.Melons.DesktopVRSwitch.DesktopVRSwitchMod), + nameof(NAK.Melons.DesktopVRSwitch), AssemblyInfoParams.Version, AssemblyInfoParams.Author, downloadLink: "https://github.com/NotAKidOnSteam/DesktopVRSwitch" @@ -21,10 +20,11 @@ using System.Reflection; [assembly: MelonGame("Alpha Blend Interactive", "ChilloutVR")] [assembly: MelonPlatform(MelonPlatformAttribute.CompatiblePlatforms.WINDOWS_X64)] [assembly: MelonPlatformDomain(MelonPlatformDomainAttribute.CompatibleDomains.MONO)] +[assembly: HarmonyDontPatchAll] -namespace DesktopVRSwitch.Properties; +namespace NAK.Melons.DesktopVRSwitch.Properties; internal static class AssemblyInfoParams { - public const string Version = "3.0.5"; + public const string Version = "4.2.4"; public const string Author = "NotAKidoS"; } \ No newline at end of file diff --git a/DesktopVRSwitch/TryCatchHell.cs b/DesktopVRSwitch/TryCatchHell.cs new file mode 100644 index 0000000..ad3313b --- /dev/null +++ b/DesktopVRSwitch/TryCatchHell.cs @@ -0,0 +1,167 @@ +using ABI_RC.Core; +using ABI_RC.Core.EventSystem; +using ABI_RC.Core.InteractionSystem; +using ABI_RC.Core.Player; +using ABI_RC.Core.Savior; +using ABI_RC.Core.UI; +using ABI_RC.Systems.Camera; +using HarmonyLib; +using UnityEngine; + +namespace NAK.Melons.DesktopVRSwitch; + +internal class TryCatchHell +{ + internal static void TryCatchWrapper(Action action, string errorMsg, params object[] msgArgs) + { + try + { + action(); + } + catch (Exception ex) + { + DesktopVRSwitchMod.Logger.Error(string.Format(errorMsg, msgArgs)); + DesktopVRSwitchMod.Logger.Msg(ex.Message); + } + } + + internal static void SetCheckVR(bool isVR) + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg($"Setting CheckVR hasVrDeviceLoaded to {isVR}."); + CheckVR.Instance.hasVrDeviceLoaded = isVR; + }, + "Setting CheckVR hasVrDeviceLoaded failed."); + } + + internal static void SetMetaPort(bool isVR) + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg($"Setting MetaPort isUsingVr to {isVR}."); + MetaPort.Instance.isUsingVr = isVR; + }, + "Setting MetaPort isUsingVr failed."); + } + + internal static void RepositionCohtmlHud(bool isVR) + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Configuring new hud affinity for CohtmlHud."); + CohtmlHud.Instance.gameObject.transform.parent = isVR ? PlayerSetup.Instance.vrCamera.transform : PlayerSetup.Instance.desktopCamera.transform; + CVRTools.ConfigureHudAffinity(); + CohtmlHud.Instance.gameObject.transform.localScale = new Vector3(1.2f, 1f, 1.2f); + }, + "Error parenting CohtmlHud to active camera."); + } + + internal static void UpdateHudOperations(bool isVR) + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Switching HudOperations worldLoadingItem & worldLoadStatus."); + HudOperations.Instance.worldLoadingItem = isVR ? HudOperations.Instance.worldLoadingItemVr : HudOperations.Instance.worldLoadingItemDesktop; + HudOperations.Instance.worldLoadStatus = isVR ? HudOperations.Instance.worldLoadStatusVr : HudOperations.Instance.worldLoadStatusDesktop; + }, + "Failed switching HudOperations objects."); + } + + internal static void DisableMirrorCanvas() + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Forcing PortableCamera canvas mirroring off."); + //tell the game we are in mirror mode so itll disable it (if enabled) + PortableCamera.Instance.mode = MirroringMode.Mirror; + PortableCamera.Instance.ChangeMirroring(); + }, + "Failed to disable PortableCamera canvas mirroring."); + } + + internal static void SwitchActiveCameraRigs(bool isVR) + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Switching active PlayerSetup camera rigs. Updating Desktop camera FOV."); + PlayerSetup.Instance.desktopCameraRig.SetActive(!isVR); + PlayerSetup.Instance.vrCameraRig.SetActive(isVR); + CVR_DesktopCameraController.UpdateFov(); + //uicamera has script that copies fov from desktop cam + //toggling the cameras on/off resets aspect ratio + //so when rigs switch, that is already handled + }, + "Failed to switch active camera rigs or update Desktop camera FOV."); + } + + internal static void PauseInputInteractions(bool toggle) + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg($"Setting CVRInputManager inputEnabled & CVR_InteractableManager enableInteractions to {!toggle}"); + CVRInputManager.Instance.inputEnabled = !toggle; + CVR_InteractableManager.enableInteractions = !toggle; + }, + "Failed to toggle CVRInputManager inputEnabled & CVR_InteractableManager enableInteractions."); + } + + internal static void ResetCVRInputManager() + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Resetting CVRInputManager inputs."); + //just in case + CVRInputManager.Instance.blockedByUi = false; + //sometimes head can get stuck, so just in case + CVRInputManager.Instance.independentHeadToggle = false; + //just nice to load into desktop with idle gesture + CVRInputManager.Instance.gestureLeft = 0f; + CVRInputManager.Instance.gestureLeftRaw = 0f; + CVRInputManager.Instance.gestureRight = 0f; + CVRInputManager.Instance.gestureRightRaw = 0f; + }, + "Failed to reset CVRInputManager inputs."); + } + + internal static void ReloadLocalAvatar() + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Attempting to reload current local avatar from GUID."); + AssetManagement.Instance.LoadLocalAvatar(MetaPort.Instance.currentAvatarGuid); + }, + "Failed to reload local avatar."); + } + + internal static void UpdateRichPresence() + { + TryCatchWrapper(() => + { + if (MetaPort.Instance.settings.GetSettingsBool("ImplementationRichPresenceDiscordEnabled", true)) + { + DesktopVRSwitchMod.Logger.Msg("Forcing Discord Rich Presence update."); + MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceDiscordEnabled", false); + MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceDiscordEnabled", true); + } + if (MetaPort.Instance.settings.GetSettingsBool("ImplementationRichPresenceSteamEnabled", true)) + { + DesktopVRSwitchMod.Logger.Msg("Forcing Steam Rich Presence update."); + MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceSteamEnabled", false); + MetaPort.Instance.settings.SetSettingsBool("ImplementationRichPresenceSteamEnabled", true); + } + }, + "Failed to update Discord & Steam Rich Presence."); + } + + internal static void UpdateGestureReconizerCam() + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Updating CVRGestureRecognizer _camera to active camera."); + Traverse.Create(CVRGestureRecognizer.Instance).Field("_camera").SetValue(PlayerSetup.Instance.GetActiveCamera().GetComponent()); + }, + "Failed to update CVRGestureRecognizer camera."); + } +} + diff --git a/DesktopVRSwitch/UIExpansionKitAddon.cs b/DesktopVRSwitch/UIExpansionKitAddon.cs deleted file mode 100644 index de9e9d7..0000000 --- a/DesktopVRSwitch/UIExpansionKitAddon.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Runtime.CompilerServices; -using UIExpansionKit.API; - -namespace DesktopVRSwitch; -public static class UiExtensionsAddon -{ - [MethodImpl(MethodImplOptions.NoInlining)] - public static void Init() - { - var settings = ExpansionKitApi.GetSettingsCategory(DesktopVRSwitch.SettingsCategory); - settings.AddSimpleButton("Switch VRMode", SwitchModeButton); - } - internal static void SwitchModeButton() => DesktopVRSwitchHelper.Instance.SwitchMode(true); -} \ No newline at end of file From 4ca30fe5cde8cbf3946f5a8b88e1c720dff7b99e Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Fri, 17 Feb 2023 06:32:30 -0600 Subject: [PATCH 27/42] bump --- DesktopVRSwitch/Properties/AssemblyInfo.cs | 2 +- DesktopVRSwitch/format.json | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/DesktopVRSwitch/Properties/AssemblyInfo.cs b/DesktopVRSwitch/Properties/AssemblyInfo.cs index 35df6ca..e8d2180 100644 --- a/DesktopVRSwitch/Properties/AssemblyInfo.cs +++ b/DesktopVRSwitch/Properties/AssemblyInfo.cs @@ -25,6 +25,6 @@ using System.Reflection; namespace NAK.Melons.DesktopVRSwitch.Properties; internal static class AssemblyInfoParams { - public const string Version = "4.2.4"; + public const string Version = "4.3.0"; public const string Author = "NotAKidoS"; } \ No newline at end of file diff --git a/DesktopVRSwitch/format.json b/DesktopVRSwitch/format.json index df073eb..6a72e2c 100644 --- a/DesktopVRSwitch/format.json +++ b/DesktopVRSwitch/format.json @@ -1,8 +1,8 @@ { "_id": 103, "name": "DesktopVRSwitch", - "modversion": "3.0.0", - "gameversion": "2022r169p1", + "modversion": "4.3.0", + "gameversion": "2022r170", "loaderversion": "0.5.7", "modtype": "Mod", "author": "NotAKidoS", @@ -16,8 +16,8 @@ "requirements": [ "None" ], - "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/r3/DesktopVRSwitch.dll", + "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/v4.3.0/DesktopVRSwitch.dll", "sourcelink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/", - "changelog": "Initial CVRMG Release", + "changelog": "Backported from the Experimental build and patched up to handle OpenVR.", "embedcolor": "3498db" } \ No newline at end of file From 4daf6c2bc8c961ffb01a873cfc9b50ec6cc8584c Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Fri, 17 Feb 2023 06:55:15 -0600 Subject: [PATCH 28/42] Update README.md --- README.md | 31 ++++++++++--------------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 4137184..6e7bbc4 100644 --- a/README.md +++ b/README.md @@ -3,31 +3,20 @@ Allows you to switch between Desktop and VR with a keybind. Press Control + F6 to switch. -While this mod is a nice convienence feature to have access to, not every chillout system or mod is built to support it. Keep in mind there **will be issues**, so don't get mad if you do end up having to restart. **:stare:** +## There are two versions of this mod! +**DesktopVRSwitch** is built for the Stable branch of ChilloutVR. (OpenVR) -Please take a look at the table below for what may not function as intended after switch. A lot of them can be remedied by rejoining your current instance. +**DesktopXRSwitch** is built for the Experimental branch of ChilloutVR (OpenXR) -| Function | Working | Note | -| ------------- | ------------- | ------------- | -| Discord/Steam RPC | None | Rich Presence will report the first mode you launched in. (might correct on world change) | -| CVRPickupObject | None | Pickups will use the grip origin set during spawn. The game overrides the default VR origin with [Desktop] origin if available, so I cannot revert to VR origins when switching from Desktop. | -| CVRWorld UpdatePostProcessing | Not Implemented | GraphicsAO and other specific post processing settings are not currently set on switch. | -| SceneLoaded worldCamera | Not Implemented | World-set camera settings are not currently set for both Desktop & VR cameras. | -| ControllerRay vrActive | Not Sure | I haven't had any issues with this, so I haven't bothered looking into it. | -| CVRWorld CopyRefCamValues | Not Implemented | This may not cause issues, but farclip is not set on the opposite modes transition effects when you load a world. | -| CameraFacingObject | Maybe | All CameraFacingObject behaviors have their camera changed to the active main camera on switch. Not sure if this is a good solution, but required for nameplates to face your viewpoint. | -| CoHtmlHud | Yes | CoHtmlHud is parented to the active camera on switch. | -| HudOperations | Kind Of | HudOperations is set to use the correct gameobjects to show loading info on the bottom right of the hud, but it seems to not be placed correctly. | -| CheckVR | No | Not needed. We initialize SteamVR ourselves and MetaPort only checks it on Start. | -| MetaPort | Yes | This is the most important as everything checks here for VRMode. Some systems will cache VRMode on start though, which is where issues with switching occur. | -| PlayerSetup | Yes | Also highly important. PlayerSetup caches VRMode from MetaPort to run correct calibration. To prevent errors, a dummy VRIK component is created before running a quick calibration to prevent PlayerSetup from erroring when switching to VR. | -| MovementSystem | Yes | MovementSystem constantly checks MetaPort for VRMode each frame, so while it isn't directly needed I still set the cached VRMode to true. | -| CVRInputManager | Yes..? | We set CVRInputManager.reload to have input & menus reload next frame, but also set independentHeadToggle and others to false to prevent the game from locking head control. | -| GesturePlaneTest | Testing | GestureReconizer will use the original launch camera for reference, which means you cannot pull the camera out with gestures when switched. It is the only part of the game that makes a cached result from VRMode private, so I have to dick around with Traverse/Harmony. :stare: | +Once the Experimental branch of ChilloutVR hits Stable, the mod name will be changing from VR -> XR. -(an old clip from the first few tests, no longer using melonprefs as uiexpansionkit kinda gets nuked on menu reload) +--- -https://user-images.githubusercontent.com/37721153/192128515-5630f47b-63ed-45c5-b0eb-0aac46d23731.mp4 +There used to be a table here detailing what did and did not work after switching, but I have worked to make that list unnecessary. + +Almost all base game features & systems that differ when in VR are now updated after switch. There are still very likely small quirks that need ironing out still, but everything major is now fixed and accounted for. + +Desktop to VR to FBT. Restarting SteamVR without restarting ChilloutVR. Reconnecting to SteamVR with a different VR headset. --- From 5b68aedeb41c9aa84334003620e4e8a8c514cecf Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Fri, 17 Feb 2023 06:57:49 -0600 Subject: [PATCH 29/42] Update README.md --- README.md | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 6e7bbc4..dd02c1b 100644 --- a/README.md +++ b/README.md @@ -3,20 +3,28 @@ Allows you to switch between Desktop and VR with a keybind. Press Control + F6 to switch. -## There are two versions of this mod! -**DesktopVRSwitch** is built for the Stable branch of ChilloutVR. (OpenVR) - -**DesktopXRSwitch** is built for the Experimental branch of ChilloutVR (OpenXR) - -Once the Experimental branch of ChilloutVR hits Stable, the mod name will be changing from VR -> XR. - --- There used to be a table here detailing what did and did not work after switching, but I have worked to make that list unnecessary. Almost all base game features & systems that differ when in VR are now updated after switch. There are still very likely small quirks that need ironing out still, but everything major is now fixed and accounted for. -Desktop to VR to FBT. Restarting SteamVR without restarting ChilloutVR. Reconnecting to SteamVR with a different VR headset. + +**Things that have been tested.** +* Desktop to VR to FBT to Desktop. +* Restarting SteamVR without restarting ChilloutVR. +* Reentering VR with different controllers. (Touch to Knuckles) + +**Things that have not been tested** +* Reconnecting to SteamVR with a different VR headset. + + +## There are two versions of this mod! +**DesktopVRSwitch** is built for the Stable branch of ChilloutVR. (OpenVR) + +**DesktopXRSwitch** is built for the Experimental branch of ChilloutVR (OpenXR) + +Once the Experimental branch of ChilloutVR hits Stable, the mod name will be changing from VR -> XR. --- From 1adc95c696417aa319c1454cb39a694b3448a321 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Fri, 17 Feb 2023 06:58:56 -0600 Subject: [PATCH 30/42] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dd02c1b..df2dd8b 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Press Control + F6 to switch. There used to be a table here detailing what did and did not work after switching, but I have worked to make that list unnecessary. -Almost all base game features & systems that differ when in VR are now updated after switch. There are still very likely small quirks that need ironing out still, but everything major is now fixed and accounted for. +Almost all base game features & systems that differ when in VR are now updated after switch. There are still very likely small quirks that need ironing out still, but everything major is now fixed and accounted for. If you attempt to switch, SteamVR should automatically be launched if an HMD is connected and not already running. **Things that have been tested.** From ae7daa203ec4f70881e516c970b533baee6f20a6 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Fri, 17 Feb 2023 06:59:19 -0600 Subject: [PATCH 31/42] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index df2dd8b..83cf9d4 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,9 @@ Press Control + F6 to switch. There used to be a table here detailing what did and did not work after switching, but I have worked to make that list unnecessary. -Almost all base game features & systems that differ when in VR are now updated after switch. There are still very likely small quirks that need ironing out still, but everything major is now fixed and accounted for. If you attempt to switch, SteamVR should automatically be launched if an HMD is connected and not already running. +Almost all base game features & systems that differ when in VR are now updated after switch. There are still very likely small quirks that need ironing out still, but everything major is now fixed and accounted for. + +When you attempt to switch, SteamVR should automatically be launched if an HMD is connected and not already running. **Things that have been tested.** From 1ac61b1dd2dcd26deb7b79dcf236b44448287506 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Fri, 17 Feb 2023 06:59:45 -0600 Subject: [PATCH 32/42] Update README.md --- README.md | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/README.md b/README.md index 83cf9d4..28c904b 100644 --- a/README.md +++ b/README.md @@ -9,18 +9,6 @@ There used to be a table here detailing what did and did not work after switchin Almost all base game features & systems that differ when in VR are now updated after switch. There are still very likely small quirks that need ironing out still, but everything major is now fixed and accounted for. -When you attempt to switch, SteamVR should automatically be launched if an HMD is connected and not already running. - - -**Things that have been tested.** -* Desktop to VR to FBT to Desktop. -* Restarting SteamVR without restarting ChilloutVR. -* Reentering VR with different controllers. (Touch to Knuckles) - -**Things that have not been tested** -* Reconnecting to SteamVR with a different VR headset. - - ## There are two versions of this mod! **DesktopVRSwitch** is built for the Stable branch of ChilloutVR. (OpenVR) From 81e734ec8f17b5c5f67aef0b0b477d80a2edbd59 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 18 Feb 2023 06:25:51 -0600 Subject: [PATCH 33/42] VRTrackerManager controller swap fix & IKSystem tweak. --- DesktopVRSwitch/DesktopVRSwitch.cs | 3 ++ DesktopVRSwitch/DesktopVRSwitch.sln | 12 +++---- DesktopVRSwitch/HarmonyPatches.cs | 10 ++++++ DesktopVRSwitch/Main.cs | 14 ++++++++ DesktopVRSwitch/Patches/IKSystemTracker.cs | 8 +++-- .../Patches/MovementSystemTracker.cs | 11 ++++-- .../Patches/VRTrackerManagerTracker.cs | 35 +++++++++++++++++++ DesktopVRSwitch/Properties/AssemblyInfo.cs | 2 +- DesktopVRSwitch/TryCatchHell.cs | 13 +++++++ 9 files changed, 95 insertions(+), 13 deletions(-) create mode 100644 DesktopVRSwitch/Patches/VRTrackerManagerTracker.cs diff --git a/DesktopVRSwitch/DesktopVRSwitch.cs b/DesktopVRSwitch/DesktopVRSwitch.cs index 7da6495..8295c59 100644 --- a/DesktopVRSwitch/DesktopVRSwitch.cs +++ b/DesktopVRSwitch/DesktopVRSwitch.cs @@ -96,6 +96,9 @@ public class DesktopVRSwitch : MonoBehaviour //one frame after switch attempt public void AfterVRModeSwitch(bool enterVR) { + //close the menus + TryCatchHell.CloseCohtmlMenus(); + //these two must come first TryCatchHell.SetCheckVR(enterVR); TryCatchHell.SetMetaPort(enterVR); diff --git a/DesktopVRSwitch/DesktopVRSwitch.sln b/DesktopVRSwitch/DesktopVRSwitch.sln index 8d77157..0223868 100644 --- a/DesktopVRSwitch/DesktopVRSwitch.sln +++ b/DesktopVRSwitch/DesktopVRSwitch.sln @@ -3,11 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.2.32630.192 MinimumVisualStudioVersion = 10.0.40219.1 -<<<<<<< Updated upstream Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DesktopVRSwitch", "DesktopVRSwitch.csproj", "{4008E6D1-32F9-449B-8820-80ACF0ED8233}" -======= -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DesktopVRSwitch", "DesktopVRSwitch.csproj", "{D8B326EF-AC8E-4D71-AFC9-0658831B059B}" ->>>>>>> Stashed changes EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -15,10 +11,10 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {D8B326EF-AC8E-4D71-AFC9-0658831B059B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D8B326EF-AC8E-4D71-AFC9-0658831B059B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D8B326EF-AC8E-4D71-AFC9-0658831B059B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D8B326EF-AC8E-4D71-AFC9-0658831B059B}.Release|Any CPU.Build.0 = Release|Any CPU + {4008E6D1-32F9-449B-8820-80ACF0ED8233}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4008E6D1-32F9-449B-8820-80ACF0ED8233}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4008E6D1-32F9-449B-8820-80ACF0ED8233}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4008E6D1-32F9-449B-8820-80ACF0ED8233}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/DesktopVRSwitch/HarmonyPatches.cs b/DesktopVRSwitch/HarmonyPatches.cs index 6790699..93dad81 100644 --- a/DesktopVRSwitch/HarmonyPatches.cs +++ b/DesktopVRSwitch/HarmonyPatches.cs @@ -89,4 +89,14 @@ internal class IKSystemPatches { __instance.gameObject.AddComponent(); } +} + +internal class VRTrackerManagerPatches +{ + [HarmonyPostfix] + [HarmonyPatch(typeof(VRTrackerManager), "Start")] + private static void Postfix_VRTrackerManager_Start(ref VRTrackerManager __instance) + { + __instance.gameObject.AddComponent(); + } } \ No newline at end of file diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index 4e61e12..5bf1280 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -1,5 +1,18 @@ using MelonLoader; +/** + I know the TryCatchHell thing might be a bit exessive, but it is + built so if a user that happens to have access to a build I do not, + I will have a good idea of what broke and where, and what to look out + for when updates/experimentals release. (which has happened a few times) + + It is also just in case other mods break or tweak functionality that + could fuck with switching. Or if they try to detect switching and break... + + The VRModeSwitchTracker system is also built so I can easily & quickly make adjustments to + components that may or may not change between builds without breaking the rest of the mod. +**/ + namespace NAK.Melons.DesktopVRSwitch; public class DesktopVRSwitchMod : MelonMod @@ -19,6 +32,7 @@ public class DesktopVRSwitchMod : MelonMod ApplyPatches(typeof(HarmonyPatches.CameraFacingObjectPatches)); ApplyPatches(typeof(HarmonyPatches.IKSystemPatches)); ApplyPatches(typeof(HarmonyPatches.MovementSystemPatches)); + ApplyPatches(typeof(HarmonyPatches.VRTrackerManagerPatches)); } private void ApplyPatches(Type type) diff --git a/DesktopVRSwitch/Patches/IKSystemTracker.cs b/DesktopVRSwitch/Patches/IKSystemTracker.cs index f64acea..7258a41 100644 --- a/DesktopVRSwitch/Patches/IKSystemTracker.cs +++ b/DesktopVRSwitch/Patches/IKSystemTracker.cs @@ -1,9 +1,8 @@ using ABI_RC.Systems.IK; -using ABI_RC.Systems.IK.SubSystems; using ABI_RC.Systems.IK.TrackingModules; using HarmonyLib; -using UnityEngine; using System.Reflection; +using UnityEngine; namespace NAK.Melons.DesktopVRSwitch.Patches; @@ -44,6 +43,11 @@ public class IKSystemTracker : MonoBehaviour var steamVRTrackingModule = CreateSteamVRTrackingModule(); ikSystem.AddTrackingModule(steamVRTrackingModule); } + + //make it so you dont instantly end up in FBT from Desktop + IKSystem.firstAvatarLoaded = false; + //turn of finger tracking just in case user switched controllers + ikSystem.FingerSystem.controlActive = false; } //thanks for marking the constructor as internal diff --git a/DesktopVRSwitch/Patches/MovementSystemTracker.cs b/DesktopVRSwitch/Patches/MovementSystemTracker.cs index 7aea4c9..a54c07d 100644 --- a/DesktopVRSwitch/Patches/MovementSystemTracker.cs +++ b/DesktopVRSwitch/Patches/MovementSystemTracker.cs @@ -6,7 +6,6 @@ namespace NAK.Melons.DesktopVRSwitch.Patches; public class MovementSystemTracker : MonoBehaviour { public MovementSystem movementSystem; - public Vector3 preSwitchWorldPosition; public Quaternion preSwitchWorldRotation; @@ -25,8 +24,16 @@ public class MovementSystemTracker : MonoBehaviour public void PreVRModeSwitch(bool enterVR, Camera activeCamera) { - preSwitchWorldPosition = movementSystem.rotationPivot.transform.position; + //correct rotationPivot y position, so we dont teleport up/down + Vector3 position = movementSystem.rotationPivot.transform.position; + position.y = movementSystem.transform.position.y; + preSwitchWorldPosition = position; preSwitchWorldRotation = movementSystem.rotationPivot.transform.rotation; + //ChilloutVR does not use VRIK root right, so avatar root is VR player root. + //This causes desync between VR and Desktop positions & collision on switch. + + //I correct for this in lazy way, but i use rotationPivot instead of avatar root, + //so the user can still switch even if avatar is null (if it failed to load for example). } public void PostVRModeSwitch(bool enterVR, Camera activeCamera) diff --git a/DesktopVRSwitch/Patches/VRTrackerManagerTracker.cs b/DesktopVRSwitch/Patches/VRTrackerManagerTracker.cs new file mode 100644 index 0000000..8ef5e50 --- /dev/null +++ b/DesktopVRSwitch/Patches/VRTrackerManagerTracker.cs @@ -0,0 +1,35 @@ +using ABI_RC.Core.Player; +using HarmonyLib; +using UnityEngine; + +namespace NAK.Melons.DesktopVRSwitch.Patches; + +public class VRTrackerManagerTracker : MonoBehaviour +{ + public VRTrackerManager vrTrackerManager; + public Traverse _hasCheckedForKnucklesTraverse; + public Traverse _posesTraverse; + + void Start() + { + vrTrackerManager = GetComponent(); + _posesTraverse = Traverse.Create(vrTrackerManager).Field("poses"); + _hasCheckedForKnucklesTraverse = Traverse.Create(vrTrackerManager).Field("hasCheckedForKnuckles"); + VRModeSwitchTracker.OnPostVRModeSwitch += PostVRModeSwitch; + } + void OnDestroy() + { + VRModeSwitchTracker.OnPostVRModeSwitch -= PostVRModeSwitch; + } + + public void PostVRModeSwitch(bool enterVR, Camera activeCamera) + { + //force the VRTrackerManager to reset anything its stored + //this makes it get correct Left/Right hand if entering VR with different controllers + //or if you restarted SteamVR and controllers are now in swapped index + vrTrackerManager.leftHand = null; + vrTrackerManager.rightHand = null; + _posesTraverse.SetValue(null); + _hasCheckedForKnucklesTraverse.SetValue(false); + } +} \ No newline at end of file diff --git a/DesktopVRSwitch/Properties/AssemblyInfo.cs b/DesktopVRSwitch/Properties/AssemblyInfo.cs index e8d2180..dd5b9f7 100644 --- a/DesktopVRSwitch/Properties/AssemblyInfo.cs +++ b/DesktopVRSwitch/Properties/AssemblyInfo.cs @@ -25,6 +25,6 @@ using System.Reflection; namespace NAK.Melons.DesktopVRSwitch.Properties; internal static class AssemblyInfoParams { - public const string Version = "4.3.0"; + public const string Version = "4.3.1"; public const string Author = "NotAKidoS"; } \ No newline at end of file diff --git a/DesktopVRSwitch/TryCatchHell.cs b/DesktopVRSwitch/TryCatchHell.cs index ad3313b..9a1a332 100644 --- a/DesktopVRSwitch/TryCatchHell.cs +++ b/DesktopVRSwitch/TryCatchHell.cs @@ -25,6 +25,17 @@ internal class TryCatchHell } } + internal static void CloseCohtmlMenus() + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Closing ViewManager & CVR_MenuManager menus."); + ViewManager.Instance.UiStateToggle(false); + CVR_MenuManager.Instance.ToggleQuickMenu(false); + }, + "Setting CheckVR hasVrDeviceLoaded failed."); + } + internal static void SetCheckVR(bool isVR) { TryCatchWrapper(() => @@ -120,6 +131,8 @@ internal class TryCatchHell CVRInputManager.Instance.gestureLeftRaw = 0f; CVRInputManager.Instance.gestureRight = 0f; CVRInputManager.Instance.gestureRightRaw = 0f; + //turn off finger tracking input + CVRInputManager.Instance.individualFingerTracking = false; }, "Failed to reset CVRInputManager inputs."); } From 23e5e9c3665821c5ac974ffd118e0efa3f76c8b9 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 18 Feb 2023 06:50:48 -0600 Subject: [PATCH 34/42] Update format.json --- DesktopVRSwitch/format.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/DesktopVRSwitch/format.json b/DesktopVRSwitch/format.json index 6a72e2c..d9514e0 100644 --- a/DesktopVRSwitch/format.json +++ b/DesktopVRSwitch/format.json @@ -1,7 +1,7 @@ { "_id": 103, "name": "DesktopVRSwitch", - "modversion": "4.3.0", + "modversion": "4.3.1", "gameversion": "2022r170", "loaderversion": "0.5.7", "modtype": "Mod", @@ -16,8 +16,8 @@ "requirements": [ "None" ], - "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/v4.3.0/DesktopVRSwitch.dll", + "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/v4.3.1/DesktopVRSwitch.dll", "sourcelink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/", - "changelog": "Backported from the Experimental build and patched up to handle OpenVR.", + "changelog": "- Backported rewrite from Experimental & patched up to handle OpenVR.\n- Reinitialize SteamVR input on switch incase user restarted SteamVR or changed controllers. Correct fixedDeltaTime when entering Desktop.\n- Many tweaks to ensure everything in-game functions as expected.", "embedcolor": "3498db" } \ No newline at end of file From 1c2383d159d1dbbd386d9cbaa6b67f7c2d3038bc Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 18 Feb 2023 06:53:47 -0600 Subject: [PATCH 35/42] Update README.md --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 28c904b..45f2cdb 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,6 @@ Press Control + F6 to switch. --- -There used to be a table here detailing what did and did not work after switching, but I have worked to make that list unnecessary. - Almost all base game features & systems that differ when in VR are now updated after switch. There are still very likely small quirks that need ironing out still, but everything major is now fixed and accounted for. ## There are two versions of this mod! From c38e9ee86a2069447ae97d36af30eed2fba46392 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 18 Feb 2023 07:03:18 -0600 Subject: [PATCH 36/42] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 45f2cdb..10909c6 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,14 @@ # DesktopVRSwitch Allows you to switch between Desktop and VR with a keybind. -Press Control + F6 to switch. +Press Control + F6 to switch. SteamVR will automatically start if it isn't already running. --- Almost all base game features & systems that differ when in VR are now updated after switch. There are still very likely small quirks that need ironing out still, but everything major is now fixed and accounted for. +This mod will likely cause issues with other mods that are not built for or expect VRMode changes during runtime. + ## There are two versions of this mod! **DesktopVRSwitch** is built for the Stable branch of ChilloutVR. (OpenVR) From e62efc714e9ba1fed8c28527aba43b9bf845e391 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 18 Feb 2023 09:30:16 -0600 Subject: [PATCH 37/42] tweaks --- DesktopVRSwitch/DesktopVRSwitch.cs | 43 +++++++++++-------- .../Patches/VRModeSwitchTracker.cs | 12 ++++++ 2 files changed, 38 insertions(+), 17 deletions(-) diff --git a/DesktopVRSwitch/DesktopVRSwitch.cs b/DesktopVRSwitch/DesktopVRSwitch.cs index 8295c59..aca9c01 100644 --- a/DesktopVRSwitch/DesktopVRSwitch.cs +++ b/DesktopVRSwitch/DesktopVRSwitch.cs @@ -45,14 +45,11 @@ public class DesktopVRSwitch : MonoBehaviour private IEnumerator StartVRSystem() { - BeforeVRModeSwitch(true); + + PreVRModeSwitch(true); XRSettings.LoadDeviceByName("OpenVR"); - yield return null; - if (string.IsNullOrEmpty(XRSettings.loadedDeviceName)) - { - DesktopVRSwitchMod.Logger.Error("Initializing VR Failed. Is there no VR device connected?"); - } - else + yield return null; //wait a frame before checking + if (!string.IsNullOrEmpty(XRSettings.loadedDeviceName)) { DesktopVRSwitchMod.Logger.Msg("Starting SteamVR..."); XRSettings.enabled = true; @@ -62,48 +59,60 @@ public class DesktopVRSwitch : MonoBehaviour //which in ChilloutVR, it is, because all those settings are default SteamVR_Input.Initialize(true); yield return null; - AfterVRModeSwitch(true); + PostVRModeSwitch(true); + yield break; } + DesktopVRSwitchMod.Logger.Error("Initializing VR Failed. Is there no VR device connected?"); + FailedVRModeSwitch(true); yield break; } private IEnumerator StopVR() { - BeforeVRModeSwitch(false); + PreVRModeSwitch(false); yield return null; if (!string.IsNullOrEmpty(XRSettings.loadedDeviceName)) { + //SteamVR.SafeDispose(); //might fuck with SteamVRTrackingModule //deactivate the action set so SteamVR_Input.Initialize can reactivate SteamVR_Input.actionSets[0].Deactivate(SteamVR_Input_Sources.Any); - SteamVR.SafeDispose(); //idk XRSettings.LoadDeviceByName(""); XRSettings.enabled = false; yield return null; - //reset physics time to Desktop default - Time.fixedDeltaTime = 0.02f; - AfterVRModeSwitch(false); + Time.fixedDeltaTime = 0.02f; //reset physics time to Desktop default + PostVRModeSwitch(false); + yield break; } + DesktopVRSwitchMod.Logger.Error("Attempted to exit VR without a VR device loaded."); + FailedVRModeSwitch(true); yield break; } + //one frame after switch attempt + public void FailedVRModeSwitch(bool enterVR) + { + //let tracked objects know a switch failed + VRModeSwitchTracker.FailVRModeSwitch(enterVR); + } + //one frame before switch attempt - public void BeforeVRModeSwitch(bool enterVR) + public void PreVRModeSwitch(bool enterVR) { //let tracked objects know we are attempting to switch VRModeSwitchTracker.PreVRModeSwitch(enterVR); } //one frame after switch attempt - public void AfterVRModeSwitch(bool enterVR) + public void PostVRModeSwitch(bool enterVR) { //close the menus TryCatchHell.CloseCohtmlMenus(); - //these two must come first + //the base of VR checks TryCatchHell.SetCheckVR(enterVR); TryCatchHell.SetMetaPort(enterVR); - //the bulk of funni changes + //game basics for functional gameplay post switch TryCatchHell.RepositionCohtmlHud(enterVR); TryCatchHell.UpdateHudOperations(enterVR); TryCatchHell.DisableMirrorCanvas(); diff --git a/DesktopVRSwitch/Patches/VRModeSwitchTracker.cs b/DesktopVRSwitch/Patches/VRModeSwitchTracker.cs index d6f20c3..4e4bd4e 100644 --- a/DesktopVRSwitch/Patches/VRModeSwitchTracker.cs +++ b/DesktopVRSwitch/Patches/VRModeSwitchTracker.cs @@ -8,6 +8,7 @@ public class VRModeSwitchTracker { public static event UnityAction OnPreVRModeSwitch; public static event UnityAction OnPostVRModeSwitch; + public static event UnityAction OnFailVRModeSwitch; public static void PreVRModeSwitch(bool enterVR) { @@ -30,4 +31,15 @@ public class VRModeSwitchTracker }, "Error while invoking VRModeSwitchTracker.OnPostVRModeSwitch. Did someone do a fucky?"); } + + public static void FailVRModeSwitch(bool enterVR) + { + TryCatchHell.TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Invoking VRModeSwitchTracker.OnFailVRModeSwitch."); + Camera activeCamera = PlayerSetup.Instance.GetActiveCamera().GetComponent(); + VRModeSwitchTracker.OnFailVRModeSwitch?.Invoke(enterVR, activeCamera); + }, + "Error while invoking OnFailVRModeSwitch.OnPreVRModeSwitch. Did someone do a fucky?"); + } } \ No newline at end of file From dcde01c2a9a5ef66411cc679ff2f4b6a874a8aff Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 18 Feb 2023 09:49:38 -0600 Subject: [PATCH 38/42] ocd --- DesktopVRSwitch/DesktopVRSwitch.cs | 22 +++++++++---------- .../Patches/CVRPickupObjectTracker.cs | 2 +- .../Patches/CameraFacingObjectTracker.cs | 2 +- DesktopVRSwitch/Patches/IKSystemTracker.cs | 4 ++-- .../Patches/MovementSystemTracker.cs | 6 ++--- .../Patches/VRModeSwitchTracker.cs | 12 +++++----- .../Patches/VRTrackerManagerTracker.cs | 2 +- DesktopVRSwitch/Properties/AssemblyInfo.cs | 2 +- DesktopVRSwitch/TryCatchHell.cs | 1 - 9 files changed, 26 insertions(+), 27 deletions(-) diff --git a/DesktopVRSwitch/DesktopVRSwitch.cs b/DesktopVRSwitch/DesktopVRSwitch.cs index aca9c01..736bf0d 100644 --- a/DesktopVRSwitch/DesktopVRSwitch.cs +++ b/DesktopVRSwitch/DesktopVRSwitch.cs @@ -89,40 +89,40 @@ public class DesktopVRSwitch : MonoBehaviour } //one frame after switch attempt - public void FailedVRModeSwitch(bool enterVR) + public void FailedVRModeSwitch(bool isVR) { //let tracked objects know a switch failed - VRModeSwitchTracker.FailVRModeSwitch(enterVR); + VRModeSwitchTracker.FailVRModeSwitch(isVR); } //one frame before switch attempt - public void PreVRModeSwitch(bool enterVR) + public void PreVRModeSwitch(bool isVR) { //let tracked objects know we are attempting to switch - VRModeSwitchTracker.PreVRModeSwitch(enterVR); + VRModeSwitchTracker.PreVRModeSwitch(isVR); } //one frame after switch attempt - public void PostVRModeSwitch(bool enterVR) + public void PostVRModeSwitch(bool isVR) { //close the menus TryCatchHell.CloseCohtmlMenus(); //the base of VR checks - TryCatchHell.SetCheckVR(enterVR); - TryCatchHell.SetMetaPort(enterVR); + TryCatchHell.SetCheckVR(isVR); + TryCatchHell.SetMetaPort(isVR); //game basics for functional gameplay post switch - TryCatchHell.RepositionCohtmlHud(enterVR); - TryCatchHell.UpdateHudOperations(enterVR); + TryCatchHell.RepositionCohtmlHud(isVR); + TryCatchHell.UpdateHudOperations(isVR); TryCatchHell.DisableMirrorCanvas(); - TryCatchHell.SwitchActiveCameraRigs(enterVR); + TryCatchHell.SwitchActiveCameraRigs(isVR); TryCatchHell.ResetCVRInputManager(); TryCatchHell.UpdateRichPresence(); TryCatchHell.UpdateGestureReconizerCam(); //let tracked objects know we switched - VRModeSwitchTracker.PostVRModeSwitch(enterVR); + VRModeSwitchTracker.PostVRModeSwitch(isVR); //reload avatar by default, optional for debugging if (_reloadLocalAvatar) diff --git a/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs b/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs index 3f73d51..20cb1c6 100644 --- a/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs +++ b/DesktopVRSwitch/Patches/CVRPickupObjectTracker.cs @@ -20,7 +20,7 @@ public class CVRPickupObjectTracker : MonoBehaviour VRModeSwitchTracker.OnPostVRModeSwitch -= PostVRModeSwitch; } - public void PostVRModeSwitch(bool enterVR, Camera activeCamera) + public void PostVRModeSwitch(bool isVR, Camera activeCamera) { if (pickupObject != null) { diff --git a/DesktopVRSwitch/Patches/CameraFacingObjectTracker.cs b/DesktopVRSwitch/Patches/CameraFacingObjectTracker.cs index 918e925..e3d59ca 100644 --- a/DesktopVRSwitch/Patches/CameraFacingObjectTracker.cs +++ b/DesktopVRSwitch/Patches/CameraFacingObjectTracker.cs @@ -17,7 +17,7 @@ public class CameraFacingObjectTracker : MonoBehaviour VRModeSwitchTracker.OnPostVRModeSwitch -= PostVRModeSwitch; } - public void PostVRModeSwitch(bool enterVR, Camera activeCamera) + public void PostVRModeSwitch(bool isVR, Camera activeCamera) { cameraFacingObject.m_Camera = activeCamera; } diff --git a/DesktopVRSwitch/Patches/IKSystemTracker.cs b/DesktopVRSwitch/Patches/IKSystemTracker.cs index 7258a41..a8b9a22 100644 --- a/DesktopVRSwitch/Patches/IKSystemTracker.cs +++ b/DesktopVRSwitch/Patches/IKSystemTracker.cs @@ -22,13 +22,13 @@ public class IKSystemTracker : MonoBehaviour VRModeSwitchTracker.OnPostVRModeSwitch -= PostVRModeSwitch; } - public void PostVRModeSwitch(bool enterVR, Camera activeCamera) + public void PostVRModeSwitch(bool isVR, Camera activeCamera) { var _trackingModules = _traverseModules.GetValue>(); SteamVRTrackingModule openVRTrackingModule = _trackingModules.FirstOrDefault(m => m is SteamVRTrackingModule) as SteamVRTrackingModule; if (openVRTrackingModule != null) { - if (enterVR) + if (isVR) { openVRTrackingModule.ModuleStart(); } diff --git a/DesktopVRSwitch/Patches/MovementSystemTracker.cs b/DesktopVRSwitch/Patches/MovementSystemTracker.cs index a54c07d..b20e249 100644 --- a/DesktopVRSwitch/Patches/MovementSystemTracker.cs +++ b/DesktopVRSwitch/Patches/MovementSystemTracker.cs @@ -22,7 +22,7 @@ public class MovementSystemTracker : MonoBehaviour VRModeSwitchTracker.OnPostVRModeSwitch -= PostVRModeSwitch; } - public void PreVRModeSwitch(bool enterVR, Camera activeCamera) + public void PreVRModeSwitch(bool isVR, Camera activeCamera) { //correct rotationPivot y position, so we dont teleport up/down Vector3 position = movementSystem.rotationPivot.transform.position; @@ -36,11 +36,11 @@ public class MovementSystemTracker : MonoBehaviour //so the user can still switch even if avatar is null (if it failed to load for example). } - public void PostVRModeSwitch(bool enterVR, Camera activeCamera) + public void PostVRModeSwitch(bool isVR, Camera activeCamera) { //lazy way of correcting Desktop & VR offset issue (game does the maths) movementSystem.TeleportToPosRot(preSwitchWorldPosition, preSwitchWorldRotation, false); //recenter desktop collision to player object - if (!enterVR) movementSystem.UpdateColliderCenter(movementSystem.transform.position); + if (!isVR) movementSystem.UpdateColliderCenter(movementSystem.transform.position); } } \ No newline at end of file diff --git a/DesktopVRSwitch/Patches/VRModeSwitchTracker.cs b/DesktopVRSwitch/Patches/VRModeSwitchTracker.cs index 4e4bd4e..a1a78d9 100644 --- a/DesktopVRSwitch/Patches/VRModeSwitchTracker.cs +++ b/DesktopVRSwitch/Patches/VRModeSwitchTracker.cs @@ -10,35 +10,35 @@ public class VRModeSwitchTracker public static event UnityAction OnPostVRModeSwitch; public static event UnityAction OnFailVRModeSwitch; - public static void PreVRModeSwitch(bool enterVR) + public static void PreVRModeSwitch(bool isVR) { TryCatchHell.TryCatchWrapper(() => { DesktopVRSwitchMod.Logger.Msg("Invoking VRModeSwitchTracker.OnPreVRModeSwitch."); Camera activeCamera = PlayerSetup.Instance.GetActiveCamera().GetComponent(); - VRModeSwitchTracker.OnPreVRModeSwitch?.Invoke(enterVR, activeCamera); + VRModeSwitchTracker.OnPreVRModeSwitch?.Invoke(isVR, activeCamera); }, "Error while invoking VRModeSwitchTracker.OnPreVRModeSwitch. Did someone do a fucky?"); } - public static void PostVRModeSwitch(bool enterVR) + public static void PostVRModeSwitch(bool isVR) { TryCatchHell.TryCatchWrapper(() => { DesktopVRSwitchMod.Logger.Msg("Invoking VRModeSwitchTracker.OnPostVRModeSwitch."); Camera activeCamera = PlayerSetup.Instance.GetActiveCamera().GetComponent(); - VRModeSwitchTracker.OnPostVRModeSwitch?.Invoke(enterVR, activeCamera); + VRModeSwitchTracker.OnPostVRModeSwitch?.Invoke(isVR, activeCamera); }, "Error while invoking VRModeSwitchTracker.OnPostVRModeSwitch. Did someone do a fucky?"); } - public static void FailVRModeSwitch(bool enterVR) + public static void FailVRModeSwitch(bool isVR) { TryCatchHell.TryCatchWrapper(() => { DesktopVRSwitchMod.Logger.Msg("Invoking VRModeSwitchTracker.OnFailVRModeSwitch."); Camera activeCamera = PlayerSetup.Instance.GetActiveCamera().GetComponent(); - VRModeSwitchTracker.OnFailVRModeSwitch?.Invoke(enterVR, activeCamera); + VRModeSwitchTracker.OnFailVRModeSwitch?.Invoke(isVR, activeCamera); }, "Error while invoking OnFailVRModeSwitch.OnPreVRModeSwitch. Did someone do a fucky?"); } diff --git a/DesktopVRSwitch/Patches/VRTrackerManagerTracker.cs b/DesktopVRSwitch/Patches/VRTrackerManagerTracker.cs index 8ef5e50..f19d579 100644 --- a/DesktopVRSwitch/Patches/VRTrackerManagerTracker.cs +++ b/DesktopVRSwitch/Patches/VRTrackerManagerTracker.cs @@ -22,7 +22,7 @@ public class VRTrackerManagerTracker : MonoBehaviour VRModeSwitchTracker.OnPostVRModeSwitch -= PostVRModeSwitch; } - public void PostVRModeSwitch(bool enterVR, Camera activeCamera) + public void PostVRModeSwitch(bool isVR, Camera activeCamera) { //force the VRTrackerManager to reset anything its stored //this makes it get correct Left/Right hand if entering VR with different controllers diff --git a/DesktopVRSwitch/Properties/AssemblyInfo.cs b/DesktopVRSwitch/Properties/AssemblyInfo.cs index dd5b9f7..91846c5 100644 --- a/DesktopVRSwitch/Properties/AssemblyInfo.cs +++ b/DesktopVRSwitch/Properties/AssemblyInfo.cs @@ -25,6 +25,6 @@ using System.Reflection; namespace NAK.Melons.DesktopVRSwitch.Properties; internal static class AssemblyInfoParams { - public const string Version = "4.3.1"; + public const string Version = "4.3.2"; public const string Author = "NotAKidoS"; } \ No newline at end of file diff --git a/DesktopVRSwitch/TryCatchHell.cs b/DesktopVRSwitch/TryCatchHell.cs index 9a1a332..effaf29 100644 --- a/DesktopVRSwitch/TryCatchHell.cs +++ b/DesktopVRSwitch/TryCatchHell.cs @@ -177,4 +177,3 @@ internal class TryCatchHell "Failed to update CVRGestureRecognizer camera."); } } - From 25c0b7cffe0e61ee8cd7493d930c810a038b6462 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 18 Feb 2023 10:15:48 -0600 Subject: [PATCH 39/42] bump --- DesktopVRSwitch/Properties/AssemblyInfo.cs | 2 +- DesktopVRSwitch/format.json | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/DesktopVRSwitch/Properties/AssemblyInfo.cs b/DesktopVRSwitch/Properties/AssemblyInfo.cs index 91846c5..85baf86 100644 --- a/DesktopVRSwitch/Properties/AssemblyInfo.cs +++ b/DesktopVRSwitch/Properties/AssemblyInfo.cs @@ -25,6 +25,6 @@ using System.Reflection; namespace NAK.Melons.DesktopVRSwitch.Properties; internal static class AssemblyInfoParams { - public const string Version = "4.3.2"; + public const string Version = "4.3.4"; public const string Author = "NotAKidoS"; } \ No newline at end of file diff --git a/DesktopVRSwitch/format.json b/DesktopVRSwitch/format.json index d9514e0..9d9566a 100644 --- a/DesktopVRSwitch/format.json +++ b/DesktopVRSwitch/format.json @@ -1,7 +1,7 @@ { "_id": 103, "name": "DesktopVRSwitch", - "modversion": "4.3.1", + "modversion": "4.3.4", "gameversion": "2022r170", "loaderversion": "0.5.7", "modtype": "Mod", @@ -16,8 +16,8 @@ "requirements": [ "None" ], - "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/v4.3.1/DesktopVRSwitch.dll", + "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/v4.3.4/DesktopVRSwitch.dll", "sourcelink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/", - "changelog": "- Backported rewrite from Experimental & patched up to handle OpenVR.\n- Reinitialize SteamVR input on switch incase user restarted SteamVR or changed controllers. Correct fixedDeltaTime when entering Desktop.\n- Many tweaks to ensure everything in-game functions as expected.", + "changelog": "- Backported rewrite from Experimental & patched up to handle OpenVR.\n- Reinitialize SteamVR input on switch incase user restarted SteamVR or changed controllers. Correct fixedDeltaTime when entering Desktop.\n- Many tweaks to ensure everything in-game functions as expected.\n- Tweak to initial switch position for correcting offsets.", "embedcolor": "3498db" } \ No newline at end of file From 94abe14f0c7a40cbf1d8606f504d97c9f6150aa3 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Sat, 18 Feb 2023 23:02:26 -0600 Subject: [PATCH 40/42] 4.3.5 --- DesktopVRSwitch/DesktopVRSwitch.cs | 3 ++- DesktopVRSwitch/HarmonyPatches.cs | 7 +++++++ DesktopVRSwitch/Main.cs | 8 ++++++-- DesktopVRSwitch/Patches/IKSystemTracker.cs | 2 +- DesktopVRSwitch/Patches/MovementSystemTracker.cs | 2 ++ DesktopVRSwitch/Properties/AssemblyInfo.cs | 3 ++- DesktopVRSwitch/TryCatchHell.cs | 10 ++++++++++ DesktopVRSwitch/format.json | 6 +++--- 8 files changed, 33 insertions(+), 8 deletions(-) diff --git a/DesktopVRSwitch/DesktopVRSwitch.cs b/DesktopVRSwitch/DesktopVRSwitch.cs index 736bf0d..36ba8d9 100644 --- a/DesktopVRSwitch/DesktopVRSwitch.cs +++ b/DesktopVRSwitch/DesktopVRSwitch.cs @@ -8,7 +8,7 @@ namespace NAK.Melons.DesktopVRSwitch; public class DesktopVRSwitch : MonoBehaviour { - //Settings + //Debug Setting public bool _reloadLocalAvatar = true; //Internal Stuff @@ -120,6 +120,7 @@ public class DesktopVRSwitch : MonoBehaviour TryCatchHell.ResetCVRInputManager(); TryCatchHell.UpdateRichPresence(); TryCatchHell.UpdateGestureReconizerCam(); + TryCatchHell.UpdateMenuCoreData(isVR); //let tracked objects know we switched VRModeSwitchTracker.PostVRModeSwitch(isVR); diff --git a/DesktopVRSwitch/HarmonyPatches.cs b/DesktopVRSwitch/HarmonyPatches.cs index 93dad81..0b7b1e0 100644 --- a/DesktopVRSwitch/HarmonyPatches.cs +++ b/DesktopVRSwitch/HarmonyPatches.cs @@ -89,6 +89,13 @@ internal class IKSystemPatches { __instance.gameObject.AddComponent(); } + + [HarmonyPostfix] //lazy fix so i dont need to wait few frames + [HarmonyPatch(typeof(TrackingPoint), "Initialize")] + private static void Postfix_TrackingPoint_Initialize(ref TrackingPoint __instance) + { + __instance.referenceTransform.localScale = Vector3.one; + } } internal class VRTrackerManagerPatches diff --git a/DesktopVRSwitch/Main.cs b/DesktopVRSwitch/Main.cs index 5bf1280..d61ac90 100644 --- a/DesktopVRSwitch/Main.cs +++ b/DesktopVRSwitch/Main.cs @@ -18,13 +18,17 @@ namespace NAK.Melons.DesktopVRSwitch; public class DesktopVRSwitchMod : MelonMod { internal const string SettingsCategory = "DesktopVRSwitch"; - internal static MelonPreferences_Category m_categoryDesktopVRSwitch; + internal static MelonPreferences_Category mCategory; internal static MelonLogger.Instance Logger; + internal static MelonPreferences_Entry + mSetting_EnterCalibrationOnSwitch; + public override void OnInitializeMelon() { Logger = LoggerInstance; - m_categoryDesktopVRSwitch = MelonPreferences.CreateCategory(SettingsCategory); + mCategory = MelonPreferences.CreateCategory(SettingsCategory); + mSetting_EnterCalibrationOnSwitch = mCategory.CreateEntry("Enter Calibration on Switch", true, description: "Should you automatically be placed into calibration after switch if FBT is available? Overridden by Save Calibration IK setting."); ApplyPatches(typeof(HarmonyPatches.PlayerSetupPatches)); ApplyPatches(typeof(HarmonyPatches.CVRPickupObjectPatches)); diff --git a/DesktopVRSwitch/Patches/IKSystemTracker.cs b/DesktopVRSwitch/Patches/IKSystemTracker.cs index a8b9a22..583aa9b 100644 --- a/DesktopVRSwitch/Patches/IKSystemTracker.cs +++ b/DesktopVRSwitch/Patches/IKSystemTracker.cs @@ -45,7 +45,7 @@ public class IKSystemTracker : MonoBehaviour } //make it so you dont instantly end up in FBT from Desktop - IKSystem.firstAvatarLoaded = false; + IKSystem.firstAvatarLoaded = DesktopVRSwitchMod.mSetting_EnterCalibrationOnSwitch.Value; //turn of finger tracking just in case user switched controllers ikSystem.FingerSystem.controlActive = false; } diff --git a/DesktopVRSwitch/Patches/MovementSystemTracker.cs b/DesktopVRSwitch/Patches/MovementSystemTracker.cs index b20e249..cab5666 100644 --- a/DesktopVRSwitch/Patches/MovementSystemTracker.cs +++ b/DesktopVRSwitch/Patches/MovementSystemTracker.cs @@ -38,6 +38,8 @@ public class MovementSystemTracker : MonoBehaviour public void PostVRModeSwitch(bool isVR, Camera activeCamera) { + //immediatly update camera to new camera transform + movementSystem.rotationPivot = activeCamera.transform; //lazy way of correcting Desktop & VR offset issue (game does the maths) movementSystem.TeleportToPosRot(preSwitchWorldPosition, preSwitchWorldRotation, false); //recenter desktop collision to player object diff --git a/DesktopVRSwitch/Properties/AssemblyInfo.cs b/DesktopVRSwitch/Properties/AssemblyInfo.cs index 85baf86..bd527e7 100644 --- a/DesktopVRSwitch/Properties/AssemblyInfo.cs +++ b/DesktopVRSwitch/Properties/AssemblyInfo.cs @@ -20,11 +20,12 @@ using System.Reflection; [assembly: MelonGame("Alpha Blend Interactive", "ChilloutVR")] [assembly: MelonPlatform(MelonPlatformAttribute.CompatiblePlatforms.WINDOWS_X64)] [assembly: MelonPlatformDomain(MelonPlatformDomainAttribute.CompatibleDomains.MONO)] +[assembly: MelonColor(ConsoleColor.DarkCyan)] [assembly: HarmonyDontPatchAll] namespace NAK.Melons.DesktopVRSwitch.Properties; internal static class AssemblyInfoParams { - public const string Version = "4.3.4"; + public const string Version = "4.3.5"; public const string Author = "NotAKidoS"; } \ No newline at end of file diff --git a/DesktopVRSwitch/TryCatchHell.cs b/DesktopVRSwitch/TryCatchHell.cs index effaf29..78f3f90 100644 --- a/DesktopVRSwitch/TryCatchHell.cs +++ b/DesktopVRSwitch/TryCatchHell.cs @@ -176,4 +176,14 @@ internal class TryCatchHell }, "Failed to update CVRGestureRecognizer camera."); } + + internal static void UpdateMenuCoreData(bool isVR) + { + TryCatchWrapper(() => + { + DesktopVRSwitchMod.Logger.Msg("Updating CVR_Menu_Data core data."); + CVR_MenuManager.Instance.coreData.core.inVr = isVR; + }, + "Failed to update CVR_Menu_Data core data."); + } } diff --git a/DesktopVRSwitch/format.json b/DesktopVRSwitch/format.json index 9d9566a..0373abd 100644 --- a/DesktopVRSwitch/format.json +++ b/DesktopVRSwitch/format.json @@ -1,7 +1,7 @@ { "_id": 103, "name": "DesktopVRSwitch", - "modversion": "4.3.4", + "modversion": "4.3.5", "gameversion": "2022r170", "loaderversion": "0.5.7", "modtype": "Mod", @@ -16,8 +16,8 @@ "requirements": [ "None" ], - "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/v4.3.4/DesktopVRSwitch.dll", + "downloadlink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/releases/download/v4.3.5/DesktopVRSwitch.dll", "sourcelink": "https://github.com/NotAKidOnSteam/DesktopVRSwitch/", - "changelog": "- Backported rewrite from Experimental & patched up to handle OpenVR.\n- Reinitialize SteamVR input on switch incase user restarted SteamVR or changed controllers. Correct fixedDeltaTime when entering Desktop.\n- Many tweaks to ensure everything in-game functions as expected.\n- Tweak to initial switch position for correcting offsets.", + "changelog": "- Reinitialize SteamVR input on switch. Correct fixedDeltaTime when entering Desktop.\n- Tweak to initial switch position for correcting offsets.\n- Fixed FBT tracking point initial size.\n- Update core menu data so QM Recalibrate/SeatedPlay button works.", "embedcolor": "3498db" } \ No newline at end of file From 7e942d61cc73e4ea2b0dc116798bb1134ecdae3a Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Tue, 21 Feb 2023 04:23:55 -0600 Subject: [PATCH 41/42] funky patch for FBT --- DesktopVRSwitch/DesktopVRSwitch.cs | 6 +++++- DesktopVRSwitch/HarmonyPatches.cs | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/DesktopVRSwitch/DesktopVRSwitch.cs b/DesktopVRSwitch/DesktopVRSwitch.cs index 36ba8d9..529cd96 100644 --- a/DesktopVRSwitch/DesktopVRSwitch.cs +++ b/DesktopVRSwitch/DesktopVRSwitch.cs @@ -8,8 +8,9 @@ namespace NAK.Melons.DesktopVRSwitch; public class DesktopVRSwitch : MonoBehaviour { - //Debug Setting + //Debug Settings public bool _reloadLocalAvatar = true; + public bool _softVRSwitch = false; //Internal Stuff private bool _switchInProgress = false; @@ -91,6 +92,7 @@ public class DesktopVRSwitch : MonoBehaviour //one frame after switch attempt public void FailedVRModeSwitch(bool isVR) { + if (_softVRSwitch) return; //let tracked objects know a switch failed VRModeSwitchTracker.FailVRModeSwitch(isVR); } @@ -98,6 +100,7 @@ public class DesktopVRSwitch : MonoBehaviour //one frame before switch attempt public void PreVRModeSwitch(bool isVR) { + if (_softVRSwitch) return; //let tracked objects know we are attempting to switch VRModeSwitchTracker.PreVRModeSwitch(isVR); } @@ -105,6 +108,7 @@ public class DesktopVRSwitch : MonoBehaviour //one frame after switch attempt public void PostVRModeSwitch(bool isVR) { + if (_softVRSwitch) return; //close the menus TryCatchHell.CloseCohtmlMenus(); diff --git a/DesktopVRSwitch/HarmonyPatches.cs b/DesktopVRSwitch/HarmonyPatches.cs index 0b7b1e0..50e6e0a 100644 --- a/DesktopVRSwitch/HarmonyPatches.cs +++ b/DesktopVRSwitch/HarmonyPatches.cs @@ -3,6 +3,7 @@ using ABI_RC.Core.Player; using ABI_RC.Core.Savior; using ABI_RC.Core.Util.Object_Behaviour; using ABI_RC.Systems.IK; +using ABI_RC.Systems.IK.TrackingModules; using ABI_RC.Systems.MovementSystem; using HarmonyLib; using NAK.Melons.DesktopVRSwitch.Patches; @@ -96,6 +97,16 @@ internal class IKSystemPatches { __instance.referenceTransform.localScale = Vector3.one; } + [HarmonyPostfix] //lazy fix so device indecies can change properly + [HarmonyPatch(typeof(SteamVRTrackingModule), "ModuleDestroy")] + private static void Postfix_SteamVRTrackingModule_ModuleDestroy(ref SteamVRTrackingModule __instance) + { + for (int i = 0; i < __instance.TrackingPoints.Count; i++) + { + UnityEngine.Object.Destroy(__instance.TrackingPoints[i].referenceGameObject); + } + __instance.TrackingPoints.Clear(); + } } internal class VRTrackerManagerPatches From 268fd422164599475077490e904a93fba83effb1 Mon Sep 17 00:00:00 2001 From: NotAKidoS <37721153+NotAKidOnSteam@users.noreply.github.com> Date: Tue, 21 Feb 2023 04:37:45 -0600 Subject: [PATCH 42/42] stuff got reverted??? --- DesktopVRSwitch/DesktopVRSwitch.cs | 2 +- DesktopVRSwitch/Patches/ReferenceCameraFix.cs | 127 ------------------ 2 files changed, 1 insertion(+), 128 deletions(-) delete mode 100644 DesktopVRSwitch/Patches/ReferenceCameraFix.cs diff --git a/DesktopVRSwitch/DesktopVRSwitch.cs b/DesktopVRSwitch/DesktopVRSwitch.cs index 529cd96..30da9de 100644 --- a/DesktopVRSwitch/DesktopVRSwitch.cs +++ b/DesktopVRSwitch/DesktopVRSwitch.cs @@ -85,7 +85,7 @@ public class DesktopVRSwitch : MonoBehaviour yield break; } DesktopVRSwitchMod.Logger.Error("Attempted to exit VR without a VR device loaded."); - FailedVRModeSwitch(true); + FailedVRModeSwitch(false); yield break; } diff --git a/DesktopVRSwitch/Patches/ReferenceCameraFix.cs b/DesktopVRSwitch/Patches/ReferenceCameraFix.cs deleted file mode 100644 index d1bc27b..0000000 --- a/DesktopVRSwitch/Patches/ReferenceCameraFix.cs +++ /dev/null @@ -1,127 +0,0 @@ -using ABI.CCK.Components; -using ABI_RC.Core.Base; -using ABI_RC.Core.Player; -using ABI_RC.Core.Savior; -using Aura2API; -using BeautifyEffect; -using HarmonyLib; -using UnityEngine; -using UnityEngine.AzureSky; -using UnityEngine.Rendering.PostProcessing; -using Object = UnityEngine.Object; - -namespace DesktopVRSwitch.Patches; - -[HarmonyPatch] -internal class ReferenceCameraFix -{ - [HarmonyPostfix] - [HarmonyPatch(typeof(CVRWorld), "SetDefaultCamValues")] - private static void CVRWorld_SetDefaultCamValues_Postfix(ref CVRWorld __instance) - { - Camera active; - Camera nonActive; - if (MetaPort.Instance.isUsingVr) - { - active = PlayerSetup.Instance.vrCamera.GetComponent(); - nonActive = PlayerSetup.Instance.desktopCamera.GetComponent(); - } - else - { - active = PlayerSetup.Instance.desktopCamera.GetComponent(); - nonActive = PlayerSetup.Instance.vrCamera.GetComponent(); - } - CopyActiveCamera(active, nonActive); - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(CVRWorld), "CopyRefCamValues")] - private static void CVRWorld_CopyRefCamValues_Postfix(ref CVRWorld __instance) - { - Camera active; - Camera nonActive; - if (MetaPort.Instance.isUsingVr) - { - active = PlayerSetup.Instance.vrCamera.GetComponent(); - nonActive = PlayerSetup.Instance.desktopCamera.GetComponent(); - } - else - { - active = PlayerSetup.Instance.desktopCamera.GetComponent(); - nonActive = PlayerSetup.Instance.vrCamera.GetComponent(); - } - CopyActiveCamera(active, nonActive); - } - - private static void CopyActiveCamera(Camera activeCamera, Camera inactiveCamera) - { - //steal basic settings - inactiveCamera.farClipPlane = activeCamera.farClipPlane; - inactiveCamera.nearClipPlane = activeCamera.nearClipPlane; - inactiveCamera.cullingMask = activeCamera.cullingMask; - inactiveCamera.depthTextureMode = activeCamera.depthTextureMode; - - //steal post processing if added - PostProcessLayer ppLayerActive = activeCamera.GetComponent(); - PostProcessLayer ppLayerNonActive = inactiveCamera.GetComponent(); - if (ppLayerActive != null && ppLayerNonActive != null) - { - ppLayerNonActive.enabled = ppLayerActive.enabled; - ppLayerNonActive.volumeLayer = ppLayerActive.volumeLayer; - } - - //what even is this aura camera stuff - AuraCamera auraActive = activeCamera.GetComponent(); - AuraCamera auraNonActive = inactiveCamera.AddComponentIfMissing(); - if (auraActive != null && auraNonActive != null) - { - auraNonActive.enabled = auraActive.enabled; - auraNonActive.frustumSettings = auraActive.frustumSettings; - } - else - { - auraNonActive.enabled = false; - } - - //flare layer thing? the sun :_:_:_:_:_: - FlareLayer flareActive = activeCamera.GetComponent(); - FlareLayer flareNonActive = inactiveCamera.AddComponentIfMissing(); - if (flareActive != null && flareNonActive != null) - { - flareNonActive.enabled = flareActive.enabled; - } - else - { - flareNonActive.enabled = false; - } - - //set correct farclipplane so effect is correct on switching world after switch - PlayerSetup.Instance.transitionEffectVr.material.SetFloat("ClippingPlane", activeCamera.farClipPlane); - PlayerSetup.Instance.transitionEffectDesktop.material.SetFloat("ClippingPlane", activeCamera.farClipPlane); - - //and now what the fuck is fog scattering - AzureFogScattering azureFogActive = activeCamera.GetComponent(); - AzureFogScattering azureFogNonActive = inactiveCamera.AddComponentIfMissing(); - if (azureFogActive != null && azureFogNonActive != null) - { - azureFogNonActive.fogScatteringMaterial = azureFogActive.fogScatteringMaterial; - } - else - { - Object.Destroy(inactiveCamera.GetComponent()); - } - - //why is there so many thingsssssssss - Beautify beautifyActive = activeCamera.GetComponent(); - Beautify beautifyNonActive = inactiveCamera.AddComponentIfMissing(); - if (beautifyActive != null && beautifyNonActive != null) - { - beautifyNonActive.quality = beautifyActive.quality; - beautifyNonActive.profile = beautifyActive.profile; - } - else - { - Object.Destroy(inactiveCamera.gameObject.GetComponent()); - } - } -} \ No newline at end of file