diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 000000000..b7085d7cc Binary files /dev/null and b/.DS_Store differ diff --git a/ClassicUO.licenseheader b/ClassicUO.licenseheader deleted file mode 100644 index 8e792d850..000000000 --- a/ClassicUO.licenseheader +++ /dev/null @@ -1,30 +0,0 @@ -extensions: .cs -#region license -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion \ No newline at end of file diff --git a/ClassicUO.sln b/ClassicUO.sln deleted file mode 100644 index 72a688832..000000000 --- a/ClassicUO.sln +++ /dev/null @@ -1,142 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.4.33205.214 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{36371756-8DDA-41A4-BB9A-B7651459ADC1}" - ProjectSection(SolutionItems) = preProject - README.md = README.md - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "scripts", "scripts", "{FD7202D2-B96B-4425-8C61-F0D5254A06F7}" - ProjectSection(SolutionItems) = preProject - scripts\build.cmd = scripts\build.cmd - scripts\build.sh = scripts\build.sh - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{D5E764E7-2719-4937-AC10-0D2D789A1134}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ManifestCreator", "tools\ManifestCreator\ManifestCreator.csproj", "{6F193271-70B3-48EC-9CE5-B8EE1A5CA89E}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "monokickstart", "monokickstart", "{D7DD340F-1EE2-4F8A-AA3E-A8FC76098AD6}" - ProjectSection(SolutionItems) = preProject - tools\monokickstart\Accessibility.dll = tools\monokickstart\Accessibility.dll - tools\monokickstart\ClassicUO = tools\monokickstart\ClassicUO - tools\monokickstart\ClassicUO.bin.osx = tools\monokickstart\ClassicUO.bin.osx - tools\monokickstart\ClassicUO.bin.x86_64 = tools\monokickstart\ClassicUO.bin.x86_64 - tools\monokickstart\Microsoft.CSharp.dll = tools\monokickstart\Microsoft.CSharp.dll - tools\monokickstart\Mono.Posix.dll = tools\monokickstart\Mono.Posix.dll - tools\monokickstart\Mono.Security.dll = tools\monokickstart\Mono.Security.dll - tools\monokickstart\monoconfig = tools\monokickstart\monoconfig - tools\monokickstart\monomachineconfig = tools\monokickstart\monomachineconfig - tools\monokickstart\mscorlib.dll = tools\monokickstart\mscorlib.dll - tools\monokickstart\Newtonsoft.Json.dll = tools\monokickstart\Newtonsoft.Json.dll - tools\monokickstart\System.Configuration.dll = tools\monokickstart\System.Configuration.dll - tools\monokickstart\System.Core.dll = tools\monokickstart\System.Core.dll - tools\monokickstart\System.Data.dll = tools\monokickstart\System.Data.dll - tools\monokickstart\System.dll = tools\monokickstart\System.dll - tools\monokickstart\System.Drawing.dll = tools\monokickstart\System.Drawing.dll - tools\monokickstart\System.IO.Compression.dll = tools\monokickstart\System.IO.Compression.dll - tools\monokickstart\System.IO.Compression.FileSystem.dll = tools\monokickstart\System.IO.Compression.FileSystem.dll - tools\monokickstart\System.Numerics.dll = tools\monokickstart\System.Numerics.dll - tools\monokickstart\System.Runtime.Serialization.dll = tools\monokickstart\System.Runtime.Serialization.dll - tools\monokickstart\System.Security.dll = tools\monokickstart\System.Security.dll - tools\monokickstart\System.Windows.Forms.dll = tools\monokickstart\System.Windows.Forms.dll - tools\monokickstart\System.Xml.dll = tools\monokickstart\System.Xml.dll - tools\monokickstart\System.Xml.Linq.dll = tools\monokickstart\System.Xml.Linq.dll - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "settings", "settings", "{21AF20E5-1A3A-414D-9B1F-AB8F3800E567}" - ProjectSection(SolutionItems) = preProject - .editorconfig = .editorconfig - ClassicUO.licenseheader = ClassicUO.licenseheader - ClassicUO.sln.DotSettings = ClassicUO.sln.DotSettings - Directory.Build.props = Directory.Build.props - FNA.Settings.props = FNA.Settings.props - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{B766E918-7350-473A-B28D-63C344385924}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClassicUO.UnitTests", "tests\ClassicUO.UnitTests\ClassicUO.UnitTests.csproj", "{85972CEA-4AB1-45DC-922C-00C4E17764B5}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FNA.Core", "external\FNA\FNA.Core.csproj", "{3F9AB6CE-3AD1-40B6-B2AA-C4D82F76258F}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClassicUO.Client", "src\ClassicUO.Client\ClassicUO.Client.csproj", "{D7EE32B0-ED1C-4263-B017-6C3EC74FD731}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClassicUO.Assets", "src\ClassicUO.Assets\ClassicUO.Assets.csproj", "{DDF690A2-7588-44BC-8E2E-9080C746A49C}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClassicUO.Utility", "src\ClassicUO.Utility\ClassicUO.Utility.csproj", "{6B932930-D24C-43BB-8877-85B4F3F7A57B}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "external", "external", "{FA5D7AB8-3570-4E55-95B0-35BA6842FEE3}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClassicUO.Renderer", "src\ClassicUO.Renderer\ClassicUO.Renderer.csproj", "{535BE739-1314-4F8D-B24B-06890DDD3B8D}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClassicUO.IO", "src\ClassicUO.IO\ClassicUO.IO.csproj", "{69C1A629-F519-4F5A-85D5-4E0317CD267F}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MP3Sharp", "external\MP3Sharp\MP3Sharp\MP3Sharp.csproj", "{5AF00B6D-70C2-4CB0-A5D8-41F488F0DDF2}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FontStashSharp.FNA.Core", "external\FontStashSharp\src\XNA\FontStashSharp.FNA.Core.csproj", "{5ACA68DA-A282-434D-919F-B243A801D4C3}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {6F193271-70B3-48EC-9CE5-B8EE1A5CA89E}.Debug|x64.ActiveCfg = Debug|x64 - {6F193271-70B3-48EC-9CE5-B8EE1A5CA89E}.Release|x64.ActiveCfg = Release|x64 - {85972CEA-4AB1-45DC-922C-00C4E17764B5}.Debug|x64.ActiveCfg = Debug|x64 - {85972CEA-4AB1-45DC-922C-00C4E17764B5}.Release|x64.ActiveCfg = Release|x64 - {3F9AB6CE-3AD1-40B6-B2AA-C4D82F76258F}.Debug|x64.ActiveCfg = Debug|x64 - {3F9AB6CE-3AD1-40B6-B2AA-C4D82F76258F}.Debug|x64.Build.0 = Debug|x64 - {3F9AB6CE-3AD1-40B6-B2AA-C4D82F76258F}.Release|x64.ActiveCfg = Release|x64 - {3F9AB6CE-3AD1-40B6-B2AA-C4D82F76258F}.Release|x64.Build.0 = Release|x64 - {D7EE32B0-ED1C-4263-B017-6C3EC74FD731}.Debug|x64.ActiveCfg = Debug|x64 - {D7EE32B0-ED1C-4263-B017-6C3EC74FD731}.Debug|x64.Build.0 = Debug|x64 - {D7EE32B0-ED1C-4263-B017-6C3EC74FD731}.Release|x64.ActiveCfg = Release|x64 - {D7EE32B0-ED1C-4263-B017-6C3EC74FD731}.Release|x64.Build.0 = Release|x64 - {DDF690A2-7588-44BC-8E2E-9080C746A49C}.Debug|x64.ActiveCfg = Debug|x64 - {DDF690A2-7588-44BC-8E2E-9080C746A49C}.Debug|x64.Build.0 = Debug|x64 - {DDF690A2-7588-44BC-8E2E-9080C746A49C}.Release|x64.ActiveCfg = Release|x64 - {DDF690A2-7588-44BC-8E2E-9080C746A49C}.Release|x64.Build.0 = Release|x64 - {6B932930-D24C-43BB-8877-85B4F3F7A57B}.Debug|x64.ActiveCfg = Debug|x64 - {6B932930-D24C-43BB-8877-85B4F3F7A57B}.Debug|x64.Build.0 = Debug|x64 - {6B932930-D24C-43BB-8877-85B4F3F7A57B}.Release|x64.ActiveCfg = Release|x64 - {6B932930-D24C-43BB-8877-85B4F3F7A57B}.Release|x64.Build.0 = Release|x64 - {535BE739-1314-4F8D-B24B-06890DDD3B8D}.Debug|x64.ActiveCfg = Debug|x64 - {535BE739-1314-4F8D-B24B-06890DDD3B8D}.Debug|x64.Build.0 = Debug|x64 - {535BE739-1314-4F8D-B24B-06890DDD3B8D}.Release|x64.ActiveCfg = Release|x64 - {535BE739-1314-4F8D-B24B-06890DDD3B8D}.Release|x64.Build.0 = Release|x64 - {69C1A629-F519-4F5A-85D5-4E0317CD267F}.Debug|x64.ActiveCfg = Debug|x64 - {69C1A629-F519-4F5A-85D5-4E0317CD267F}.Debug|x64.Build.0 = Debug|x64 - {69C1A629-F519-4F5A-85D5-4E0317CD267F}.Release|x64.ActiveCfg = Release|x64 - {69C1A629-F519-4F5A-85D5-4E0317CD267F}.Release|x64.Build.0 = Release|x64 - {5AF00B6D-70C2-4CB0-A5D8-41F488F0DDF2}.Debug|x64.ActiveCfg = Debug|x64 - {5AF00B6D-70C2-4CB0-A5D8-41F488F0DDF2}.Debug|x64.Build.0 = Debug|x64 - {5AF00B6D-70C2-4CB0-A5D8-41F488F0DDF2}.Release|x64.ActiveCfg = Release|x64 - {5AF00B6D-70C2-4CB0-A5D8-41F488F0DDF2}.Release|x64.Build.0 = Release|x64 - {5ACA68DA-A282-434D-919F-B243A801D4C3}.Debug|x64.ActiveCfg = Debug|Any CPU - {5ACA68DA-A282-434D-919F-B243A801D4C3}.Debug|x64.Build.0 = Debug|Any CPU - {5ACA68DA-A282-434D-919F-B243A801D4C3}.Release|x64.ActiveCfg = Release|Any CPU - {5ACA68DA-A282-434D-919F-B243A801D4C3}.Release|x64.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {6F193271-70B3-48EC-9CE5-B8EE1A5CA89E} = {D5E764E7-2719-4937-AC10-0D2D789A1134} - {D7DD340F-1EE2-4F8A-AA3E-A8FC76098AD6} = {D5E764E7-2719-4937-AC10-0D2D789A1134} - {85972CEA-4AB1-45DC-922C-00C4E17764B5} = {B766E918-7350-473A-B28D-63C344385924} - {3F9AB6CE-3AD1-40B6-B2AA-C4D82F76258F} = {FA5D7AB8-3570-4E55-95B0-35BA6842FEE3} - {D7EE32B0-ED1C-4263-B017-6C3EC74FD731} = {36371756-8DDA-41A4-BB9A-B7651459ADC1} - {DDF690A2-7588-44BC-8E2E-9080C746A49C} = {36371756-8DDA-41A4-BB9A-B7651459ADC1} - {6B932930-D24C-43BB-8877-85B4F3F7A57B} = {36371756-8DDA-41A4-BB9A-B7651459ADC1} - {535BE739-1314-4F8D-B24B-06890DDD3B8D} = {36371756-8DDA-41A4-BB9A-B7651459ADC1} - {69C1A629-F519-4F5A-85D5-4E0317CD267F} = {36371756-8DDA-41A4-BB9A-B7651459ADC1} - {5AF00B6D-70C2-4CB0-A5D8-41F488F0DDF2} = {FA5D7AB8-3570-4E55-95B0-35BA6842FEE3} - {5ACA68DA-A282-434D-919F-B243A801D4C3} = {FA5D7AB8-3570-4E55-95B0-35BA6842FEE3} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {0A99E91A-ADAB-45C3-8170-2656140F6EFA} - EndGlobalSection -EndGlobal diff --git a/ClassicUO.sln.DotSettings b/ClassicUO.sln.DotSettings deleted file mode 100644 index 176e5ac53..000000000 --- a/ClassicUO.sln.DotSettings +++ /dev/null @@ -1,11 +0,0 @@ - - DO_NOT_SHOW - DO_NOT_SHOW - DO_NOT_SHOW - DO_NOT_SHOW - UO - <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /> - - True - True - True \ No newline at end of file diff --git a/Directory.Build.props b/Directory.Build.props deleted file mode 100644 index 39a22ac87..000000000 --- a/Directory.Build.props +++ /dev/null @@ -1,47 +0,0 @@ - - - - net472 - Preview - x64 - x64 - true - true - true - true - false - false - PackageReference - - - - ClassicUO - KaRaShO' - 0.1.11.0 - 0.1.11.0 - ClassicUO - https://www.classicuo.eu/ - An open source implementation of the Ultima Online Classic Client. - - - - $(DefineConstants);DEV_BUILD - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - \ No newline at end of file diff --git a/FNA.Settings.props b/FNA.Settings.props deleted file mode 100644 index 3bfb82dfc..000000000 --- a/FNA.Settings.props +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index 4ebfb6cc4..000000000 --- a/LICENSE.md +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2022, andreakarasho -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -3. All advertising materials mentioning features or use of this software - must display the following acknowledgement: - This product includes software developed by andreakarasho - https://github.com/andreakarasho -4. Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/README.md b/README.md deleted file mode 100644 index ff5479d8c..000000000 --- a/README.md +++ /dev/null @@ -1,470 +0,0 @@ -

- -

- - chat on Discord -

------------------------------------------------------------------- - - -Release: [![Release](https://github.com/bittiez/TazUO/actions/workflows/build-test.yml/badge.svg?branch=main)](https://github.com/bittiez/TazUO/actions/workflows/build-test.yml) Dev: [![Dev](https://github.com/bittiez/TazUO/actions/workflows/build-test.yml/badge.svg?branch=dev)](https://github.com/bittiez/TazUO/actions/workflows/build-test.yml) - - -Join TazUO's discord for ideas/support/updates -> https://discord.gg/SqwtB5g95H - -Check out our [wiki](../../wiki) for details on all of the changes TazUO has made for players! - -This version of CUO adds [grid containers](../../wiki/TazUO.Grid-Containers) and many other features to the regular CUO client - - Searchable - - Resizable - - Scrollable - - Can lock items in specific place - - Quick preview for containers inside *if the client has already cached that bag* - - Item scaling! - -[Cool down bars](../../wiki/TazUO.Cooldown-bars) - -[Follow mode improvements](../../wiki/TazUO.Follow-mode) - -[Improved journal](../../wiki/TazUO.Journal) - -[Nameplate healthbars](../../wiki/TazUO.Nameplate-Healthbars) - -And others in our [wiki](../../wiki) - -![Cooldown](https://user-images.githubusercontent.com/3859393/227056224-ef1c6958-fff5-4698-a21a-c63c5814877c.gif) -![SlottedInv](https://user-images.githubusercontent.com/3859393/226514464-32919a68-ebad-4ec0-8bcf-8614a5055f7d.gif) -![Grid Previe](https://user-images.githubusercontent.com/3859393/222873187-c88ad321-8b19-4cfd-9617-7e23b2443b6a.gif) -![image](https://user-images.githubusercontent.com/3859393/222975241-319e5fa6-2c1e-441d-97e6-b04a5e1f6f3b.png) -![Journal](https://user-images.githubusercontent.com/3859393/222942915-e31d26aa-e9a7-41df-9c99-570bcc00d1fb.gif) -![image](https://user-images.githubusercontent.com/3859393/225168130-5ce83950-853d-43ce-9583-65ec4b0ae9d6.png) -![image](https://user-images.githubusercontent.com/3859393/225307385-c8e8014f-9b84-4fe4-a2cd-f33fbeee9563.png) -![image](https://user-images.githubusercontent.com/3859393/226114408-28c6556d-6ba8-43c7-bf1a-079342aaeacd.png) -![image](https://user-images.githubusercontent.com/3859393/226114417-e68b1653-f719-49b3-b799-0beb07e0a211.png) - - -# Original CUO Readme: ------------------------------------------------------------------- - -An open source implementation of the Ultima Online Classic Client. - -[![GitHub Actions Status](https://github.com/dust765/ClassicUO/workflows/Build-Test/badge.svg)](https://github.com/dust765/ClassicUO/actions) -[![GitHub Actions Status](https://github.com/dust765/ClassicUO/workflows/Deploy/badge.svg)](https://github.com/dust765/ClassicUO/actions) - -# Project dust765 -This project is to address a problem constructed within the toxicity of this community. This is to show the community, open source projects are not meant for cliques and high school drama but rather the expansion of something greater, innovation. -A penny for your thoughts, the adder that prays beneath the rose. - -![dust765_logo](https://user-images.githubusercontent.com/77043734/209156140-14558d04-eaf9-42f0-9939-ddec9cf6c1ac.png) - -# BRANCHES - -main is 1:1 from upstream (Karasho) - -dev_dust765 stable release - -dev_dust765_activedev stable work in progress releases - -dev_dust765_x_tazuo Dust765 and TazUO merged - -# contact and team info - -Discord: dust765#2787 - -Dust765: 7 Link, 6 Gaechti, 5 Syrupz - -Join me on TazUO discord: - - - -# feature showcase - -[Video Part 1 on YouTube](https://youtu.be/aqHiiOhx8Q8) - -[Video Part 2 on YouTube](https://youtu.be/P7YBrI3s6ZI) - -[Video Part 3 on YouTube](https://youtu.be/074Osj1Fcrg) - -# art / hue changes - -Stealth footsteps color - -Energy Bolt - art and color - -Gold - art and color - -Tree to stumps / tiles and color - -Blockers to stumps / tiles and color - -# visual helpers - -Highlight tiles at range - -Highlight tiles at range if spell is up - -Preview field spells, wall of stone and area of effect spells - -Glowing weapons - -Color own aura by HP - -Highlight lasttarget (more colors and options) - -# healthbar - -highlight lasttarget healthbar - -color border by state - -flashing outline (many options) - -# cursor - -Show spell on cursor (and runout countdown) - -Color game cursor when targeting (hostile / friendly) - -# overhead / underchar - -Distance - -# oldhealthlines - -old healthbars - -mana / stamina lines, for self and party, - -bigger version and transparency - -# misc - -Offscreen targeting - -Razor lasttarget sync (Razor lasttarget string - set this to the same lasttarget overhead string as set in Razor, so the ClassicUO lasttarget will be the same as in Razor.) - -Black Outline for statics - -Ignore stamina check - -Block Wall of Stone rubberband - -Block Energy Field rubberband - -# misc2 - -wireframe view - -hue impassable tiles - -transparent / invisible house and items by Z level from player and min Z from ground - -draw mobiles with surface overhead - -ignore list for circle of transparency (txt file created in your /Data/Client folder) - -show death location on worldmap - -# nameoverhead - -hp line in nameoverheads - -more filters for nameoverheads - -# UI gumps - -sticky last target healthbar (healthbar that always will be your last targets healthbar) - -bandage gump (bandage timer UI) - -# texturemanager - -texture manager (arrow or halo on mobiles) - -# UCC UI - -UI UCC LINES - Draws a line to HUMANS on your screen. - -Please specify the correct settings to make theese properly work! - -UI UCC AL - Is an autoloot feature / UI. Only works with GridLoot enabled. You can add items to the txt file created in your /Data/Client folder. Recommendation is to set high value items to the autolootlist.txt (items you potentialy would go gray for) and low value items to autolootlistlow. If you check SL (SafeLoot (available for both lists)), items will ONLY be auto looted if you have looting rights. Loot Above ID adds all items to the loot list higher than X, so you dont have to add hundreds of items to the list. - -UI UCC BUFFBAR - Provides a visible timer for next swing and disarm. You can enable lines individually enable them and also lock the UI to prevent moving it. There is a txt in /Data/Client to modify the timers for weapons. It does NOT change calculation with SSI or the like. - -UI UCC SELF - Is an Automation feature to bandaid yourself, use pouches, pots and enhanced apple (auto rearms a weapon after being disarmed). - -Checkboxes on the UI - -Rearm Pot - Auto rearm after pot. - -Armorer Guild - Auto rearm after being disarmed. - -Thiefes Guild - Disables any actions when hidden. - -Mages Guild - Disables any actions when a spellcursor is up. - -Tavern - Diable auto disarm. - -# features macros - -HighlightTileAtRange (toggle) - -ToggleTransparentHouses (toggle) - -ToggleInvisibleHouses (toggle) - -UCCLinesToggleLT (toggle) - -UCCLinesToggleHM (toggle) - -AutoMeditate (toggle) - -ToggleECBuffGump / ToggleECDebuffGump / ToggleECStateGump / ToggleModernCooldownBar (toggle) - -# simple macros - -ObjectInfo (-info command) - -OpenCorpses (open corpses in 2 tiles) - -OpenJournal2 (open second journal) - -SetTargetClientSide (set target client side only) - -LastTargetRC (LastTarget with RangeCheck) - -HideX (removes a game object) - -HealOnHPChange (keep pressed, casts greater heal as soon as HP change) - -HarmOnSwing (keep pressed, casts harm as soon as a swinganimation is issued from server) - -CureGH (cure or gheal) - -# advanced macros - -OpenCorpsesSafe (open corpses in 2 tiles safe to loot) - -GrabFriendlyBars, GrabEnemyBars, GrabPartyAllyBars (grab all bars with hotkey) - -AutoPot (one pot button) - -DefendSelfKey, DefendPartyKey (clever defend self or party) - -CustomInterrupt (interrupt current spellcast) - -EquipManager (fast equip) - -SetMimic_PlayerSerial (set master or custom serial for EquipManager) - -# commands - -type command in chat - --mimic (mimic casting of master) - --marker X Y (add world marker) - -auto add marker for T-Maps - --df (defender) - --automed (auto meditate) - --engage (auto pathfind and attack lasttarget) - --autorange (auto show range indicator when weapon is equipped) (edit autorange.txt in /Data/Client to adjust range for individual weapons) - -# outlands - -disabled features due to client enforcement (code updates NOT maintained) - -inferno bridge solver (color specific land tiles) - -overhead: Summon timer (also on healthbar) - -overhead: Peace timer (also on healthbar) - -underchar: Hamstrung timer (also on healthbar) - -buffbar: hamstrung - -# lobby - -connect multiple Dust765 clients to a lobby server to issue commands - -[Dust765's LobbyServer] (https://github.com/dust765/LobbyServer) - -features: send your lasttarget to be everyones, drop everyones spell on lasttarget, make everyone cast a spell, everyone attack lasttarget - -autostealthposition: command: -autohid ((needs connected lobby) broadcast your position when hidden, everyone will see your position - -commands: see options for a full list - -macros: see options for a full list - -# POC - -proof of concepts - -guardlines: show guardlines on land tiles (disabled due to performance) - -# gridloot - -The order in which items are shown in grid-loot will now depend on item type. - -Motivation: some items are likely to be always looted (e.g. gold, gems) and when looting is performed automatically (e.g. by Razor macros) it makes items to move in a grid making it harder to browse their properties. Hence, items like gold should be at the end of the grid. - -# multi journal - -Replaces journal with multiple nameable and much better configurable journals - -note: edit journals.xml in your profile folder, set hue to 0 if you wish to reset color to default - -(use macro OpenJournal2 for old journal) - -# status gump - -adds a version of the status gump with health / mana / stamina bar when expanded - -# modern cooldown bar - -adds a macro to open a BuffGump for each type (blue, green, red) similar to the EC client - -note: edit ecbuffs.txt / ecdebuffs.txt / ecstates.txt in /Data/Client to swap icons arround - -adds a modern version of the cooldown bar - -note: filter displayed buffs with modernbuffs.txt in /Data/Client, the EC txt are used to determine color - -# on casting gump - -shows a little gump on cursor when casting (can be hidden) - -main purpose being, to prevent rubberband on servers that dont send a freeze packet during casting - -(mod by Mark) - -# show all layers - -shows all equipment layers on mobiles (covered items should show) - -(mod by Mark) - -show additional equipment slots on paperdoll (for torso/arms/pants/shoes/cloak) - -# thief supreme - -override container open range (ie. backpacks dont close until paperdoll gets closed) - -hide X macro has been update to hide items inside containers - -# visual response manager (WIP) - -goal is to have a visual response on your character from various triggers. - -bandies, pots, clilocs,.... - -# Added files - -/src/Dust765 - -/src/Dust765/External - -/src/halo.png - -/src/arrow.png - -/src/Dust765/Macros - -/src/Dust765/Managers - -/src/Dust765/Autos - -/src/Dust765/Shared - -/src/Dust765/Lobby - -# changed constants - -WAIT_FOR_TARGET_DELAY 5000 -> 4000 - -MAX_CIRCLE_OF_TRANSPARENCY_RADIUS 200 -> 1000 - -DEATH_SCREEN_TIMER 1500 -> 750 - -MAX_JOURNAL_HISTORY_COUNT 100 -> 250 - -# Original readme -Individuals/hobbyists: support continued maintenance and development via the monthly Patreon: -
  [![Patreon](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/patreon_02.png)](http://www.patreon.com/classicuo) - -Individuals/hobbyists: support continued maintenance and development via PayPal: -
  [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=9ZWJBY6MS99D8) - - - - -# Introduction -ClassicUO is an open source implementation of the Ultima Online Classic Client. This client is intended to emulate all standard client versions and is primarily tested against Ultima Online free shards. - -The client is currently under heavy development but is functional. The code is based on the [FNA-XNA](https://fna-xna.github.io/) framework. C# is chosen because there is a large community of developers working on Ultima Online server emulators in C#, because FNA-XNA exists and seems reasonably suitable for creating this type of game. - -![screenshot_2020-07-06_12-29-02](https://user-images.githubusercontent.com/20810422/208747312-04f6782f-3dc8-4951-b0a0-73d2305bbfca.png) - - -ClassicUO is natively cross platform and supports: -* Browser [Chrome] -* Windows [DirectX 11, OpenGL, Vulkan] -* Linux [OpenGL, Vulkan] -* macOS [Metal, OpenGL, MoltenVK] - -# Download & Play! -| Platform | Link | -| --- | --- | -| Browser | [Play!](https://play.classicuo.org) | -| Windows x64 | [Download](https://www.classicuo.eu/launcher/win-x64/ClassicUOLauncher-win-x64-release.zip) | -| Linux x64 | [Download](https://www.classicuo.eu/launcher/linux-x64/ClassicUOLauncher-linux-x64-release.zip) | -| macOS | [Download](https://www.classicuo.eu/launcher/osx/ClassicUOLauncher-osx-x64-release.zip) | - -Or visit the [ClassicUO Website](https://www.classicuo.eu/) - -# How to build the project - -Clone repository with: -``` -git config --global url."https://".insteadOf git:// -git clone --recursive https://github.com/ClassicUO/ClassicUO.git -``` - -Build the project: -``` -dotnet build -c Release -``` - -# Contribute -Everyone is welcome to contribute! The GitHub issues and project tracker are kept up to date with tasks that need work. - -# Legal -The code itself has been written using the following projects as a reference: - -* [OrionUO](https://github.com/hotride/orionuo) -* [Razor](https://github.com/msturgill/razor) -* [UltimaXNA](https://github.com/ZaneDubya/UltimaXNA) -* [ServUO](https://github.com/servuo/servuo) - -Backend: -* [FNA](https://github.com/FNA-XNA/FNA) - -This work is released under the BSD 4 license. This project does not distribute any copyrighted game assets. In order to run this client you'll need to legally obtain a copy of the Ultima Online Classic Client. -Using a custom client to connect to official UO servers is strictly forbidden. We do not assume any responsibility of the usage of this client. - -Ultima Online(R) © 2022 Electronic Arts Inc. All Rights Reserved. diff --git a/external/FNA b/external/FNA deleted file mode 160000 index 591b3a37c..000000000 --- a/external/FNA +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 591b3a37cdeabf3ccbd6b66f6ce71e67a4407337 diff --git a/external/FontStashSharp b/external/FontStashSharp deleted file mode 160000 index f11f97b70..000000000 --- a/external/FontStashSharp +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f11f97b709e50960dd8ce1f727974744c4f8a0dd diff --git a/external/MP3Sharp b/external/MP3Sharp deleted file mode 160000 index db2d71d0a..000000000 --- a/external/MP3Sharp +++ /dev/null @@ -1 +0,0 @@ -Subproject commit db2d71d0aa2ed2fd1609d3ce06db0727ac63eecf diff --git a/external/cuoapi/cuoapi.dll b/external/cuoapi/cuoapi.dll deleted file mode 100644 index 77716eebf..000000000 Binary files a/external/cuoapi/cuoapi.dll and /dev/null differ diff --git a/external/lib64/libFAudio.so.0 b/external/lib64/libFAudio.so.0 deleted file mode 100644 index d63e03266..000000000 Binary files a/external/lib64/libFAudio.so.0 and /dev/null differ diff --git a/external/lib64/libFNA3D.so.0 b/external/lib64/libFNA3D.so.0 deleted file mode 100644 index 088e15d45..000000000 Binary files a/external/lib64/libFNA3D.so.0 and /dev/null differ diff --git a/external/lib64/libSDL2-2.0.so.0 b/external/lib64/libSDL2-2.0.so.0 deleted file mode 100644 index 5d2b303ed..000000000 Binary files a/external/lib64/libSDL2-2.0.so.0 and /dev/null differ diff --git a/external/lib64/libtheorafile.so b/external/lib64/libtheorafile.so deleted file mode 100644 index d75c3d51a..000000000 Binary files a/external/lib64/libtheorafile.so and /dev/null differ diff --git a/external/osx/libFAudio.0.dylib b/external/osx/libFAudio.0.dylib deleted file mode 100644 index 695a59f36..000000000 Binary files a/external/osx/libFAudio.0.dylib and /dev/null differ diff --git a/external/osx/libFNA3D.0.dylib b/external/osx/libFNA3D.0.dylib deleted file mode 100644 index b6d848399..000000000 Binary files a/external/osx/libFNA3D.0.dylib and /dev/null differ diff --git a/external/osx/libMoltenVK.dylib b/external/osx/libMoltenVK.dylib deleted file mode 100644 index 9cf069dbf..000000000 Binary files a/external/osx/libMoltenVK.dylib and /dev/null differ diff --git a/external/osx/libSDL2-2.0.0.dylib b/external/osx/libSDL2-2.0.0.dylib deleted file mode 100644 index 0c714ced6..000000000 Binary files a/external/osx/libSDL2-2.0.0.dylib and /dev/null differ diff --git a/external/osx/libtheorafile.dylib b/external/osx/libtheorafile.dylib deleted file mode 100644 index e0ef91a91..000000000 Binary files a/external/osx/libtheorafile.dylib and /dev/null differ diff --git a/external/osx/libvulkan.1.dylib b/external/osx/libvulkan.1.dylib deleted file mode 100644 index ff138d4d2..000000000 Binary files a/external/osx/libvulkan.1.dylib and /dev/null differ diff --git a/external/vulkan/icd.d/MoltenVK_icd.json b/external/vulkan/icd.d/MoltenVK_icd.json deleted file mode 100644 index 6e4d9ae91..000000000 --- a/external/vulkan/icd.d/MoltenVK_icd.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "file_format_version" : "1.0.0", - "ICD": { - "library_path": "../../../MacOS/osx/libMoltenVK.dylib", - "api_version" : "1.1.0" - } -} diff --git a/external/x64/FAudio.dll b/external/x64/FAudio.dll deleted file mode 100644 index 2d8fe4fe7..000000000 Binary files a/external/x64/FAudio.dll and /dev/null differ diff --git a/external/x64/FNA3D.dll b/external/x64/FNA3D.dll deleted file mode 100644 index b30095267..000000000 Binary files a/external/x64/FNA3D.dll and /dev/null differ diff --git a/external/x64/SDL2.dll b/external/x64/SDL2.dll deleted file mode 100644 index 4553fa951..000000000 Binary files a/external/x64/SDL2.dll and /dev/null differ diff --git a/external/x64/libtheorafile.dll b/external/x64/libtheorafile.dll deleted file mode 100644 index 93f791595..000000000 Binary files a/external/x64/libtheorafile.dll and /dev/null differ diff --git a/external/x64/vcruntime140.dll b/external/x64/vcruntime140.dll deleted file mode 100644 index 459166dc7..000000000 Binary files a/external/x64/vcruntime140.dll and /dev/null differ diff --git a/external/x64/zlib.dll b/external/x64/zlib.dll deleted file mode 100644 index c092b8a7c..000000000 Binary files a/external/x64/zlib.dll and /dev/null differ diff --git a/scripts/build.cmd b/scripts/build.cmd deleted file mode 100644 index 86a8ee4fa..000000000 --- a/scripts/build.cmd +++ /dev/null @@ -1,2 +0,0 @@ -dotnet build "../src/ClassicUO.csproj" -c Release -dotnet publish "../src/ClassicUO.csproj" -c Release /p:DefineConstants="STANDARD_BUILD" -p:IS_DEV_BUILD=true \ No newline at end of file diff --git a/scripts/build.sh b/scripts/build.sh deleted file mode 100755 index ae686895e..000000000 --- a/scripts/build.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/sh - -output="../bin/" -config="$1" - -if [ -z "$1" ] || [ "$1" = "release" ]; then - config="Release" -elif [ "$1" = "debug" ]; then - config="Debug" -fi - - -if [ "${config}" = "Debug" ]; then - echo "\n\n*** WARNING: USING DEBUG CONFIGURATION. IT WILL AFFECT PERFORMANCES OF THE GAME!! ***\n\n" -fi - - -echo "OUTPUT PATH: ${output}${config}" - - -msbuild "../src/ClassicUO.csproj" /p:Configuration=$config /p:OutputPath="${output}${config}" diff --git a/src/ClassicUO.Assets/AnimDataLoader.cs b/src/ClassicUO.Assets/AnimDataLoader.cs deleted file mode 100644 index 6033d8198..000000000 --- a/src/ClassicUO.Assets/AnimDataLoader.cs +++ /dev/null @@ -1,101 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using System; -using System.IO; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class AnimDataLoader : UOFileLoader - { - private static AnimDataLoader _instance; - private UOFileMul _file; - - private AnimDataLoader() - { - } - - public static AnimDataLoader Instance => _instance ?? (_instance = new AnimDataLoader()); - - public UOFile AnimDataFile => _file; - - public override Task Load() - { - return Task.Run - ( - () => - { - string path = UOFileManager.GetUOFilePath("animdata.mul"); - - if (File.Exists(path)) - { - _file = new UOFileMul(path); - } - } - ); - } - - public unsafe AnimDataFrame CalculateCurrentGraphic(ushort graphic) - { - IntPtr address = _file?.StartAddress ?? IntPtr.Zero; - - if (address != IntPtr.Zero) - { - IntPtr addr = address + (graphic * 68 + 4 * ((graphic >> 3) + 1)); - - if (addr.ToInt64() < address.ToInt64() + _file.Length) - { - ref AnimDataFrame a = ref Unsafe.AsRef((void*)addr); - - return a; - } - } - - return default; - } - } - - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public unsafe struct AnimDataFrame - { - public fixed sbyte FrameData[64]; - public byte Unknown; - public byte FrameCount; - public byte FrameInterval; - public byte FrameStart; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Assets/AnimationsLoader.cs b/src/ClassicUO.Assets/AnimationsLoader.cs deleted file mode 100644 index 2fd708c43..000000000 --- a/src/ClassicUO.Assets/AnimationsLoader.cs +++ /dev/null @@ -1,1838 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public unsafe class AnimationsLoader : UOFileLoader - { - public const int MAX_ACTIONS = 80; // gargoyle is like 78 - public const int MAX_DIRECTIONS = 5; - - private static AnimationsLoader _instance; - - [ThreadStatic] - private static FrameInfo[] _frames; - - [ThreadStatic] - private static byte[] _decompressedData; - - private readonly UOFileMul[] _files = new UOFileMul[5]; - private readonly UOFileUop[] _filesUop = new UOFileUop[4]; - - private readonly Dictionary> _equipConv = new Dictionary>(); - private readonly Dictionary _mobTypes = new Dictionary(); - private readonly Dictionary _bodyInfos = new Dictionary(); - private readonly Dictionary _corpseInfos = new Dictionary(); - private readonly Dictionary _bodyConvInfos = new Dictionary(); - private readonly Dictionary _uopInfos = new Dictionary(); - - private AnimationsLoader() { } - - public static AnimationsLoader Instance => - _instance ?? (_instance = new AnimationsLoader()); - - public IReadOnlyDictionary> EquipConversions => _equipConv; - - public List<(ushort, byte)>[] GroupReplaces { get; } = - new List<(ushort, byte)>[2] - { - new List<(ushort, byte)>(), - new List<(ushort, byte)>() - }; - - private unsafe void LoadInternal() - { - bool loaduop = false; - int[] un = { 0x40000, 0x10000, 0x20000, 0x20000, 0x20000 }; - - for (int i = 0; i < 5; i++) - { - string pathmul = UOFileManager.GetUOFilePath( - "anim" + (i == 0 ? string.Empty : (i + 1).ToString()) + ".mul" - ); - - string pathidx = UOFileManager.GetUOFilePath( - "anim" + (i == 0 ? string.Empty : (i + 1).ToString()) + ".idx" - ); - - if (File.Exists(pathmul) && File.Exists(pathidx)) - { - _files[i] = new UOFileMul(pathmul, pathidx, un[i], i == 0 ? 6 : -1); - } - - if (i > 0 && UOFileManager.IsUOPInstallation) - { - string pathuop = UOFileManager.GetUOFilePath($"AnimationFrame{i}.uop"); - - if (File.Exists(pathuop)) - { - _filesUop[i - 1] = new UOFileUop( - pathuop, - "build/animationlegacyframe/{0:D6}/{0:D2}.bin" - ); - - if (!loaduop) - { - loaduop = true; - } - } - } - } - - if (loaduop) - { - LoadUop(); - } - - if (UOFileManager.Version >= ClientVersion.CV_500A) - { - string path = UOFileManager.GetUOFilePath("mobtypes.txt"); - - if (File.Exists(path)) - { - var typeNames = new string[5] - { - "monster", - "sea_monster", - "animal", - "human", - "equipment" - }; - - using (var reader = new StreamReader(File.OpenRead(path))) - { - string line; - - while ((line = reader.ReadLine()) != null) - { - line = line.Trim(); - - if (line.Length == 0 || line[0] == '#' || !char.IsNumber(line[0])) - { - continue; - } - - string[] parts = line.Split( - new[] { '\t', ' ' }, - StringSplitOptions.RemoveEmptyEntries - ); - - if (parts.Length < 3) - { - continue; - } - - int id = int.Parse(parts[0]); - string testType = parts[1].ToLower(); - int commentIdx = parts[2].IndexOf('#'); - - if (commentIdx > 0) - { - parts[2] = parts[2].Substring(0, commentIdx - 1); - } - else if (commentIdx == 0) - { - continue; - } - - uint number = uint.Parse(parts[2], NumberStyles.HexNumber); - - for (int i = 0; i < 5; i++) - { - if ( - testType.Equals( - typeNames[i], - StringComparison.InvariantCultureIgnoreCase - ) - ) - { - _mobTypes[id] = new MobTypeInfo() - { - Type = (AnimationGroupsType)i, - Flags = (AnimationFlags )(0x80000000 | number) - }; - - break; - } - } - } - } - } - } - - string file = UOFileManager.GetUOFilePath("Anim1.def"); - - if (File.Exists(file)) - { - using (DefReader defReader = new DefReader(file)) - { - while (defReader.Next()) - { - ushort group = (ushort)defReader.ReadInt(); - - if (group == 0xFFFF) - { - continue; - } - - int replace = defReader.ReadGroupInt(); - - GroupReplaces[0].Add((group, (byte)replace)); - } - } - } - - file = UOFileManager.GetUOFilePath("Anim2.def"); - - if (File.Exists(file)) - { - using (DefReader defReader = new DefReader(file)) - { - while (defReader.Next()) - { - ushort group = (ushort)defReader.ReadInt(); - - if (group == 0xFFFF) - { - continue; - } - - int replace = defReader.ReadGroupInt(); - - GroupReplaces[1].Add((group, (byte)replace)); - } - } - } - - ProcessEquipConvDef(); - ProcessBodyDef(); - ProcessCorpseDef(); - } - - public bool ReplaceBody(ref ushort body, ref ushort hue) - { - if (_bodyInfos.TryGetValue(body, out var bodyInfo)) - { - body = bodyInfo.Graphic; - hue = bodyInfo.Hue; - - return true; - } - - return false; - } - - public bool ReplaceCorpse(ref ushort body, ref ushort hue) - { - if (_corpseInfos.TryGetValue(body, out var bodyInfo)) - { - body = bodyInfo.Graphic; - hue = bodyInfo.Hue; - - return true; - } - - return false; - } - - public bool ReplaceUopGroup(ushort body, ref byte group) - { - if (_uopInfos.TryGetValue(body, out var uopInfo)) - { - group = (byte)uopInfo.ReplacedAnimations[group]; - - return true; - } - - return false; - } - - public ReadOnlySpan GetIndices - ( - ClientVersion clientVersion, - ushort body, - ref ushort hue, - ref AnimationFlags flags, - out int fileIndex, - out AnimationGroupsType animType, - out sbyte mountHeight - ) - { - fileIndex = 0; - animType = AnimationGroupsType.Unknown; - mountHeight = 0; - - if (!_mobTypes.TryGetValue(body, out var mobInfo)) - { - mobInfo.Flags = AnimationFlags.None; - mobInfo.Type = AnimationGroupsType.Unknown; - } - - flags = mobInfo.Flags; - - if (mobInfo.Flags.HasFlag(AnimationFlags.UseUopAnimation)) - { - if (animType == AnimationGroupsType.Unknown) - animType = mobInfo.Type != AnimationGroupsType.Unknown ? mobInfo.Type : CalculateTypeByGraphic(body); - - var replaceFound = _uopInfos.TryGetValue(body, out var uopInfo); - mountHeight = uopInfo.HeightOffset; - var animIndices = Array.Empty(); - - for (int actioIdx = 0; actioIdx < MAX_ACTIONS; ++actioIdx) - { - var action = replaceFound ? uopInfo.ReplacedAnimations[actioIdx] : actioIdx; - var hashString = $"build/animationlegacyframe/{body:D6}/{action:D2}.bin"; - var hash = UOFileUop.CreateHash(hashString); - - for (int index = 0; index < _filesUop.Length; ++index) - { - if (_filesUop[index] != null && _filesUop[index].TryGetUOPData(hash, out var data)) - { - if (animIndices.Length == 0) - animIndices = new AnimIdxBlock[MAX_ACTIONS]; - - fileIndex = index; - - ref var animIndex = ref animIndices[actioIdx]; - animIndex.Position = (uint)data.Offset; - animIndex.Size = (uint)data.Length; - animIndex.Unknown = (uint)data.DecompressedLength; - - break; - } - } - } - - return animIndices; - } - - if (_bodyConvInfos.TryGetValue(body, out var bodyConvInfo)) - { - hue = bodyConvInfo.Hue; - body = bodyConvInfo.Graphic; - fileIndex = bodyConvInfo.FileIndex; - mountHeight = bodyConvInfo.MountHeight; - - if (clientVersion < ClientVersion.CV_500A) - animType = bodyConvInfo.AnimType; - } - - if (animType == AnimationGroupsType.Unknown) - animType = mobInfo.Type != AnimationGroupsType.Unknown ? mobInfo.Type : CalculateTypeByGraphic(body, fileIndex); - - var fileIdx = _files[fileIndex].IdxFile; - var offsetAddress = CalculateOffset(body, animType, flags, out var actionCount); - - var offset = fileIdx.StartAddress.ToInt64() + offsetAddress; - var end = fileIdx.StartAddress.ToInt64() + fileIdx.Length; - - if (offset >= end) - { - return ReadOnlySpan.Empty; - } - - if (offset + (actionCount * MAX_DIRECTIONS * sizeof(AnimIdxBlock)) > end) - { - return ReadOnlySpan.Empty; - } - - var animIdxSpan = new ReadOnlySpan( - (void*)offset, - actionCount * MAX_DIRECTIONS - ); - - return animIdxSpan; - } - - private long CalculateOffset( - ushort graphic, - AnimationGroupsType type, - AnimationFlags flags, - out int groupCount - ) - { - long result = 0; - groupCount = 0; - - var group = AnimationGroups.None; - - switch (type) - { - case AnimationGroupsType.Monster: - - if ((flags & AnimationFlags.CalculateOffsetByPeopleGroup) != 0) - { - group = AnimationGroups.People; - } - else if ((flags & AnimationFlags.CalculateOffsetByLowGroup) != 0) - { - group = AnimationGroups.Low; - } - else - { - group = AnimationGroups.High; - } - - break; - - case AnimationGroupsType.SeaMonster: - result = CalculateHighGroupOffset(graphic); - groupCount = (int)LowAnimationGroup.AnimationCount; - - break; - - case AnimationGroupsType.Animal: - - if ((flags & AnimationFlags.CalculateOffsetLowGroupExtended) != 0) - { - if ((flags & AnimationFlags.CalculateOffsetByPeopleGroup) != 0) - { - group = AnimationGroups.People; - } - else if ((flags & AnimationFlags.CalculateOffsetByLowGroup) != 0) - { - group = AnimationGroups.Low; - } - else - { - group = AnimationGroups.High; - } - } - else - { - group = AnimationGroups.Low; - } - - break; - - default: - group = AnimationGroups.People; - - break; - } - - switch (group) - { - case AnimationGroups.Low: - result = CalculateLowGroupOffset(graphic); - groupCount = (int)LowAnimationGroup.AnimationCount; - - break; - - case AnimationGroups.High: - result = CalculateHighGroupOffset(graphic); - groupCount = (int)HighAnimationGroup.AnimationCount; - - break; - - case AnimationGroups.People: - result = CalculatePeopleGroupOffset(graphic); - groupCount = (int)PeopleAnimationGroup.AnimationCount; - - break; - } - - return result; - } - - public override unsafe Task Load() - { - return Task.Run(LoadInternal); - } - - private void ProcessEquipConvDef() - { - if (UOFileManager.Version < ClientVersion.CV_300) - { - return; - } - - var file = UOFileManager.GetUOFilePath("Equipconv.def"); - - if (File.Exists(file)) - { - using (DefReader defReader = new DefReader(file, 5)) - { - while (defReader.Next()) - { - ushort body = (ushort)defReader.ReadInt(); - ushort graphic = (ushort)defReader.ReadInt(); - ushort newGraphic = (ushort)defReader.ReadInt(); - int gump = defReader.ReadInt(); - - if (gump > ushort.MaxValue) - { - continue; - } - - if (gump == 0) - { - gump = graphic; - } - else if (gump == 0xFFFF || gump == -1) - { - gump = newGraphic; - } - - ushort color = (ushort)defReader.ReadInt(); - - if (!_equipConv.TryGetValue(body, out var dict)) - { - _equipConv[body] = (dict = new Dictionary()); - } - - dict[graphic] = new EquipConvData(newGraphic, (ushort)gump, color); - } - } - } - } - - public void ProcessBodyConvDef(BodyConvFlags flags) - { - if (UOFileManager.Version < ClientVersion.CV_300) - { - return; - } - - var file = UOFileManager.GetUOFilePath("Bodyconv.def"); - - if (!File.Exists(file)) - return; - - using (var defReader = new DefReader(file)) - { - while (defReader.Next()) - { - ushort index = (ushort)defReader.ReadInt(); - - for (int i = 1; i < defReader.PartsCount; i++) - { - int body = defReader.ReadInt(); - if (body < 0) - { - continue; - } - - // Ensure the client is allowed to use these new graphics - if (i == 1) - { - if (!flags.HasFlag(BodyConvFlags.Anim1)) - { - continue; - } - } - else if (i == 2) - { - if (!flags.HasFlag(BodyConvFlags.Anim2)) - { - continue; - } - } - - // NOTE: for fileindex >= 3 the client automatically accepts body conversion. - // Probably it ignores the flags - /*else if (i == 3) - { - if (flags.HasFlag(BodyConvFlags.Anim3)) - { - continue; - } - } - else if (i == 4) - { - if (flags.HasFlag(BodyConvFlags.Anim4)) - { - continue; - } - } - */ - - sbyte mountedHeightOffset = 0; - if (i == 1) - { - if (index == 0x00C0 || index == 793) - { - mountedHeightOffset = -9; - } - } - else if (i == 2) - { - if (index == 0x0579) - { - mountedHeightOffset = 9; - } - } - else if (i == 4) - { - mountedHeightOffset = -9; - - if (index == 0x0115 || index == 0x00C0) - { - mountedHeightOffset = 0; - } - else if (index == 0x042D) - { - mountedHeightOffset = 3; - } - } - - if (i >= _files.Length || _files[i] == null) - { - continue; - } - - _bodyConvInfos[index] = new BodyConvInfo() - { - FileIndex = i, - Graphic = (ushort)body, - // TODO: fix for UOFileManager.Version < ClientVersion.CV_500A - AnimType = CalculateTypeByGraphic((ushort)body, i), - MountHeight = mountedHeightOffset - }; - } - } - } - } - - private void ProcessBodyDef() - { - if (UOFileManager.Version < ClientVersion.CV_300) - { - return; - } - - var file = UOFileManager.GetUOFilePath("Body.def"); - - if (!File.Exists(file)) - return; - - using (var defReader = new DefReader(file, 1)) - { - while (defReader.Next()) - { - int index = defReader.ReadInt(); - - if (_bodyInfos.TryGetValue(index, out var info) && info.Graphic != 0) - { - continue; - } - - int[] group = defReader.ReadGroup(); - - if (group == null) - { - continue; - } - - int color = defReader.ReadInt(); - - //Yes, this is actually how this is supposed to work. - var checkIndex = group.Length >= 3 ? group[2] : group[0]; - - _bodyInfos[index] = new BodyInfo() - { - Graphic = (ushort)checkIndex, - Hue = (ushort)color - }; - } - } - } - - private void ProcessCorpseDef() - { - if (UOFileManager.Version < ClientVersion.CV_300) - { - return; - } - - var file = UOFileManager.GetUOFilePath("Corpse.def"); - - if (!File.Exists(file)) - return; - - using (var defReader = new DefReader(file, 1)) - { - while (defReader.Next()) - { - int index = defReader.ReadInt(); - - if (_corpseInfos.TryGetValue(index, out var b) && b.Graphic != 0) - { - continue; - } - - int[] group = defReader.ReadGroup(); - - if (group == null) - { - continue; - } - - int color = defReader.ReadInt(); - int checkIndex = group.Length >= 3 ? group[2] : group[0]; - - _corpseInfos[index] = new BodyInfo() - { - Graphic = (ushort)checkIndex, - Hue = (ushort)color - }; - } - } - } - - private void LoadUop() - { - if (UOFileManager.Version <= ClientVersion.CV_60144) - { - return; - } - - string animationSequencePath = UOFileManager.GetUOFilePath("AnimationSequence.uop"); - - if (!File.Exists(animationSequencePath)) - { - Log.Warn("AnimationSequence.uop not found"); - - return; - } - - // ========================== - // credit: @tristran - // ========================== - // u32 animid - // 12 times: [ - // u32 unk0 //often zero - // ] - // //-------------- - // u32 replace - // replace times: [ - // u32 oldgroup - // u32 framecount - // u32 newgroup - // //if newgroup not is -1 then this animation group is replaced by that group - // u32 flags1 //unsure what these mean often 0x41100000 - // 16 times: [ //maybe something to do with mounts but... - // u8 unk1 //if newgroup ==-1 usually -128 else usually 0 - // ] - // 8 times: [ - // u32 unk2 //often 0 animation 826 has something different... - // ] - // u32 num1 //rarely present but human (400) has them for oldgroup 0,1,2,3,23,24,35 (stand/walk/run) - // num1 times: [ - // u32 w0 - // u32 w1 - // u32 w2 - // u32 w3 - // u32 w4 - // u32 w5 - // u16 s6 - // u32 w7 - // u16 s8 - // ] - // u32 num2 - // num2 times: [ - // u32 unk3 - // ] - // ] - // //----------- - // u32 xtra - // xtra times: [ - // u8 mob_mode //identifies the "mode" this defintion belongs to combat(0)/id(1)/ride (2) /fly(3)/fly combat?(4)/fly idle(5) /sit(6) - // s8 b2 //fallback mode? - // u32 def_action // default action (fallback if action not in following structure) - // u32 num1 - // num1 times: [ //transition to other mode? (see gargoyle (666)) - // u8 b6 //mode - // u32 n5 //anim/group - // ] - // u32 num2 //usually 3 (stand, walk, run) - // num2 times: [ - // u8 action - // u32 anim1h //one handed? - // u32 anim2h //two handed? - // ] - // u32 num3 // NewCharacterAnimation - // num3 times: [ - // s8 type //actual action fight etc - // s8 action //sub action - // u32 num4 //random select one of the list - // num4 times: [ - // u32 anim //group - // ] - // ] - // ] - - /* - based on the current "mode" the mobile is in (e.g. IsFlying check) select the right set of definitions from the xtra array - then consult the num2 based list for stand/walk/run - and the num3 based list for NewCharacterAnimation packets - / - / flags - 41100000 - 41400000 usually group 22,24 (walk run?) - 40C00000 often group 31 - 42860000 anim 692 Animated weapon - 41F80000 anim 692 - 41300000 anim 1246,1247 , group 0 (jack o lantern) - */ - - /* - based on the current "mode" the mobile is in (e.g. IsFlying check) select the right set of definitions from the xtra array - then consult the num2 based list for stand/walk/run - and the num3 based list for NewCharacterAnimation packets - / - / flags - 41100000 - 41400000 usually group 22,24 (walk run?) - 40C00000 often group 31 - 42860000 anim 692 Animated weapon - 41F80000 anim 692 - 41300000 anim 1246,1247 , group 0 (jack o lantern) - */ - - var animSeq = new UOFileUop( - animationSequencePath, - "build/animationsequence/{0:D8}.bin" - ); - //var animseqEntries = new UOFileIndex[animSeq.TotalEntriesCount]; - //animSeq.FillEntries(ref animseqEntries); - - Span spanAlloc = stackalloc byte[1024]; - - foreach (var pair in animSeq.Hashes) - { - var entry = pair.Value; - - if (entry.Offset == 0) - { - continue; - } - - animSeq.Seek(entry.Offset); - - byte[] buffer = null; - - Span span = - entry.DecompressedLength <= 1024 - ? spanAlloc - : ( - buffer = System.Buffers.ArrayPool.Shared.Rent( - entry.DecompressedLength - ) - ); - - try - { - fixed (byte* destPtr = span) - { - var result = ZLib.Decompress( - animSeq.PositionAddress, - entry.Length, - 0, - (IntPtr)destPtr, - entry.DecompressedLength - ); - - if (result != ZLib.ZLibError.Okay) - { - Log.Error($"error reading animationsequence {result}"); - return; - } - } - - var reader = new StackDataReader(span.Slice(0, entry.DecompressedLength)); - - uint animID = reader.ReadUInt32LE(); - reader.Skip(48); - int replaces = reader.ReadInt32LE(); - - var uopInfo = new UopInfo(); - var replacedAnimSpan = uopInfo.ReplacedAnimations; - for (var j = 0; j < replacedAnimSpan.Length; ++j) - replacedAnimSpan[j] = j; - - if (replaces != 48 && replaces != 68) - { - for (int k = 0; k < replaces; k++) - { - int oldGroup = reader.ReadInt32LE(); - uint frameCount = reader.ReadUInt32LE(); - int newGroup = reader.ReadInt32LE(); - - if (frameCount == 0) - { - replacedAnimSpan[oldGroup] = newGroup; - } - - reader.Skip(60); - } - - if ( - animID == 0x04E7 - || animID == 0x042D - || animID == 0x04E6 - || animID == 0x05F7 - || animID == 0x05A1 - ) - { - uopInfo.HeightOffset = 18; - } - else if ( - animID == 0x01B0 - || animID == 0x0579 - || animID == 0x05F6 - || animID == 0x05A0 - ) - { - uopInfo.HeightOffset = 9; - } - } - - _uopInfos[(int)animID] = uopInfo; - - reader.Release(); - } - finally - { - if (buffer != null) - { - System.Buffers.ArrayPool.Shared.Return(buffer); - } - } - } - - animSeq.Dispose(); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe uint CalculatePeopleGroupOffset(ushort graphic) - { - return (uint)(((graphic - 400) * 175 + 35000) * sizeof(AnimIdxBlock)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe uint CalculateHighGroupOffset(ushort graphic) - { - return (uint)(graphic * 110 * sizeof(AnimIdxBlock)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe uint CalculateLowGroupOffset(ushort graphic) - { - return (uint)(((graphic - 200) * 65 + 22000) * sizeof(AnimIdxBlock)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private AnimationGroupsType CalculateTypeByGraphic(ushort graphic, int fileIndex = 0) - { - if (fileIndex == 1) // anim2 - { - return graphic < 200 ? AnimationGroupsType.Monster : AnimationGroupsType.Animal; - } - - if (fileIndex == 2) // anim3 - { - return graphic < 300 - ? AnimationGroupsType.Animal - : graphic < 400 - ? AnimationGroupsType.Monster - : AnimationGroupsType.Human; - } - - return graphic < 200 - ? AnimationGroupsType.Monster - : graphic < 400 - ? AnimationGroupsType.Animal - : AnimationGroupsType.Human; - } - - public override void ClearResources() { } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void GetAnimDirection(ref byte dir, ref bool mirror) - { - switch (dir) - { - case 2: - case 4: - mirror = dir == 2; - dir = 1; - - break; - - case 1: - case 5: - mirror = dir == 1; - dir = 2; - - break; - - case 0: - case 6: - mirror = dir == 0; - dir = 3; - - break; - - case 3: - dir = 0; - - break; - - case 7: - dir = 4; - - break; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void GetSittingAnimDirection(ref byte dir, ref bool mirror, ref int x, ref int y) - { - switch (dir) - { - case 0: - mirror = true; - dir = 3; - - break; - - case 2: - mirror = true; - dir = 1; - - break; - - case 4: - mirror = false; - dir = 1; - - break; - - case 6: - mirror = false; - dir = 3; - - break; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void FixSittingDirection( - ref byte direction, - ref bool mirror, - ref int x, - ref int y, - ref SittingInfoData data - ) - { - switch (direction) - { - case 7: - case 0: - { - if (data.Direction1 == -1) - { - if (direction == 7) - { - direction = (byte)data.Direction4; - } - else - { - direction = (byte)data.Direction2; - } - } - else - { - direction = (byte)data.Direction1; - } - - break; - } - - case 1: - case 2: - { - if (data.Direction2 == -1) - { - if (direction == 1) - { - direction = (byte)data.Direction1; - } - else - { - direction = (byte)data.Direction3; - } - } - else - { - direction = (byte)data.Direction2; - } - - break; - } - - case 3: - case 4: - { - if (data.Direction3 == -1) - { - if (direction == 3) - { - direction = (byte)data.Direction2; - } - else - { - direction = (byte)data.Direction4; - } - } - else - { - direction = (byte)data.Direction3; - } - - break; - } - - case 5: - case 6: - { - if (data.Direction4 == -1) - { - if (direction == 5) - { - direction = (byte)data.Direction3; - } - else - { - direction = (byte)data.Direction1; - } - } - else - { - direction = (byte)data.Direction4; - } - - break; - } - } - - GetSittingAnimDirection(ref direction, ref mirror, ref x, ref y); - - const int SITTING_OFFSET_X = 8; - - int offsX = SITTING_OFFSET_X; - - if (mirror) - { - if (direction == 3) - { - y += 25 + data.MirrorOffsetY; - x += offsX - 4; - } - else - { - y += data.OffsetY + 9; - } - } - else - { - if (direction == 3) - { - y += 23 + data.MirrorOffsetY; - x -= 3; - } - else - { - y += 10 + data.OffsetY; - x -= offsX + 1; - } - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public AnimationGroups GetGroupIndex(ushort graphic, AnimationGroupsType animType) - { - switch (animType) - { - case AnimationGroupsType.Animal: - return AnimationGroups.Low; - - case AnimationGroupsType.Monster: - case AnimationGroupsType.SeaMonster: - return AnimationGroups.High; - - case AnimationGroupsType.Human: - case AnimationGroupsType.Equipment: - return AnimationGroups.People; - } - - return AnimationGroups.High; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public byte GetDeathAction( - ushort animID, - AnimationFlags animFlags, - AnimationGroupsType animType, - bool second, - bool isRunning = false - ) - { - //ConvertBodyIfNeeded(ref animID); - - if (animFlags.HasFlag(AnimationFlags.CalculateOffsetByLowGroup)) - { - animType = AnimationGroupsType.Animal; - } - - switch (animType) - { - case AnimationGroupsType.Animal: - - if ( - (animFlags & AnimationFlags.Use2IfHittedWhileRunning) != 0 - || (animFlags & AnimationFlags.CanFlying) != 0 - ) - { - return 2; - } - - if ((animFlags & AnimationFlags.UseUopAnimation) != 0) - { - return (byte)(second ? 3 : 2); - } - - return (byte)( - second ? LowAnimationGroup.Die2 : LowAnimationGroup.Die1 - ); - - case AnimationGroupsType.SeaMonster: - { - if (!isRunning) - { - return 8; - } - - goto case AnimationGroupsType.Monster; - } - - case AnimationGroupsType.Monster: - - if ((animFlags & AnimationFlags.UseUopAnimation) != 0) - { - return (byte)(second ? 3 : 2); - } - - return (byte)( - second ? HighAnimationGroup.Die2 : HighAnimationGroup.Die1 - ); - - case AnimationGroupsType.Human: - case AnimationGroupsType.Equipment: - return (byte)( - second ? PeopleAnimationGroup.Die2 : PeopleAnimationGroup.Die1 - ); - } - - return 0; - } - - public Span ReadUOPAnimationFrames( - ushort animID, - byte animGroup, - byte direction, - AnimationGroupsType type, - int fileIndex, - AnimationsLoader.AnimIdxBlock index - ) - { - if (fileIndex < 0 || fileIndex >= _filesUop.Length) - { - return Span.Empty; - } - - var file = _filesUop[fileIndex]; - - if (index.Position == 0 && index.Size == 0) - { - return Span.Empty; - } - - if (_frames == null) - { - _frames = new FrameInfo[22]; - } - - if ( - fileIndex == 0 - && index.Size == 0 - && index.Unknown == 0 - && index.Position == 0 - ) - { - Log.Warn("uop animData is null"); - - return Span.Empty; - } - - file.Seek(index.Position); - - if (_decompressedData == null || index.Unknown > _decompressedData.Length) - { - _decompressedData = new byte[index.Unknown]; - } - - fixed (byte* ptr = _decompressedData.AsSpan()) - { - var result = ZLib.Decompress( - file.PositionAddress, - (int)index.Size, - 0, - (IntPtr)ptr, - (int)index.Unknown - ); - - if (result != ZLib.ZLibError.Okay) - { - Log.Error($"error reading uop animation. AnimID: {animID} | Group: {animGroup} | Dir: {direction} | FileIndex: {fileIndex}"); - - return Span.Empty; - } - } - - var reader = new StackDataReader( - _decompressedData.AsSpan().Slice(0, (int)index.Unknown) - ); - reader.Skip(32); - - long end = (long)reader.StartAddress + reader.Length; - - int fc = reader.ReadInt32LE(); - uint dataStart = reader.ReadUInt32LE(); - reader.Seek(dataStart); - - byte frameCount = (byte)( - type < AnimationGroupsType.Equipment ? Math.Round(fc / (float) MAX_DIRECTIONS) : MAX_DIRECTIONS * 2 - ); - if (frameCount > _frames.Length) - { - _frames = new FrameInfo[frameCount]; - } - - var frames = _frames.AsSpan(0, frameCount); - - /* If the UOP files didn't omit frames, we could just do this: - * reader.Skip(sizeof(UOPAnimationHeader) * direction * frameCount); - * but we can't. So we have to walk through the frames to seek to where we need to go. - */ - UOPAnimationHeader* animHeaderInfo = (UOPAnimationHeader*)reader.PositionAddress; - - for (ushort currentDir = 0; currentDir <= direction; currentDir++) - { - for (ushort frameNum = 0; frameNum < frameCount; frameNum++) - { - long start = reader.Position; - animHeaderInfo = (UOPAnimationHeader*)reader.PositionAddress; - - if (animHeaderInfo->Group != animGroup) - { - /* Something bad has happened. Just return. */ - return Span.Empty; - } - - /* FrameID is 1's based and just keeps increasing, regardless of direction. - * So north will be 1-22, northeast will be 23-44, etc. And it's possible for frames - * to be missing. */ - ushort headerFrameNum = (ushort)((animHeaderInfo->FrameID - 1) % frameCount); - - ref var frame = ref frames[frameNum]; - - // we need to zero-out the frame or we will see ghost animations coming from other animation queries - frame.Num = frameNum; - frame.CenterX = 0; - frame.CenterY = 0; - frame.Width = 0; - frame.Height = 0; - - if (frameNum < headerFrameNum) - { - /* Missing frame. Keep walking forward. */ - continue; - } - - if (frameNum > headerFrameNum) - { - /* We've reached the next direction early */ - break; - } - - if (currentDir == direction) - { - /* We're on the direction we actually wanted to read */ - if (start + animHeaderInfo->DataOffset >= reader.Length) - { - /* File seems to be corrupt? Skip loading. */ - continue; - } - - reader.Skip((int)animHeaderInfo->DataOffset); - - var palette = new ReadOnlySpan(reader.PositionAddress.ToPointer(), 512 / sizeof(ushort)); - reader.Skip(512); - - ReadSpriteData(ref reader, palette, ref frame, true); - } - - reader.Seek(start + sizeof(UOPAnimationHeader)); - } - } - - reader.Release(); - - return frames; - } - - public Span ReadMULAnimationFrames(int fileIndex, AnimIdxBlock index) - { - if (fileIndex < 0 || fileIndex >= _files.Length) - { - return Span.Empty; - } - - if (index.Position == 0 && index.Size == 0) - { - return Span.Empty; - } - - if (index.Position == 0xFFFF_FFFF || index.Size == 0xFFFF_FFFF) - { - return Span.Empty; - } - - var file = _files[fileIndex]; - - var reader = new StackDataReader( - new ReadOnlySpan( - (byte*)file.StartAddress.ToPointer() + index.Position, - (int)index.Size - ) - ); - reader.Seek(0); - - var palette = new ReadOnlySpan(reader.PositionAddress.ToPointer(), 512 / sizeof(ushort)); - reader.Skip(512); - - long dataStart = reader.Position; - uint frameCount = reader.ReadUInt32LE(); - var frameOffset = new ReadOnlySpan((uint*)reader.PositionAddress, (int)frameCount); - - if (_frames == null || frameCount > _frames.Length) - { - _frames = new FrameInfo[frameCount]; - } - - var frames = _frames.AsSpan().Slice(0, (int)frameCount); - - for (int i = 0; i < frameCount; i++) - { - reader.Seek(dataStart + frameOffset[i]); - - frames[i].Num = i; - ReadSpriteData(ref reader, palette, ref frames[i], false); - } - - return frames; - } - - private void ReadSpriteData( - ref StackDataReader reader, - ReadOnlySpan palette, - ref FrameInfo frame, - bool alphaCheck - ) - { - frame.CenterX = reader.ReadInt16LE(); - frame.CenterY = reader.ReadInt16LE(); - frame.Width = reader.ReadInt16LE(); - frame.Height = reader.ReadInt16LE(); - - if (frame.Width <= 0 || frame.Height <= 0) - { - return; - } - - int bufferSize = frame.Width * frame.Height; - - if (frame.Pixels == null || frame.Pixels.Length < bufferSize) - { - frame.Pixels = new uint[bufferSize]; - } - else - { - frame.Pixels.AsSpan().Slice(0, bufferSize).Fill(0); - } - - Span data = frame.Pixels; - - uint header = reader.ReadUInt32LE(); - - while (header != 0x7FFF7FFF && reader.Position < reader.Length) - { - ushort runLength = (ushort)(header & 0x0FFF); - int x = (int)((header >> 22) & 0x03FF); - - if ((x & 0x0200) > 0) - { - x |= unchecked((int)0xFFFFFE00); - } - - int y = (int)((header >> 12) & 0x3FF); - - if ((y & 0x0200) > 0) - { - y |= unchecked((int)0xFFFFFE00); - } - - x += frame.CenterX; - y += frame.CenterY + frame.Height; - - int block = y * frame.Width + x; - - for (int k = 0; k < runLength; ++k, ++block) - { - ushort val = palette[reader.ReadUInt8()]; - - // FIXME: same of MUL ? Keep it as original for the moment - if (!alphaCheck || val != 0) - { - data[block] = HuesHelper.Color16To32(val) | 0xFF_00_00_00; - } - else - { - data[block] = 0; - } - } - - header = reader.ReadUInt32LE(); - } - } - - public struct FrameInfo - { - public int Num; - public short CenterX; - public short CenterY; - public short Width; - public short Height; - public uint[] Pixels; - } - - public struct SittingInfoData - { - public SittingInfoData( - ushort graphic, - sbyte d1, - sbyte d2, - sbyte d3, - sbyte d4, - sbyte offsetY, - sbyte mirrorOffsetY, - bool drawback - ) - { - Graphic = graphic; - Direction1 = d1; - Direction2 = d2; - Direction3 = d3; - Direction4 = d4; - OffsetY = offsetY; - MirrorOffsetY = mirrorOffsetY; - DrawBack = drawback; - } - - public readonly ushort Graphic; - public readonly sbyte Direction1, - Direction2, - Direction3, - Direction4; - public readonly sbyte OffsetY, - MirrorOffsetY; - public readonly bool DrawBack; - - public static SittingInfoData Empty = new SittingInfoData(); - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct AnimIdxBlock - { - public uint Position; - public uint Size; - public uint Unknown; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - ref struct UOPAnimationHeader - { - public ushort Group; - public ushort FrameID; - - public ushort Unk0; - public ushort Unk1; - public ushort Unk2; - public ushort Unk3; - - public uint DataOffset; - } - } - - public enum AnimationGroups - { - None = 0, - Low, - High, - People - } - - public enum AnimationGroupsType - { - Monster = 0, - SeaMonster, - Animal, - Human, - Equipment, - Unknown - } - - public enum HighAnimationGroup - { - Walk = 0, - Stand, - Die1, - Die2, - Attack1, - Attack2, - Attack3, - Misc1, - Misc2, - Misc3, - Stumble, - SlapGround, - Cast, - GetHit1, - Misc4, - GetHit2, - GetHit3, - Fidget1, - Fidget2, - Fly, - Land, - DieInFlight, - AnimationCount - } - - public enum PeopleAnimationGroup - { - WalkUnarmed = 0, - WalkArmed, - RunUnarmed, - RunArmed, - Stand, - Fidget1, - Fidget2, - StandOnehandedAttack, - StandTwohandedAttack, - AttackOnehanded, - AttackUnarmed1, - AttackUnarmed2, - AttackTwohandedDown, - AttackTwohandedWide, - AttackTwohandedJab, - WalkWarmode, - CastDirected, - CastArea, - AttackBow, - AttackCrossbow, - GetHit, - Die1, - Die2, - OnmountRideSlow, - OnmountRideFast, - OnmountStand, - OnmountAttack, - OnmountAttackBow, - OnmountAttackCrossbow, - OnmountSlapHorse, - Turn, - AttackUnarmedAndWalk, - EmoteBow, - EmoteSalute, - Fidget3, - AnimationCount - } - - public enum LowAnimationGroup - { - Walk = 0, - Run, - Stand, - Eat, - Unknown, - Attack1, - Attack2, - Attack3, - Die1, - Fidget1, - Fidget2, - LieDown, - Die2, - AnimationCount - } - - [Flags] - public enum AnimationFlags : uint - { - None = 0x00000, - Unknown1 = 0x00001, - Use2IfHittedWhileRunning = 0x00002, - IdleAt8Frame = 0x00004, - CanFlying = 0x00008, - Unknown10 = 0x00010, - CalculateOffsetLowGroupExtended = 0x00020, - CalculateOffsetByLowGroup = 0x00040, - Unknown80 = 0x00080, - Unknown100 = 0x00100, - Unknown200 = 0x00200, - CalculateOffsetByPeopleGroup = 0x00400, - Unknown800 = 0x00800, - Unknown1000 = 0x01000, - Unknown2000 = 0x02000, - Unknown4000 = 0x04000, - Unknown8000 = 0x08000, - UseUopAnimation = 0x10000, - Unknown20000 = 0x20000, - Unknown40000 = 0x40000, - Unknown80000 = 0x80000, - Found = 0x80000000 - } - - public struct EquipConvData : IEquatable - { - public EquipConvData(ushort graphic, ushort gump, ushort color) - { - Graphic = graphic; - Gump = gump; - Color = color; - } - - public ushort Graphic; - public ushort Gump; - public ushort Color; - - public override int GetHashCode() - { - return (Graphic, Gump, Color).GetHashCode(); - } - - public override bool Equals(object obj) - { - return obj is EquipConvData v && Equals(v); - } - - public bool Equals(EquipConvData other) - { - return (Graphic, Gump, Color) == (other.Graphic, other.Gump, other.Color); - } - } - - struct MobTypeInfo - { - public AnimationGroupsType Type; - public AnimationFlags Flags; - } - - struct BodyInfo - { - public ushort Graphic; - public ushort Hue; - } - - struct BodyConvInfo - { - public int FileIndex; - public AnimationGroupsType AnimType; - public ushort Graphic; - public ushort Hue; - public sbyte MountHeight; - } - - unsafe struct UopInfo - { - private fixed int _replacedAnim[AnimationsLoader.MAX_ACTIONS]; - - public Span ReplacedAnimations - { - get - { - - fixed (int* ptr = _replacedAnim) - { - return new Span(ptr, AnimationsLoader.MAX_ACTIONS); - } - } - } - - public sbyte HeightOffset; - } - - [Flags] - public enum BodyConvFlags - { - Anim1 = 0x1, - Anim2 = 0x2, - Anim3 = 0x4, - Anim4 = 0x8, - Anim5 = 0x10, - } -} diff --git a/src/ClassicUO.Assets/ArtLoader.cs b/src/ClassicUO.Assets/ArtLoader.cs deleted file mode 100644 index d1a498ab7..000000000 --- a/src/ClassicUO.Assets/ArtLoader.cs +++ /dev/null @@ -1,389 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using System; -using System.IO; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class ArtLoader : UOFileLoader - { - private static ArtLoader _instance; - private UOFile _file; - private readonly ushort _graphicMask; - - [ThreadStatic] - private static uint[] _data = null; - - public const int MAX_LAND_DATA_INDEX_COUNT = 0x4000; - public const int MAX_STATIC_DATA_INDEX_COUNT = 0x14000; - - private ArtLoader(int staticCount, int landCount) - { - _graphicMask = UOFileManager.IsUOPInstallation ? (ushort)0xFFFF : (ushort)0x3FFF; - } - - public static ArtLoader Instance => - _instance - ?? (_instance = new ArtLoader(MAX_STATIC_DATA_INDEX_COUNT, MAX_LAND_DATA_INDEX_COUNT)); - - public override Task Load() - { - return Task.Run(() => - { - string filePath = UOFileManager.GetUOFilePath("artLegacyMUL.uop"); - - if (UOFileManager.IsUOPInstallation && File.Exists(filePath)) - { - _file = new UOFileUop(filePath, "build/artlegacymul/{0:D8}.tga"); - Entries = new UOFileIndex[ - Math.Max(((UOFileUop)_file).TotalEntriesCount, MAX_STATIC_DATA_INDEX_COUNT) - ]; - } - else - { - filePath = UOFileManager.GetUOFilePath("art.mul"); - string idxPath = UOFileManager.GetUOFilePath("artidx.mul"); - - if (File.Exists(filePath) && File.Exists(idxPath)) - { - _file = new UOFileMul(filePath, idxPath, MAX_STATIC_DATA_INDEX_COUNT); - } - } - - _file.FillEntries(ref Entries); - }); - } - - // public Rectangle GetRealArtBounds(int index) => - // index + 0x4000 >= _spriteInfos.Length - // ? Rectangle.Empty - // : _spriteInfos[index + 0x4000].ArtBounds; - - private bool LoadData(Span data, int g, out short width, out short height) - { - ref var entry = ref GetValidRefEntry(g); - - if (entry.Length == 0) - { - width = 0; - height = 0; - - return false; - } - - _file.SetData(entry.Address, entry.FileSize); - _file.Seek(entry.Offset); - //var flags = _file.ReadUInt(); - - //if (flags > 0xFFFF || flags == 0) - if (g < 0x4000) - { - width = 44; - height = 44; - - if (data == null || data.Length < (width * height)) - { - return false; - } - - /* - * Since the data only contains the diamond shape, we may not actually read - * into every pixel in 'data'. We must zero the buffer here since it is - * re-used. But we only have to zero out the (44 * 44) worth. - */ - data.Slice(0, (width * height)).Fill(0); - - for (int i = 0; i < 22; ++i) - { - int start = 22 - (i + 1); - int pos = i * 44 + start; - int end = start + ((i + 1) << 1); - - for (int j = start; j < end; ++j) - { - data[pos++] = HuesHelper.Color16To32(_file.ReadUShort()) | 0xFF_00_00_00; - } - } - - for (int i = 0; i < 22; ++i) - { - int pos = (i + 22) * 44 + i; - int end = i + ((22 - i) << 1); - - for (int j = i; j < end; ++j) - { - data[pos++] = HuesHelper.Color16To32(_file.ReadUShort()) | 0xFF_00_00_00; - } - } - } - else - { - var flags = _file.ReadUInt(); - width = _file.ReadShort(); - height = _file.ReadShort(); - - if (width <= 0 || height <= 0 || data.Length < (width * height)) - { - return false; - } - - /* - * Since the data is run-length-encoded, we may not actually read - * into every pixel in 'data'. We must zero the buffer here since it is - * re-used. But we only have to zero out the (width * height) worth. - */ - data.Slice(0, (width * height)).Fill(0); - - ushort fixedGraphic = (ushort)(g - 0x4000); - - if (ReadData(data, width, height, _file)) - { - // keep the cursor graphic check to cleanup edges - //if ((fixedGraphic >= 0x2053 && fixedGraphic <= 0x2062) || (fixedGraphic >= 0x206A && fixedGraphic <= 0x2079)) - //{ - // for (int i = 0; i < width; i++) - // { - // data[i] = 0; - // data[(height - 1) * width + i] = 0; - // } - - // for (int i = 0; i < height; i++) - // { - // data[i * width] = 0; - // data[i * width + width - 1] = 0; - // } - //} - } - } - - return true; - } - - public Span GetRawImage(uint g, out short width, out short height) - { - if (!LoadData(_data, (int)g, out width, out height)) - { - if (_data != null && width * height < _data.Length) - { - return Span.Empty; - } - - _data = new uint[width * height]; - - if (!LoadData(_data, (int)g, out width, out height)) - { - return Span.Empty; - } - } - - return _data.AsSpan(0, width * height); - } - - private bool ReadHeader( - DataReader file, - ref UOFileIndex entry, - out short width, - out short height - ) - { - if (entry.Length == 0) - { - width = 0; - height = 0; - - return false; - } - - file.SetData(entry.Address, entry.FileSize); - file.Seek(entry.Offset); - file.Skip(4); - width = file.ReadShort(); - height = file.ReadShort(); - - return width > 0 && height > 0; - } - - private unsafe bool ReadData(Span pixels, int width, int height, DataReader file) - { - ushort* ptr = (ushort*)file.PositionAddress; - ushort* lineoffsets = ptr; - byte* datastart = (byte*)ptr + height * 2; - int x = 0; - int y = 0; - ptr = (ushort*)(datastart + lineoffsets[0] * 2); - - while (y < height) - { - ushort xoffs = *ptr++; - ushort run = *ptr++; - - if (xoffs + run >= 2048) - { - return false; - } - - if (xoffs + run != 0) - { - x += xoffs; - int pos = y * width + x; - - for (int j = 0; j < run; ++j, ++pos) - { - ushort val = *ptr++; - - if (val != 0) - { - pixels[pos] = HuesHelper.Color16To32(val) | 0xFF_00_00_00; - } - } - - x += run; - } - else - { - x = 0; - ++y; - ptr = (ushort*)(datastart + lineoffsets[y] * 2); - } - } - - return true; - } - - // private void FinalizeData( - // Span pixels, - // ref UOFileIndex entry, - // ushort graphic, - // int width, - // int height, - // out Rectangle bounds - // ) - // { - // int pos1 = 0; - // int minX = width, - // minY = height, - // maxX = 0, - // maxY = 0; - - // /* Temporarily broken. This isn't the right way to do it anyway since it can't be toggled on/off. - // if (StaticFilters.IsCave(graphic) && ProfileManager.CurrentProfile != null && ProfileManager.CurrentProfile.EnableCaveBorder) - // { - // AddBlackBorder(pixels, width, height); - // } - // */ - - // for (int y = 0; y < height; ++y) - // { - // for (int x = 0; x < width; ++x) - // { - // if (pixels[pos1++] != 0) - // { - // minX = Math.Min(minX, x); - // maxX = Math.Max(maxX, x); - // minY = Math.Min(minY, y); - // maxY = Math.Max(maxY, y); - // } - // } - // } - - // entry.Width = (short)((width >> 1) - 22); - // entry.Height = (short)(height - 44); - - // bounds.X = minX; - // bounds.Y = minY; - // bounds.Width = maxX - minX; - // bounds.Height = maxY - minY; - // } - - private void AddBlackBorder(Span pixels, int width, int height) - { - for (int yy = 0; yy < height; yy++) - { - int startY = yy != 0 ? -1 : 0; - int endY = yy + 1 < height ? 2 : 1; - - for (int xx = 0; xx < width; xx++) - { - ref uint pixel = ref pixels[yy * width + xx]; - - if (pixel == 0) - { - continue; - } - - int startX = xx != 0 ? -1 : 0; - int endX = xx + 1 < width ? 2 : 1; - - for (int i = startY; i < endY; i++) - { - int currentY = yy + i; - - for (int j = startX; j < endX; j++) - { - int currentX = xx + j; - - ref uint currentPixel = ref pixels[currentY * width + currentX]; - - if (currentPixel == 0u) - { - pixel = 0xFF_00_00_00; - } - } - } - } - } - } - - public ArtInfo GetArt(uint idx) - { - var pixels = GetRawImage(idx, out var width, out var height); - - return new ArtInfo() - { - Pixels = pixels, - Width = width, - Height = height - }; - } - } - - public ref struct ArtInfo - { - public Span Pixels; - public int Width; - public int Height; - } -} diff --git a/src/ClassicUO.Assets/ClassicUO.Assets.csproj b/src/ClassicUO.Assets/ClassicUO.Assets.csproj deleted file mode 100644 index 52717bc63..000000000 --- a/src/ClassicUO.Assets/ClassicUO.Assets.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - - Library - - - - - - - - - - - - - - - - - diff --git a/src/ClassicUO.Assets/ClilocLoader.cs b/src/ClassicUO.Assets/ClilocLoader.cs deleted file mode 100644 index c9a45be5c..000000000 --- a/src/ClassicUO.Assets/ClilocLoader.cs +++ /dev/null @@ -1,381 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class ClilocLoader : UOFileLoader - { - private static ClilocLoader _instance; - private string _cliloc; - private readonly Dictionary _entries = new Dictionary(); - - private ClilocLoader() - { - } - - public static ClilocLoader Instance => _instance ?? (_instance = new ClilocLoader()); - - public Task Load(string lang) - { - if (string.IsNullOrEmpty(lang)) - { - lang = "enu"; - } - - _cliloc = $"Cliloc.{lang}"; - Log.Trace($"searching for: '{_cliloc}'"); - - if (!File.Exists(UOFileManager.GetUOFilePath(_cliloc))) - { - Log.Warn($"'{_cliloc}' not found. Rolled back to Cliloc.enu"); - - _cliloc = "Cliloc.enu"; - } - - return Load(); - } - - public override Task Load() - { - return Task.Run - ( - () => - { - if (string.IsNullOrEmpty(_cliloc)) - { - _cliloc = "Cliloc.enu"; - } - - string path = UOFileManager.GetUOFilePath(_cliloc); - - if (!File.Exists(path)) - { - Log.Error($"cliloc not found: '{path}'"); - return; - } - - if (string.Compare(_cliloc, "cliloc.enu", StringComparison.InvariantCultureIgnoreCase) != 0) - { - string enupath = UOFileManager.GetUOFilePath("Cliloc.enu"); - - using (BinaryReader reader = new BinaryReader(new FileStream(enupath, FileMode.Open, FileAccess.Read))) - { - reader.ReadInt32(); - reader.ReadInt16(); - - byte[] buffer = System.Buffers.ArrayPool.Shared.Rent(1024); - - try - { - while (reader.BaseStream.Length != reader.BaseStream.Position) - { - int number = reader.ReadInt32(); - byte flag = reader.ReadByte(); - int length = reader.ReadInt16(); - - if (length > buffer.Length) - { - System.Buffers.ArrayPool.Shared.Return(buffer); - - buffer = System.Buffers.ArrayPool.Shared.Rent((length + 1023) & ~1023); - } - - reader.Read(buffer, 0, length); - string text = string.Intern(Encoding.UTF8.GetString(buffer, 0, length)); - - _entries[number] = text; - } - } - finally - { - System.Buffers.ArrayPool.Shared.Return(buffer); - } - } - } - - using (BinaryReader reader = new BinaryReader(new FileStream(path, FileMode.Open, FileAccess.Read))) - { - reader.ReadInt32(); - reader.ReadInt16(); - byte[] buffer = System.Buffers.ArrayPool.Shared.Rent(1024); - - try - { - while (reader.BaseStream.Length != reader.BaseStream.Position) - { - int number = reader.ReadInt32(); - byte flag = reader.ReadByte(); - int length = reader.ReadInt16(); - - if (length > buffer.Length) - { - System.Buffers.ArrayPool.Shared.Return(buffer); - - buffer = System.Buffers.ArrayPool.Shared.Rent((length + 1023) & ~1023); - } - - reader.Read(buffer, 0, length); - string text = string.Intern(Encoding.UTF8.GetString(buffer, 0, length)); - - _entries[number] = text; - } - } - finally - { - System.Buffers.ArrayPool.Shared.Return(buffer); - } - } - } - ); - } - - public override void ClearResources() - { - _entries.Clear(); - } - - public string GetString(int number) - { - _entries.TryGetValue(number, out string text); - - return text; - } - - public string GetString(int number, string replace) - { - string s = GetString(number); - - if (string.IsNullOrEmpty(s)) - { - s = replace; - } - - return s; - } - - public string GetString(int number, bool camelcase, string replace = "") - { - string s = GetString(number); - - if (string.IsNullOrEmpty(s) && !string.IsNullOrEmpty(replace)) - { - s = replace; - } - - if (camelcase && !string.IsNullOrEmpty(s)) - { - s = StringHelper.CapitalizeAllWords(s); - } - - return s; - } - - public unsafe string Translate(int clilocNum, string arg = "", bool capitalize = false) - { - string baseCliloc = GetString(clilocNum); - - if (baseCliloc == null) - { - return null; - } - - if (arg == null) - { - arg = ""; - } - - var roChars = arg.AsSpan(); - - - // get count of valid args - int i = 0; - int totalArgs = 0; - int trueStart = -1; - - for (; i < roChars.Length; ++i) - { - if (roChars[i] != '\t') - { - if (trueStart == -1) - { - trueStart = i; - } - } - else if (trueStart >= 0) - { - ++totalArgs; - } - } - - if (trueStart == -1) - { - trueStart = 0; - } - - // store index locations - Span<(int, int)> locations = stackalloc (int, int)[++totalArgs]; - i = trueStart; - for (int j = 0; i < roChars.Length; ++i) - { - if (roChars[i] == '\t') - { - locations[j].Item1 = trueStart; - locations[j].Item2 = i; - - trueStart = i + 1; - - ++j; - } - } - - bool has_arguments = totalArgs - 1 > 0; - - locations[totalArgs - 1].Item1 = trueStart; - locations[totalArgs - 1].Item2 = i; - - ValueStringBuilder sb = new ValueStringBuilder(baseCliloc.AsSpan()); - { - int index, pos = 0; - - while (pos < sb.Length) - { - int poss = pos; - pos = sb.RawChars.Slice(pos, sb.Length - pos).IndexOf('~'); - - if (pos == -1) - { - break; - } - - pos += poss; - - int pos2 = sb.RawChars.Slice(pos + 1, sb.Length - (pos + 1)).IndexOf('~'); - - if (pos2 == -1) //non valid arg - { - break; - } - - pos2 += pos + 1; - - index = sb.RawChars.Slice(pos + 1, pos2 - (pos + 1)).IndexOf('_'); - - if (index == -1) - { - //there is no underscore inside the bounds, so we use all the part to get the number of argument - index = pos2; - } - else - { - index += pos + 1; - } - - int start = pos + 1; - int max = index - start; - int count = 0; - - for (; count < max; count++) - { - if (!char.IsNumber(sb.RawChars[start + count])) - { - break; - } - } - - if (!int.TryParse(sb.RawChars.Slice(start, count).ToString(), out index)) - { - return $"MegaCliloc: error for {clilocNum}"; - } - - --index; - - var a = index < 0 || index >= totalArgs ? string.Empty.AsSpan() : arg.AsSpan().Slice(locations[index].Item1, locations[index].Item2 - locations[index].Item1); - - if (a.Length > 1) - { - if (a[0] == '#') - { - if (int.TryParse(a.Slice(1).ToString(), out int id1)) - { - var ss = GetString(id1); - - if (string.IsNullOrEmpty(ss)) - { - a = string.Empty.AsSpan(); - } - else - { - a = ss.AsSpan(); - } - } - } - else if (has_arguments && int.TryParse(a.ToString(), out int clil)) - { - if (_entries.TryGetValue(clil, out string value) && !string.IsNullOrEmpty(value)) - { - a = value.AsSpan(); - } - } - } - - sb.Remove(pos, pos2 - pos + 1); - sb.Insert(pos, a); - - if (index >= 0 && index < totalArgs) - { - pos += a.Length /*locations[index].Y - locations[index].X*/; - } - } - - baseCliloc = sb.ToString(); - - sb.Dispose(); - - if (capitalize) - { - baseCliloc = StringHelper.CapitalizeAllWords(baseCliloc); - } - - return baseCliloc; - } - } - } -} diff --git a/src/ClassicUO.Assets/FontsLoader.cs b/src/ClassicUO.Assets/FontsLoader.cs deleted file mode 100644 index 42be47560..000000000 --- a/src/ClassicUO.Assets/FontsLoader.cs +++ /dev/null @@ -1,3829 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using ClassicUO.Utility.Collections; -using ClassicUO.Utility.Logging; -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class FontsLoader : UOFileLoader - { - private const int UOFONT_SOLID = 0x0001; - private const int UOFONT_ITALIC = 0x0002; - private const int UOFONT_INDENTION = 0x0004; - private const int UOFONT_BLACK_BORDER = 0x0008; - private const int UOFONT_UNDERLINE = 0x0010; - private const int UOFONT_FIXED = 0x0020; - private const int UOFONT_CROPPED = 0x0040; - private const int UOFONT_BQ = 0x0080; - private const int UOFONT_EXTRAHEIGHT = 0x0100; - private const int UOFONT_CROPTEXTURE = 0x0200; - private const int UOFONT_FIXEDHEIGHT = 0x0400; - private const int UNICODE_SPACE_WIDTH = 8; - private const int MAX_HTML_TEXT_HEIGHT = 18; - private const byte NOPRINT_CHARS = 32; - private const float ITALIC_FONT_KOEFFICIENT = 3.3f; - - private static FontsLoader _instance; - - public struct Margin - { - public int X, Y, Width, Height; - - public Margin() - { - this = default; - } - - public Margin(int x, int y, int width, int height) - { - X = x; Y = y; Width = width; Height = height; - } - - - public readonly int Right => X + Width; - public readonly int Bottom => Y + Height; - - public readonly bool Contains(int x, int y) - { - return (x >= X && x < Right && y >= Y && y < Bottom); - } - - public static readonly Margin Empty = new Margin(); - } - - struct HtmlStatus - { - public uint BackgroundColor; - public uint VisitedWebLinkColor; - public uint WebLinkColor; - public uint Color; - public Margin Margins; - - public bool IsHtmlBackgroundColored; - } - - private HtmlStatus _htmlStatus; - - private FontCharacterData[,] _fontData; - private readonly IntPtr[] _unicodeFontAddress = new IntPtr[20]; - private readonly long[] _unicodeFontSize = new long[20]; - private readonly Dictionary _webLinks = new Dictionary(); - private readonly int[] _offsetCharTable = { 2, 0, 2, 2, 0, 0, 2, 2, 0, 0 }; - private readonly int[] _offsetSymbolTable = { 1, 0, 1, 1, -1, 0, 1, 1, 0, 0 }; - - private FontsLoader() { } - - public static FontsLoader Instance => _instance ?? (_instance = new FontsLoader()); - - public int FontCount { get; private set; } - - public bool UnusePartialHue { get; set; } = false; - - public bool RecalculateWidthByInfo { get; set; } = false; - - public bool IsUsingHTML { get; set; } - - public override unsafe Task Load() - { - return Task.Run(() => - { - UOFileMul fonts = new UOFileMul(UOFileManager.GetUOFilePath("fonts.mul")); - UOFileMul[] uniFonts = new UOFileMul[20]; - - for (int i = 0; i < 20; i++) - { - string path = UOFileManager.GetUOFilePath( - "unifont" + (i == 0 ? "" : i.ToString()) + ".mul" - ); - - if (File.Exists(path)) - { - uniFonts[i] = new UOFileMul(path); - - _unicodeFontAddress[i] = uniFonts[i].StartAddress; - - _unicodeFontSize[i] = uniFonts[i].Length; - } - } - - int fontHeaderSize = sizeof(FontHeader); - FontCount = 0; - - while (fonts.Position < fonts.Length) - { - bool exit = false; - fonts.Skip(1); - - for (int i = 0; i < 224; i++) - { - FontHeader* fh = (FontHeader*)fonts.PositionAddress; - - if (fonts.Position + fontHeaderSize >= fonts.Length) - { - continue; - } - - fonts.Skip(fontHeaderSize); - int bcount = fh->Width * fh->Height * 2; - - if (fonts.Position + bcount > fonts.Length) - { - exit = true; - - break; - } - - fonts.Skip(bcount); - } - - if (exit) - { - break; - } - - FontCount++; - } - - if (FontCount < 1) - { - FontCount = 0; - - return; - } - - _fontData = new FontCharacterData[FontCount, 224]; - fonts.Seek(0); - - for (int i = 0; i < FontCount; i++) - { - byte header = fonts.ReadByte(); - - for (int j = 0; j < 224; j++) - { - if (fonts.Position + 3 >= fonts.Length) - { - continue; - } - - byte w = fonts.ReadByte(); - byte h = fonts.ReadByte(); - fonts.Skip(1); - _fontData[i, j] = new FontCharacterData( - w, - h, - (ushort*)fonts.PositionAddress - ); - fonts.Skip(w * h * sizeof(ushort)); - } - } - - if (_unicodeFontAddress[1] == IntPtr.Zero) - { - _unicodeFontAddress[1] = _unicodeFontAddress[0]; - _unicodeFontSize[1] = _unicodeFontSize[0]; - } - }); - } - - public bool UnicodeFontExists(byte font) - { - return font < 20 && _unicodeFontAddress[font] != IntPtr.Zero; - } - - /// Get the index in ASCII fonts of a character. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private int GetASCIIIndex(char c) - { - byte ch = (byte)c; // ASCII fonts cover only 256 characters - - if (ch < NOPRINT_CHARS) - { - return 0; - } - - return ch - NOPRINT_CHARS; - } - - public int GetWidthASCII(byte font, string str) - { - if (font >= FontCount || string.IsNullOrEmpty(str)) - { - return 0; - } - - int textLength = 0; - - foreach (char c in str) - { - textLength += _fontData[font, GetASCIIIndex(c)].Width; - } - - return textLength; - } - - public int GetCharWidthASCII(byte font, char c) - { - if (font >= FontCount || c == 0 || c == '\r') - { - return 0; - } - - if (c < NOPRINT_CHARS) - { - return _fontData[font, 0].Width; - } - - int index = c - NOPRINT_CHARS; - - if (index < _fontData.GetLength(1)) - { - return _fontData[font, index].Width; - } - - return 0; - } - - public int GetWidthExASCII( - byte font, - string text, - int maxwidth, - TEXT_ALIGN_TYPE align, - ushort flags - ) - { - if (font > FontCount || string.IsNullOrEmpty(text)) - { - return 0; - } - - MultilinesFontInfo info = GetInfoASCII(font, text, text.Length, align, flags, maxwidth); - - int textWidth = 0; - - while (info != null) - { - if (info.Width > textWidth) - { - textWidth = info.Width; - } - - MultilinesFontInfo ptr = info; - info = info.Next; - ptr.Data.Clear(); - ptr = null; - } - - return textWidth; - } - - private int GetHeightASCII(MultilinesFontInfo info) - { - int textHeight = 0; - - while (info != null) - { - textHeight += info.MaxHeight; - info = info.Next; - } - - return textHeight; - } - - public int GetHeightASCII( - byte font, - string str, - int width, - TEXT_ALIGN_TYPE align, - ushort flags - ) - { - if (width == 0) - { - width = GetWidthASCII(font, str); - } - - MultilinesFontInfo info = GetInfoASCII(font, str, str.Length, align, flags, width); - - int textHeight = 0; - - while (info != null) - { - if (IsUsingHTML) - { - textHeight += MAX_HTML_TEXT_HEIGHT; - } - else - { - textHeight += info.MaxHeight; - } - - MultilinesFontInfo ptr = info; - info = info.Next; - ptr.Data.Clear(); - ptr = null; - } - - return textHeight; - } - - public struct FontInfo - { - public uint[] Data; - public int Width; - public int Height; - - public int LineCount; - public FastList Links; - - public static FontInfo Empty = new FontInfo() { Data = null }; - } - - public FontInfo GenerateASCII( - byte font, - string str, - ushort color, - int width, - TEXT_ALIGN_TYPE align, - ushort flags, - bool saveHitmap, - int height - ) - { - if (string.IsNullOrEmpty(str)) - { - return FontInfo.Empty; - } - - if ( - (flags & UOFONT_FIXED) != 0 - || (flags & UOFONT_CROPPED) != 0 - || (flags & UOFONT_CROPTEXTURE) != 0 - ) - { - if (width == 0 || string.IsNullOrEmpty(str)) - { - return FontInfo.Empty; - } - - int realWidth = GetWidthASCII(font, str); - - if (realWidth > width) - { - string newstr = GetTextByWidthASCII( - font, - str, - width, - (flags & UOFONT_CROPPED) != 0, - align, - flags - ); - - if ((flags & UOFONT_CROPTEXTURE) != 0 && !string.IsNullOrEmpty(newstr)) - { - int totalheight = 0; - - while (totalheight < height) - { - totalheight += GetHeightASCII(font, newstr, width, align, flags); - - if (str.Length > newstr.Length) - { - newstr += GetTextByWidthASCII( - font, - str.Substring(newstr.Length), - width, - (flags & UOFONT_CROPPED) != 0, - align, - flags - ); - } - else - { - break; - } - } - } - - return GeneratePixelsASCII( - font, - newstr, - color, - width, - align, - flags, - saveHitmap - ); - } - } - - return GeneratePixelsASCII(font, str, color, width, align, flags, saveHitmap); - } - - public string GetTextByWidthASCII( - byte font, - string str, - int width, - bool isCropped, - TEXT_ALIGN_TYPE align, - ushort flags - ) - { - if (font >= FontCount || string.IsNullOrEmpty(str)) - { - return string.Empty; - } - - int strLen = str.Length; - - Span span = stackalloc char[strLen]; - ValueStringBuilder sb = new ValueStringBuilder(span); - - if (IsUsingHTML) - { - unsafe - { - HTMLChar* chars = stackalloc HTMLChar[strLen]; - - GetHTMLData(chars, font, str.AsSpan(), ref strLen, align, flags); - } - - int size = str.Length - strLen; - - if (size > 0) - { - sb.Append(str.Substring(0, size)); - str = str.Substring(str.Length - strLen, strLen); - - if (GetWidthASCII(font, str) < width) - { - isCropped = false; - } - } - } - - if (isCropped) - { - width -= _fontData[font, '.' - NOPRINT_CHARS].Width * 3; - } - - int textLength = 0; - - foreach (char c in str) - { - textLength += _fontData[font, GetASCIIIndex(c)].Width; - - if (textLength > width) - { - break; - } - - sb.Append(c); - } - - if (isCropped) - { - sb.Append("..."); - } - - string ss = sb.ToString(); - - sb.Dispose(); - - return ss; - } - - private unsafe FontInfo GeneratePixelsASCII( - byte font, - string str, - ushort color, - int width, - TEXT_ALIGN_TYPE align, - ushort flags, - bool saveHitmap - ) - { - if (font >= FontCount) - { - return FontInfo.Empty; - } - - int len = str.Length; - - if (len == 0) - { - return FontInfo.Empty; - } - - if (width <= 0) - { - width = GetWidthASCII(font, str); - } - - if (width <= 0) - { - return FontInfo.Empty; - } - - MultilinesFontInfo info = GetInfoASCII(font, str, len, align, flags, width); - - if (info == null) - { - return FontInfo.Empty; - } - - width += 4; - int height = GetHeightASCII(info); - - if (height <= 0) - { - MultilinesFontInfo ptr1 = info; - - while (ptr1 != null) - { - info = ptr1; - ptr1 = ptr1.Next; - info.Data.Clear(); - info = null; - } - - return FontInfo.Empty; - } - - int blocksize = height * width; - uint[] pData = new uint[blocksize]; // System.Buffers.ArrayPool.Shared.Rent(blocksize); - - try - { - int lineOffsY = 0; - MultilinesFontInfo ptr = info; - bool isPartial = font != 5 && font != 8 && !UnusePartialHue; - int font6OffsetY = font == 6 ? 7 : 0; - int linesCount = 0; // this value should be added to TextTexture.LineCount += linesCount - - while (ptr != null) - { - info = ptr; - linesCount++; - int w = 0; - - switch (ptr.Align) - { - case TEXT_ALIGN_TYPE.TS_CENTER: - { - w = (width - ptr.Width) >> 1; - - if (w < 0) - { - w = 0; - } - - break; - } - - case TEXT_ALIGN_TYPE.TS_RIGHT: - { - w = width - 10 - ptr.Width; - - if (w < 0) - { - w = width; - } - - break; - } - - case TEXT_ALIGN_TYPE.TS_LEFT when (flags & UOFONT_INDENTION) != 0: - w = ptr.IndentionOffset; - - break; - } - - var count = ptr.Data.Length; - - for (int i = 0; i < count; i++) - { - byte index = (byte)ptr.Data[i].Item; - - int offsY = GetFontOffsetY(font, index); - - ref FontCharacterData fcd = ref _fontData[ - font, - GetASCIIIndex(ptr.Data[i].Item) - ]; - - int dw = fcd.Width; - int dh = fcd.Height; - ushort charColor = color; - - for (int y = 0; y < dh; y++) - { - int testY = y + lineOffsY + offsY; - - if (testY >= height) - { - break; - } - - for (int x = 0; x < dw; x++) - { - if (x + w >= width) - { - break; - } - - ushort pic = fcd.Data[y * dw + x]; - - if (pic != 0) - { - uint pcl; - - if (isPartial) - { - pcl = HuesLoader.Instance.GetPartialHueColor( - pic, - charColor - ); - } - else - { - pcl = HuesLoader.Instance.ApplyHueRgba8888(pic, charColor); - } - - int block = testY * width + x + w; - - if (block >= 0) - { - pData[block] = pcl | 0xFF_00_00_00; - } - } - } - } - - w += dw; - } - - lineOffsY += ptr.MaxHeight - font6OffsetY; - ptr = ptr.Next; - info.Data.Clear(); - info = null; - } - - FontInfo fi = new FontInfo(); - fi.LineCount = linesCount; - fi.Data = pData; - fi.Width = width; - fi.Height = height; - fi.Links = null; - - return fi; - } - finally - { - //System.Buffers.ArrayPool.Shared.Return(pData, true); - } - } - - private int GetFontOffsetY(byte font, byte index) - { - if (index == 0xB8) - { - return 1; - } - - if ( - !(index >= 0x41 && index <= 0x5A) - && !(index >= 0xC0 && index <= 0xDF) - && index != 0xA8 - ) - { - if (font < 10) - { - if (index >= 0x61 && index <= 0x7A) - { - return _offsetCharTable[font]; - } - - return _offsetSymbolTable[font]; - } - - return 2; - } - - return 0; - } - - public MultilinesFontInfo GetInfoASCII( - byte font, - string str, - int len, - TEXT_ALIGN_TYPE align, - ushort flags, - int width, - bool countret = false, - bool countspaces = false - ) - { - if (font >= FontCount) - { - return null; - } - - MultilinesFontInfo info = new MultilinesFontInfo(); - info.Reset(); - info.Align = align; - MultilinesFontInfo ptr = info; - int indentionOffset = 0; - ptr.IndentionOffset = 0; - bool isFixed = (flags & UOFONT_FIXED) != 0; - bool isCropped = (flags & UOFONT_CROPPED) != 0; - int charCount = 0; - int lastSpace = 0; - int readWidth = 0; - int newlineval = countret ? 1 : 0; - - for (int i = 0; i < len; i++) - { - char si = str[i]; - - if ( /*si == '\r' ||*/ - si == '\n') - { - if (si == '\r' || isFixed || isCropped) - { - continue; - } - } - - if (si == ' ') - { - lastSpace = i; - ptr.Width += readWidth; - readWidth = 0; - ptr.CharCount += charCount; - charCount = 0; - } - - ref FontCharacterData fcd = ref _fontData[font, GetASCIIIndex(si)]; - int eval = ptr.CharStart; - - if (si == '\n' || ptr.Width + readWidth + fcd.Width > width) - { - if (lastSpace == ptr.CharStart && lastSpace == 0 && si != '\n') - { - ++eval; - } - - if (si == '\n') - { - ptr.Width += readWidth; - ptr.CharCount += charCount + newlineval; - lastSpace = i; - - if (ptr.Width == 0) - { - ptr.Width = 1; - } - - if (ptr.MaxHeight == 0) - { - ptr.MaxHeight = 14; - } - - ptr.Data.Length = ptr.CharCount - newlineval; - - MultilinesFontInfo newptr = new MultilinesFontInfo(); - newptr.Reset(); - ptr.Next = newptr; - ptr = newptr; - ptr.Align = align; - ptr.CharStart = i + 1; - readWidth = 0; - charCount = 0; - indentionOffset = 0; - ptr.IndentionOffset = 0; - - continue; - } - - if (lastSpace + 1 == eval && !isFixed && !isCropped) - { - ptr.Width += readWidth; - ptr.CharCount += charCount; - - if (ptr.Width == 0) - { - ptr.Width = 1; - } - - if (ptr.MaxHeight == 0) - { - ptr.MaxHeight = 14; - } - - MultilinesFontInfo newptr = new MultilinesFontInfo(); - newptr.Reset(); - ptr.Next = newptr; - ptr = newptr; - ptr.Align = align; - ptr.CharStart = i; - lastSpace = i - 1; - charCount = 0; - - if (ptr.Align == TEXT_ALIGN_TYPE.TS_LEFT && (flags & UOFONT_INDENTION) != 0) - { - indentionOffset = 14; - } - - ptr.IndentionOffset = indentionOffset; - readWidth = indentionOffset; - } - else - { - if (isFixed) - { - MultilinesFontData mfd1 = new MultilinesFontData( - 0xFFFFFFFF, - flags, - font, - si, - 0 - ); - - ptr.Data.Add(mfd1); - readWidth += fcd.Width; - - if (fcd.Height > ptr.MaxHeight) - { - ptr.MaxHeight = fcd.Height; - } - - charCount++; - ptr.Width += readWidth; - ptr.CharCount += charCount; - } - - i = lastSpace + 1; - si = i < len ? str[i] : '\0'; - - if (ptr.Width == 0) - { - ptr.Width = 1; - } - else if (countspaces && si != '\0' && lastSpace - eval == ptr.CharCount) - { - ptr.CharCount++; - } - - if (ptr.MaxHeight == 0) - { - ptr.MaxHeight = 14; - } - - //ptr.CharCount = charCount; - charCount = 0; - ptr.Data.Length = ptr.CharCount; - - if (isFixed || isCropped) - { - break; - } - - MultilinesFontInfo newptr = new MultilinesFontInfo(); - newptr.Reset(); - ptr.Next = newptr; - ptr = newptr; - ptr.Align = align; - ptr.CharStart = i; - - if (ptr.Align == TEXT_ALIGN_TYPE.TS_LEFT && (flags & UOFONT_INDENTION) != 0) - { - indentionOffset = 14; - } - - ptr.IndentionOffset = indentionOffset; - readWidth = indentionOffset; - } - } - - MultilinesFontData mfd = new MultilinesFontData(0xFFFFFFFF, flags, font, si, 0); - - ptr.Data.Add(mfd); - readWidth += si == '\r' ? 0 : fcd.Width; - - if (fcd.Height > ptr.MaxHeight) - { - ptr.MaxHeight = fcd.Height; - } - - charCount++; - } - - ptr.Width += readWidth; - ptr.CharCount += charCount; - - if (readWidth == 0 && len > 0 && (str[len - 1] == '\n' || str[len - 1] == '\r')) - { - ptr.Width = 1; - ptr.MaxHeight = 14; - } - - if (font == 4) - { - ptr = info; - - while (ptr != null) - { - if (ptr.Width > 1) - { - ptr.MaxHeight = ptr.MaxHeight + 2; - } - else - { - ptr.MaxHeight = ptr.MaxHeight + 6; - } - - ptr = ptr.Next; - } - } - - return info; - } - - public void SetUseHTML( - bool value, - uint htmlStartColor = 0xFFFFFFFF, - bool backgroundCanBeColored = false - ) - { - IsUsingHTML = value; - _htmlStatus.Color = htmlStartColor; - _htmlStatus.IsHtmlBackgroundColored = backgroundCanBeColored; - } - - public FontInfo GenerateUnicode( - byte font, - string str, - ushort color, - byte cell, - int width, - TEXT_ALIGN_TYPE align, - ushort flags, - bool saveHitmap, - int height - ) - { - if (string.IsNullOrEmpty(str)) - { - return FontInfo.Empty; - } - - if ( - (flags & UOFONT_FIXED) != 0 - || (flags & UOFONT_CROPPED) != 0 - || (flags & UOFONT_CROPTEXTURE) != 0 - ) - { - if (width == 0) - { - return FontInfo.Empty; - } - - int realWidth = GetWidthUnicode(font, str.AsSpan()); - - if (realWidth > width) - { - string newstr = GetTextByWidthUnicode( - font, - str.AsSpan(), - width, - (flags & UOFONT_CROPPED) != 0, - align, - flags - ); - - if ((flags & UOFONT_CROPTEXTURE) != 0 && !string.IsNullOrEmpty(newstr)) - { - int totalheight = 0; - - while (totalheight < height) - { - totalheight += GetHeightUnicode(font, newstr, width, align, flags); - - if (str.Length > newstr.Length) - { - newstr += GetTextByWidthUnicode( - font, - str.AsSpan(0, newstr.Length), - width, - (flags & UOFONT_CROPPED) != 0, - align, - flags - ); - } - else - { - break; - } - } - } - - return GeneratePixelsUnicode( - font, - newstr, - color, - cell, - width, - align, - flags, - saveHitmap - ); - } - } - - return GeneratePixelsUnicode(font, str, color, cell, width, align, flags, saveHitmap); - } - - public unsafe string GetTextByWidthUnicode( - byte font, - ReadOnlySpan str, - int width, - bool isCropped, - TEXT_ALIGN_TYPE align, - ushort flags - ) - { - if (font >= 20 || _unicodeFontAddress[font] == IntPtr.Zero || str.IsEmpty) - { - return string.Empty; - } - - uint* table = (uint*)_unicodeFontAddress[font]; - int strLen = str.Length; - - Span span = stackalloc char[strLen]; - ValueStringBuilder sb = new ValueStringBuilder(span); - - if (IsUsingHTML) - { - unsafe - { - HTMLChar* data = stackalloc HTMLChar[strLen]; - - GetHTMLData(data, font, str, ref strLen, align, flags); - } - - int size = str.Length - strLen; - - if (size > 0) - { - sb.Append(str.Slice(0, size)); - str = str.Slice(str.Length - strLen, strLen); - - if (GetWidthUnicode(font, str) < width) - { - isCropped = false; - } - } - } - - if (isCropped) - { - uint offset = table['.']; - - if (offset != 0 && offset != 0xFFFFFFFF) - { - width -= *(byte*)((IntPtr)table + (int)offset + 2) * 3 + 3; - } - } - - int textLength = 0; - - foreach (char c in str) - { - uint offset = table[c]; - sbyte charWidth = 0; - - if (offset != 0 && offset != 0xFFFFFFFF) - { - byte* ptr = (byte*)((IntPtr)table + (int)offset); - charWidth = (sbyte)((sbyte)ptr[0] + (sbyte)ptr[2] + 1); - } - else if (c == ' ') - { - charWidth = UNICODE_SPACE_WIDTH; - } - - if (charWidth != 0) - { - textLength += charWidth; - - if (textLength > width) - { - break; - } - - sb.Append(c); - } - } - - if (isCropped) - { - sb.Append("..."); - } - - string ss = sb.ToString(); - - sb.Dispose(); - - return ss; - } - - public int GetWidthUnicode(byte font, string str) - { - if (font >= 20 || _unicodeFontAddress[font] == IntPtr.Zero || string.IsNullOrEmpty(str)) - { - return 0; - } - - return GetWidthUnicode(font, str.AsSpan()); - } - - private unsafe int GetWidthUnicode(byte font, ReadOnlySpan str) - { - if (font >= 20 || _unicodeFontAddress[font] == IntPtr.Zero || str.IsEmpty) - { - return 0; - } - - uint* table = (uint*)_unicodeFontAddress[font]; - int textLength = 0; - int maxTextLenght = 0; - - foreach (char c in str) - { - uint offset = table[c]; - - if (c != '\r' && offset != 0 && offset != 0xFFFFFFFF) - { - byte* ptr = (byte*)((IntPtr)table + (int)offset); - textLength += (sbyte)ptr[0] + (sbyte)ptr[2] + 1; - } - else if (c == ' ') - { - textLength += UNICODE_SPACE_WIDTH; - } - else if (c == '\n') - { - maxTextLenght = Math.Max(maxTextLenght, textLength); - textLength = 0; - } - } - - return Math.Max(maxTextLenght, textLength); - } - - public unsafe int GetCharWidthUnicode(byte font, char c) - { - if (font >= 20 || _unicodeFontAddress[font] == IntPtr.Zero || c == 0 || c == '\r') - { - return 0; - } - - uint* table = (uint*)_unicodeFontAddress[font]; - uint offset = table[c]; - - if (offset != 0 && offset != 0xFFFFFFFF) - { - byte* ptr = (byte*)((IntPtr)table + (int)offset); - - return (sbyte)ptr[0] + (sbyte)ptr[2] + 1; - } - - if (c == ' ') - { - return UNICODE_SPACE_WIDTH; - } - - return 0; - } - - public int GetWidthExUnicode( - byte font, - string text, - int maxwidth, - TEXT_ALIGN_TYPE align, - ushort flags - ) - { - if ( - font >= 20 || _unicodeFontAddress[font] == IntPtr.Zero || string.IsNullOrEmpty(text) - ) - { - return 0; - } - - MultilinesFontInfo info = GetInfoUnicode( - font, - text, - text.Length, - align, - flags, - maxwidth - ); - - int textWidth = 0; - - while (info != null) - { - if (info.Width > textWidth) - { - textWidth = info.Width; - } - - MultilinesFontInfo ptr = info; - info = info.Next; - ptr.Data.Clear(); - ptr = null; - } - - return textWidth + 4; - } - - public unsafe MultilinesFontInfo GetInfoUnicode( - byte font, - string str, - int len, - TEXT_ALIGN_TYPE align, - ushort flags, - int width, - bool countret = false, - bool countspaces = false - ) - { - _htmlStatus.WebLinkColor = 0xFF0000FF; - _htmlStatus.VisitedWebLinkColor = 0x0000FFFF; - _htmlStatus.BackgroundColor = 0; - _htmlStatus.Margins = Margin.Empty; - - if (font >= 20 || _unicodeFontAddress[font] == IntPtr.Zero) - { - return null; - } - - if (IsUsingHTML) - { - return GetInfoHTML(font, str, len, align, flags, width); - } - - uint* table = (uint*)_unicodeFontAddress[font]; - MultilinesFontInfo info = new MultilinesFontInfo(); - info.Reset(); - info.Align = align; - MultilinesFontInfo ptr = info; - int indetionOffset = 0; - ptr.IndentionOffset = 0; - int charCount = 0; - int lastSpace = 0; - int readWidth = 0; - int newlineval = countret ? 1 : 0; - int extraheight = (flags & UOFONT_EXTRAHEIGHT) != 0 ? 4 : 0; - bool isFixed = (flags & UOFONT_FIXED) != 0; - bool isCropped = (flags & UOFONT_CROPPED) != 0; - TEXT_ALIGN_TYPE current_align = align; - ushort current_flags = flags; - byte current_font = font; - uint charcolor = 0xFFFFFFFF; - uint current_charcolor = 0xFFFFFFFF; - uint lastspace_charcolor = 0xFFFFFFFF; - uint lastaspace_current_charcolor = 0xFFFFFFFF; - - for (int i = 0; i < len; i++) - { - char si = str[i]; - - if (si == '\n') - { - if (isFixed || isCropped) - { - si = (char)0; - } - } - - if ( - (table[si] == 0 || table[si] == 0xFFFFFFFF) - && si != ' ' - && si != '\n' - && si != '\r' - ) - { - continue; - } - - byte* data = (byte*)((IntPtr)table + (int)table[si]); - - if (si == ' ') - { - lastSpace = i; - ptr.Width += readWidth; - readWidth = 0; - ptr.CharCount += charCount; - charCount = 0; - lastspace_charcolor = charcolor; - lastaspace_current_charcolor = current_charcolor; - } - - int eval = ptr.CharStart; - - if (ptr.Width + readWidth + (sbyte)data[0] + (sbyte)data[2] > width || si == '\n') - { - if (lastSpace == ptr.CharStart && lastSpace == 0 && si != '\n') - { - ++eval; - } - - if (si == '\n') - { - ptr.Width += readWidth; - ptr.CharCount += charCount + newlineval; - lastSpace = i; - - if (ptr.Width == 0) - { - ptr.Width = 1; - } - - if (ptr.MaxHeight == 0) - { - ptr.MaxHeight = 14 + extraheight; - } - - ptr.Data.Length = ptr.CharCount - newlineval; - MultilinesFontInfo newptr = new MultilinesFontInfo(); - newptr.Reset(); - ptr.Next = newptr; - ptr = newptr; - ptr.Align = current_align; - ptr.CharStart = i + 1; - readWidth = 0; - charCount = 0; - indetionOffset = 0; - ptr.IndentionOffset = 0; - - continue; - } - - if (lastSpace + 1 == eval && !isFixed && !isCropped) - { - ptr.Width += readWidth; - ptr.CharCount += charCount; - - if (ptr.Width == 0) - { - ptr.Width = 1; - } - - if (ptr.MaxHeight == 0) - { - ptr.MaxHeight = 14 + extraheight; - } - - MultilinesFontInfo newptr = new MultilinesFontInfo(); - newptr.Reset(); - ptr.Next = newptr; - ptr = newptr; - ptr.Align = current_align; - ptr.CharStart = i; - lastSpace = i - 1; - charCount = 0; - - if ( - ptr.Align == TEXT_ALIGN_TYPE.TS_LEFT - && (current_flags & UOFONT_INDENTION) != 0 - ) - { - indetionOffset = 14; - } - - ptr.IndentionOffset = indetionOffset; - readWidth = indetionOffset; - } - else - { - if (isFixed) - { - MultilinesFontData mfd1 = new MultilinesFontData( - current_charcolor, - current_flags, - current_font, - si, - 0 - ); - - ptr.Data.Add(mfd1); - readWidth += si == '\r' ? 0 : (sbyte)data[0] + (sbyte)data[2] + 1; - - if ((sbyte)data[1] + (sbyte)data[3] > ptr.MaxHeight) - { - ptr.MaxHeight = (sbyte)data[1] + (sbyte)data[3] + extraheight; - } - - charCount++; - ptr.Width += readWidth; - ptr.CharCount += charCount; - } - - i = lastSpace + 1; - charcolor = lastspace_charcolor; - current_charcolor = lastspace_charcolor; - si = i < str.Length ? str[i] : '\0'; - - if (ptr.Width == 0) - { - ptr.Width = 1; - } - else if (countspaces && si != '\0' && lastSpace - eval == ptr.CharCount) - { - ptr.CharCount++; - } - - if (ptr.MaxHeight == 0) - { - ptr.MaxHeight = 14 + extraheight; - } - - //ptr.CharCount = charCount; - - charCount = 0; - ptr.Data.Length = ptr.CharCount; - - if (isFixed || isCropped) - { - break; - } - - MultilinesFontInfo newptr = new MultilinesFontInfo(); - newptr.Reset(); - ptr.Next = newptr; - ptr = newptr; - ptr.Align = current_align; - ptr.CharStart = i; - charCount = 0; - - if ( - ptr.Align == TEXT_ALIGN_TYPE.TS_LEFT - && (current_flags & UOFONT_INDENTION) != 0 - ) - { - indetionOffset = 14; - } - - ptr.IndentionOffset = indetionOffset; - readWidth = indetionOffset; - } - } - - MultilinesFontData mfd = new MultilinesFontData( - current_charcolor, - current_flags, - current_font, - si, - 0 - ); - - ptr.Data.Add(mfd); - - if (si == ' ') - { - readWidth += UNICODE_SPACE_WIDTH; - - if (ptr.MaxHeight <= 0) - { - ptr.MaxHeight = 5 + extraheight; - } - } - else - { - readWidth += si == '\r' ? 0 : (sbyte)data[0] + (sbyte)data[2] + 1; - - if ((sbyte)data[1] + (sbyte)data[3] > ptr.MaxHeight) - { - ptr.MaxHeight = (sbyte)data[1] + (sbyte)data[3] + extraheight; - } - } - - charCount++; - } - - ptr.Width += readWidth; - ptr.CharCount += charCount; - - if (readWidth == 0 && len != 0) - { - switch (str[len - 1]) - { - case '\n': - ptr.CharCount += newlineval; - goto case '\r'; - - case '\r': - ptr.Width = 1; - ptr.MaxHeight = 14; - - break; - } - } - - return info; - } - - private unsafe FontInfo GeneratePixelsUnicode( - byte font, - string str, - ushort color, - byte cell, - int width, - TEXT_ALIGN_TYPE align, - ushort flags, - bool saveHitmap - ) - { - if (font >= 20 || _unicodeFontAddress[font] == IntPtr.Zero) - { - return FontInfo.Empty; - } - - int len = str.Length; - - if (len == 0) - { - return FontInfo.Empty; - } - - int oldWidth = width; - - if (width == 0) - { - width = GetWidthUnicode(font, str.AsSpan()); - - if (width == 0) - { - return FontInfo.Empty; - } - } - - MultilinesFontInfo info = GetInfoUnicode(font, str, len, align, flags, width); - - if (info == null) - { - return FontInfo.Empty; - } - - if (IsUsingHTML && (_htmlStatus.Margins.X != 0 || _htmlStatus.Margins.Width != 0)) - { - while (info != null) - { - MultilinesFontInfo ptr1 = info.Next; - info.Data.Clear(); - info = null; - info = ptr1; - } - - int newWidth = width - (_htmlStatus.Margins.Right); - - if (newWidth < 10) - { - newWidth = 10; - } - - info = GetInfoUnicode(font, str, len, align, flags, newWidth); - - if (info == null) - { - return FontInfo.Empty; - } - } - - if (oldWidth == 0 && RecalculateWidthByInfo) - { - MultilinesFontInfo ptr1 = info; - width = 0; - - while (ptr1 != null) - { - if (ptr1.Width > width) - { - width = ptr1.Width; - } - - ptr1 = ptr1.Next; - } - } - - width += 4; - int height = GetHeightUnicode(info); - - if (height == 0) - { - while (info != null) - { - MultilinesFontInfo ptr1 = info; - info = info.Next; - ptr1.Data.Clear(); - ptr1 = null; - } - - return FontInfo.Empty; - } - - height += _htmlStatus.Margins.Y + _htmlStatus.Margins.Height + 4; - int blocksize = height * width; - uint[] pData = new uint[blocksize]; // System.Buffers.ArrayPool.Shared.Rent(blocksize); - - try - { - uint* table = (uint*)_unicodeFontAddress[font]; - int lineOffsY = _htmlStatus.Margins.Y; - MultilinesFontInfo ptr = info; - uint datacolor = 0; - - if (color == 0xFFFF) - { - datacolor = 0xFEFFFFFF; - } - else - { - datacolor = - HuesHelper.RgbaToArgb((HuesLoader.Instance.GetHueColorRgba8888(cell, color) << 8) | 0xFF); - } - - bool isItalic = (flags & UOFONT_ITALIC) != 0; - bool isSolid = (flags & UOFONT_SOLID) != 0; - bool isBlackBorder = (flags & UOFONT_BLACK_BORDER) != 0; - bool isUnderline = (flags & UOFONT_UNDERLINE) != 0; - uint blackColor = 0xFF010101; - bool isLink = false; - int linkStartX = 0; - int linkStartY = 0; - int linesCount = 0; - var links = new FastList(); - - while (ptr != null) - { - info = ptr; - linesCount++; - int w = _htmlStatus.Margins.Y; - - switch (ptr.Align) - { - case TEXT_ALIGN_TYPE.TS_CENTER: - { - w += (width - 8) / 2 - ptr.Width / 2; - - if (w < 0) - { - w = 0; - } - - break; - } - - case TEXT_ALIGN_TYPE.TS_RIGHT: - { - w += width - 10 - ptr.Width; - - if (w < 0) - { - w = 0; - } - - break; - } - - case TEXT_ALIGN_TYPE.TS_LEFT when (flags & UOFONT_INDENTION) != 0: - w += ptr.IndentionOffset; - - break; - } - - ushort oldLink = 0; - var dataSize = ptr.Data.Length; - - for (int i = 0; i < dataSize; i++) - { - ref MultilinesFontData dataPtr = ref ptr.Data.Buffer[i]; - char si = dataPtr.Item; - table = (uint*)_unicodeFontAddress[dataPtr.Font]; - - if (!isLink) - { - oldLink = dataPtr.LinkID; - - if (oldLink != 0) - { - isLink = true; - linkStartX = w; - linkStartY = lineOffsY + 3; - } - } - else if (dataPtr.LinkID == 0 || i + 1 == dataSize) - { - isLink = false; - int linkHeight = lineOffsY - linkStartY; - - if (linkHeight < 14) - { - linkHeight = 14; - } - - int ofsX = 0; - - if (si == ' ') - { - ofsX = UNICODE_SPACE_WIDTH; - } - else if ((table[si] == 0 || table[si] == 0xFFFFFFFF) && si != ' ') { } - else - { - byte* xData = (byte*)((IntPtr)table + (int)table[si]); - ofsX = (sbyte)xData[2]; - } - - WebLinkRect wlr = new WebLinkRect - { - LinkID = oldLink, - Bounds = new Margin(linkStartX, linkStartY, w - ofsX, linkHeight) - }; - - links.Add(wlr); - oldLink = 0; - } - - if ((table[si] == 0 || table[si] == 0xFFFFFFFF) && si != ' ') - { - continue; - } - - byte* data = (byte*)((IntPtr)table + (int)table[si]); - int offsX = 0; - int offsY = 0; - int dw = 0; - int dh = 0; - - if (si == ' ') - { - offsX = 0; - dw = UNICODE_SPACE_WIDTH; - } - else - { - offsX = (sbyte)data[0] + 1; - offsY = (sbyte)data[1]; - dw = data[2]; - dh = data[3]; - data += 4; - } - - int tmpW = w; - uint charcolor = datacolor; - - bool isBlackPixel = - ((charcolor >> 0) & 0xFF) <= 8 - && ((charcolor >> 8) & 0xFF) <= 8 - && ((charcolor >> 16) & 0xFF) <= 8; - - if (si != ' ') - { - if (IsUsingHTML && i < ptr.Data.Length) - { - isItalic = (dataPtr.Flags & UOFONT_ITALIC) != 0; - isSolid = (dataPtr.Flags & UOFONT_SOLID) != 0; - isBlackBorder = (dataPtr.Flags & UOFONT_BLACK_BORDER) != 0; - isUnderline = (dataPtr.Flags & UOFONT_UNDERLINE) != 0; - - if (dataPtr.Color != 0xFFFFFFFF) - { - charcolor = HuesHelper.RgbaToArgb(dataPtr.Color); - - //isBlackPixel = ((charcolor >> 24) & 0xFF) <= 8 && ((charcolor >> 16) & 0xFF) <= 8 && ((charcolor >> 8) & 0xFF) <= 8; - isBlackPixel = - ((charcolor >> 0) & 0xFF) <= 8 - && ((charcolor >> 8) & 0xFF) <= 8 - && ((charcolor >> 16) & 0xFF) <= 8; - } - } - - int scanlineCount = ((dw - 1) >> 3) + 1; - - for (int y = 0; y < dh; y++) - { - int testY = offsY + lineOffsY + y; - - if (testY < 0) - { - testY = 0; - } - - if (testY >= height) - { - break; - } - - byte* scanlines = data; - data += scanlineCount; - - int italicOffset = 0; - - if (isItalic) - { - italicOffset = (int)((dh - y) / ITALIC_FONT_KOEFFICIENT); - } - - int testX = w + offsX + italicOffset + (isSolid ? 1 : 0); - - for (int c = 0; c < scanlineCount; c++) - { - int coff = c << 3; - - for (int j = 0; j < 8; j++) - { - int x = coff + j; - - if (x >= dw) - { - break; - } - - int nowX = testX + x; - - if (nowX >= width) - { - break; - } - - byte cl = (byte)(scanlines[c] & (1 << (7 - j))); - int block = testY * width + nowX; - - if (cl != 0) - { - pData[block] = charcolor; - } - } - } - } - - if (isSolid) - { - uint solidColor = blackColor; - - if (solidColor == charcolor) - { - solidColor++; - } - - int minXOk = w + offsX > 0 ? -1 : 0; - int maxXOk = w + offsX + dw < width ? 1 : 0; - maxXOk += dw; - - for (int cy = 0; cy < dh; cy++) - { - int testY = offsY + lineOffsY + cy; - - if (testY >= height) - { - break; - } - - if (testY < 0) - { - testY = 0; - } - - int italicOffset = 0; - - if (isItalic && cy < dh) - { - italicOffset = (int)((dh - cy) / ITALIC_FONT_KOEFFICIENT); - } - - for (int cx = minXOk; cx < maxXOk; cx++) - { - int testX = cx + w + offsX + italicOffset; - - if (testX >= width) - { - break; - } - - int block = testY * width + testX; - - if (pData[block] == 0 && pData[block] != solidColor) - { - int endX = cx < dw ? 2 : 1; - - if (endX == 2 && testX + 1 >= width) - { - endX--; - } - - for (int x = 0; x < endX; x++) - { - int nowX = testX + x; - int testBlock = testY * width + nowX; - - if ( - pData[testBlock] != 0 - && pData[testBlock] != solidColor - ) - { - pData[block] = solidColor; - - break; - } - } - } - } - } - - for (int cy = 0; cy < dh; cy++) - { - int testY = offsY + lineOffsY + cy; - - if (testY >= height) - { - break; - } - - if (testY < 0) - { - testY = 0; - } - - int italicOffset = 0; - - if (isItalic) - { - italicOffset = (int)((dh - cy) / ITALIC_FONT_KOEFFICIENT); - } - - for (int cx = 0; cx < dw; cx++) - { - int testX = cx + w + offsX + italicOffset; - - if (testX >= width) - { - break; - } - - int block = testY * width + testX; - - if (pData[block] == solidColor) - { - pData[block] = charcolor; - } - } - } - } - - if (isBlackBorder && !isBlackPixel) - { - int minXOk = w + offsX > 0 ? -1 : 0; - int minYOk = offsY + lineOffsY > 0 ? -1 : 0; - int maxXOk = w + offsX + dw < width ? 1 : 0; - int maxYOk = offsY + lineOffsY + dh < height ? 1 : 0; - maxXOk += dw; - maxYOk += dh; - - for (int cy = minYOk; cy < maxYOk; cy++) - { - int testY = offsY + lineOffsY + cy; - - if (testY < 0) - { - testY = 0; - } - - if (testY >= height) - { - break; - } - - int italicOffset = 0; - - if (isItalic && cy >= 0 && cy < dh) - { - italicOffset = (int)((dh - cy) / ITALIC_FONT_KOEFFICIENT); - } - - for (int cx = minXOk; cx < maxXOk; cx++) - { - int testX = cx + w + offsX + italicOffset; - - if (testX >= width) - { - break; - } - - int block = testY * width + testX; - - if (pData[block] == 0 && pData[block] != blackColor) - { - int startX = cx > 0 ? -1 : 0; - int startY = cy > 0 ? -1 : 0; - int endX = cx < dw - 1 ? 2 : 1; - int endY = cy < dh - 1 ? 2 : 1; - - if (endX == 2 && testX + 1 >= width) - { - endX--; - } - - bool passed = false; - - for (int x = startX; x < endX; x++) - { - int nowX = testX + x; - - for (int y = startY; y < endY; y++) - { - int testBlock = (testY + y) * width + nowX; - - if (testBlock < 0) - { - continue; - } - - if ( - testBlock < pData.Length - && pData[testBlock] != 0 - && pData[testBlock] != blackColor - ) - { - pData[block] = blackColor; - passed = true; - - break; - } - } - - if (passed) - { - break; - } - } - } - } - } - } - - w += dw + offsX + (isSolid ? 1 : 0); - } - else if (si == ' ') - { - w += UNICODE_SPACE_WIDTH; - - if (IsUsingHTML) - { - isUnderline = (dataPtr.Flags & UOFONT_UNDERLINE) != 0; - - if (dataPtr.Color != 0xFFFFFFFF) - { - charcolor = HuesHelper.RgbaToArgb(dataPtr.Color); - - isBlackPixel = - ((charcolor >> 0) & 0xFF) <= 8 - && ((charcolor >> 8) & 0xFF) <= 8 - && ((charcolor >> 16) & 0xFF) <= 8; - } - } - } - - if (isUnderline) - { - int minXOk = tmpW + offsX > 0 ? -1 : 0; - int maxXOk = w + offsX + dw < width ? 1 : 0; - byte* aData = (byte*)((IntPtr)table + (int)table[(byte)'a']); - int testY = lineOffsY + (sbyte)aData[1] + (sbyte)aData[3]; - - if (testY >= height) - { - break; - } - - if (testY < 0) - { - testY = 0; - } - - for (int cx = minXOk; cx < dw + maxXOk; cx++) - { - int testX = cx + tmpW + offsX + (isSolid ? 1 : 0); - - if (testX >= width) - { - break; - } - - int block = testY * width + testX; - pData[block] = charcolor; - } - } - } - - lineOffsY += ptr.MaxHeight; - ptr = ptr.Next; - info.Data.Clear(); - info = null; - } - - if ( - IsUsingHTML - && _htmlStatus.IsHtmlBackgroundColored - && _htmlStatus.BackgroundColor != 0 - ) - { - _htmlStatus.BackgroundColor |= 0xFF; - - uint hue = HuesHelper.RgbaToArgb(_htmlStatus.BackgroundColor); - - for (int y = 0; y < height; y++) - { - int yPos = y * width; - - for (int x = 0; x < width; x++) - { - ref uint p = ref pData[yPos + x]; - - if (p == 0) - { - p = hue; - } - } - } - } - - FontInfo fi = new FontInfo(); - - fi.LineCount = linesCount; - fi.Width = width; - fi.Height = height; - fi.Data = pData; - fi.Links = links; - return fi; - } - finally - { - //System.Buffers.ArrayPool.Shared.Return(pData, true); - } - } - - private unsafe MultilinesFontInfo GetInfoHTML( - byte font, - string str, - int len, - TEXT_ALIGN_TYPE align, - ushort flags, - int width - ) - { - if (len <= 0) - { - return null; - } - - HTMLChar* htmlData = stackalloc HTMLChar[len]; - - GetHTMLData(htmlData, font, str.AsSpan(), ref len, align, flags); - - if (len <= 0) - { - return null; - } - - MultilinesFontInfo info = new MultilinesFontInfo(); - info.Reset(); - info.Align = align; - MultilinesFontInfo ptr = info; - int indentionOffset = 0; - ptr.IndentionOffset = indentionOffset; - int charCount = 0; - int lastSpace = 0; - int readWidth = 0; - bool isFixed = (flags & UOFONT_FIXED) != 0; - bool isCropped = (flags & UOFONT_CROPPED) != 0; - - if (len != 0) - { - ptr.Align = htmlData[0].Align; - } - - for (int i = 0; i < len; i++) - { - char si = htmlData[i].Char; - - uint* table = (uint*)_unicodeFontAddress[htmlData[i].Font]; - - if (si == 0x000D || si == '\n') - { - if (si == 0x000D || isFixed || isCropped) - { - si = (char)0; - } - else - { - si = '\n'; - } - } - - if ((table[si] == 0 || table[si] == 0xFFFFFFFF) && si != ' ' && si != '\n') - { - continue; - } - - byte* data = (byte*)((IntPtr)table + (int)table[si]); - - if (si == ' ') - { - lastSpace = i; - ptr.Width += readWidth; - readWidth = 0; - ptr.CharCount += charCount; - charCount = 0; - } - - int solidWidth = htmlData[i].Flags & UOFONT_SOLID; - - if ( - ptr.Width + readWidth + (sbyte)data[0] + (sbyte)data[2] + solidWidth > width - || si == '\n' - ) - { - if (lastSpace == ptr.CharStart && lastSpace == 0 && si != '\n') - { - ptr.CharStart = 1; - } - - if (si == '\n') - { - ptr.Width += readWidth; - ptr.CharCount += charCount; - lastSpace = i; - - if (ptr.Width <= 0) - { - ptr.Width = 1; - } - - ptr.MaxHeight = MAX_HTML_TEXT_HEIGHT; - ptr.Data.Length = ptr.CharCount; - MultilinesFontInfo newptr = new MultilinesFontInfo(); - newptr.Reset(); - ptr.Next = newptr; - ptr = newptr; - - ptr.Align = htmlData[i].Align; - - ptr.CharStart = i + 1; - readWidth = 0; - charCount = 0; - indentionOffset = 0; - ptr.IndentionOffset = indentionOffset; - - continue; - } - - if (lastSpace + 1 == ptr.CharStart && !isFixed && !isCropped) - { - ptr.Width += readWidth; - ptr.CharCount += charCount; - - if (ptr.Width <= 0) - { - ptr.Width = 1; - } - - ptr.MaxHeight = MAX_HTML_TEXT_HEIGHT; - MultilinesFontInfo newptr = new MultilinesFontInfo(); - newptr.Reset(); - ptr.Next = newptr; - ptr = newptr; - - ptr.Align = htmlData[i].Align; - - ptr.CharStart = i; - lastSpace = i - 1; - charCount = 0; - - if ( - ptr.Align == TEXT_ALIGN_TYPE.TS_LEFT - && (htmlData[i].Flags & UOFONT_INDENTION) != 0 - ) - { - indentionOffset = 14; - } - - ptr.IndentionOffset = indentionOffset; - readWidth = indentionOffset; - } - else - { - if (isFixed) - { - MultilinesFontData mfd1 = new MultilinesFontData( - htmlData[i].Color, - htmlData[i].Flags, - htmlData[i].Font, - si, - htmlData[i].LinkID - ); - - ptr.Data.Add(mfd1); - readWidth += (sbyte)data[0] + (sbyte)data[2] + 1; - ptr.MaxHeight = MAX_HTML_TEXT_HEIGHT; - charCount++; - ptr.Width += readWidth; - ptr.CharCount += charCount; - } - - i = lastSpace + 1; - - if (i >= len) - { - break; - } - - si = htmlData[i].Char; - - solidWidth = htmlData[i].Flags & UOFONT_SOLID; - - if (ptr.Width <= 0) - { - ptr.Width = 1; - } - - ptr.MaxHeight = MAX_HTML_TEXT_HEIGHT; - ptr.Data.Length = ptr.CharCount; - charCount = 0; - - if (isFixed || isCropped) - { - break; - } - - MultilinesFontInfo newptr = new MultilinesFontInfo(); - newptr.Reset(); - ptr.Next = newptr; - ptr = newptr; - - ptr.Align = htmlData[i].Align; - - ptr.CharStart = i; - - if ( - ptr.Align == TEXT_ALIGN_TYPE.TS_LEFT - && (htmlData[i].Flags & UOFONT_INDENTION) != 0 - ) - { - indentionOffset = 14; - } - - ptr.IndentionOffset = indentionOffset; - readWidth = indentionOffset; - } - } - - MultilinesFontData mfd = new MultilinesFontData( - htmlData[i].Color, - htmlData[i].Flags, - htmlData[i].Font, - si, - htmlData[i].LinkID - ); - - ptr.Data.Add(mfd); - - if (si == ' ') - { - readWidth += UNICODE_SPACE_WIDTH; - } - else - { - readWidth += (sbyte)data[0] + (sbyte)data[2] + 1 + solidWidth; - } - - charCount++; - } - - ptr.Width += readWidth; - ptr.CharCount += charCount; - ptr.MaxHeight = MAX_HTML_TEXT_HEIGHT; - - return info; - } - - private unsafe void GetHTMLData( - HTMLChar* data, - byte font, - ReadOnlySpan str, - ref int len, - TEXT_ALIGN_TYPE align, - ushort flags - ) - { - int newlen = 0; - - HTMLDataInfo info = new HTMLDataInfo - { - Tag = HTML_TAG_TYPE.HTT_NONE, - Align = align, - Flags = flags, - Font = font, - Color = _htmlStatus.Color, - Link = 0 - }; - - var stack = new FastList(); - stack.Add(info); - HTMLDataInfo currentInfo = info; - - for (int i = 0; i < len; i++) - { - char si = str[i]; - - if (si == '<') - { - bool endTag = false; - - HTMLDataInfo newInfo = new HTMLDataInfo - { - Tag = HTML_TAG_TYPE.HTT_NONE, - Align = TEXT_ALIGN_TYPE.TS_LEFT, - Flags = 0, - Font = 0xFF, - Color = 0, - Link = 0 - }; - - HTML_TAG_TYPE tag = ParseHTMLTag(str, len, ref i, ref endTag, ref newInfo); - - if (tag == HTML_TAG_TYPE.HTT_NONE) - { - continue; - } - - if (!endTag) - { - if (newInfo.Font == 0xFF) - { - newInfo.Font = stack[stack.Length - 1].Font; - } - - if (tag != HTML_TAG_TYPE.HTT_BODY) - { - stack.Add(newInfo); - } - else - { - stack.Clear(); - newlen = 0; - - if (newInfo.Color != 0) - { - info.Color = newInfo.Color; - } - - stack.Add(info); - } - } - else if (stack.Length > 1) - { - //int index = -1; - - for (var j = stack.Length - 1; j >= 1; j--) - { - if (stack[j].Tag == tag) - { - stack.RemoveAt(j); // MAYBE ERROR? - - break; - } - } - } - - GetCurrentHTMLInfo(ref stack, ref currentInfo); - - switch (tag) - { - case HTML_TAG_TYPE.HTT_LEFT: - case HTML_TAG_TYPE.HTT_CENTER: - case HTML_TAG_TYPE.HTT_RIGHT: - - if (newlen != 0) - { - endTag = true; - } - - goto case HTML_TAG_TYPE.HTT_P; - - case HTML_TAG_TYPE.HTT_P: - - if (endTag) - { - si = '\n'; - } - else - { - si = (char)0; - } - - break; - - case HTML_TAG_TYPE.HTT_BODYBGCOLOR: - case HTML_TAG_TYPE.HTT_BR: - case HTML_TAG_TYPE.HTT_BQ: - si = '\n'; - - break; - - default: - si = (char)0; - - break; - } - } - - if (si != 0) - { - ref HTMLChar c = ref data[newlen]; - - c.Char = si; - c.Font = currentInfo.Font; - c.Align = currentInfo.Align; - c.Flags = currentInfo.Flags; - c.Color = currentInfo.Color; - c.LinkID = currentInfo.Link; - - ++newlen; - } - } - - len = newlen; - } - - private void GetCurrentHTMLInfo(ref FastList list, ref HTMLDataInfo info) - { - info.Tag = HTML_TAG_TYPE.HTT_NONE; - info.Align = TEXT_ALIGN_TYPE.TS_LEFT; - info.Flags = 0; - info.Font = 0xFF; - info.Color = 0; - info.Link = 0; - - for (int i = 0; i < list.Length; i++) - { - ref var current = ref list.Buffer[i]; - - switch (current.Tag) - { - case HTML_TAG_TYPE.HTT_NONE: - info = current; - - break; - - case HTML_TAG_TYPE.HTT_B: - case HTML_TAG_TYPE.HTT_I: - case HTML_TAG_TYPE.HTT_U: - case HTML_TAG_TYPE.HTT_P: - info.Flags |= current.Flags; - info.Align = current.Align; - - break; - - case HTML_TAG_TYPE.HTT_A: - info.Flags |= current.Flags; - info.Color = current.Color; - info.Link = current.Link; - - break; - - case HTML_TAG_TYPE.HTT_BIG: - case HTML_TAG_TYPE.HTT_SMALL: - - if ( - current.Font != 0xFF && _unicodeFontAddress[current.Font] != IntPtr.Zero - ) - { - info.Font = current.Font; - } - - break; - - case HTML_TAG_TYPE.HTT_BASEFONT: - - if ( - current.Font != 0xFF && _unicodeFontAddress[current.Font] != IntPtr.Zero - ) - { - info.Font = current.Font; - } - - if (current.Color != 0) - { - info.Color = current.Color; - } - - break; - - case HTML_TAG_TYPE.HTT_H1: - case HTML_TAG_TYPE.HTT_H2: - case HTML_TAG_TYPE.HTT_H4: - case HTML_TAG_TYPE.HTT_H5: - info.Flags |= current.Flags; - goto case HTML_TAG_TYPE.HTT_H3; - - case HTML_TAG_TYPE.HTT_H3: - case HTML_TAG_TYPE.HTT_H6: - - if ( - current.Font != 0xFF && _unicodeFontAddress[current.Font] != IntPtr.Zero - ) - { - info.Font = current.Font; - } - - break; - - case HTML_TAG_TYPE.HTT_BQ: - info.Color = current.Color; - info.Flags |= current.Flags; - - break; - - case HTML_TAG_TYPE.HTT_LEFT: - case HTML_TAG_TYPE.HTT_CENTER: - case HTML_TAG_TYPE.HTT_RIGHT: - info.Align = current.Align; - - break; - - case HTML_TAG_TYPE.HTT_DIV: - info.Align = current.Align; - - break; - } - } - } - - private HTML_TAG_TYPE ParseHTMLTag( - ReadOnlySpan str, - int len, - ref int i, - ref bool endTag, - ref HTMLDataInfo info - ) - { - HTML_TAG_TYPE tag = HTML_TAG_TYPE.HTT_NONE; - i++; - - if (i < len && str[i] == '/') - { - endTag = true; - i++; - } - - while (i < len && str[i] == ' ') - { - i++; - } - - int j = i; - - for (; i < len; i++) - { - // special case for single <{TAG}/> - if (str[i] == '/') - { - endTag = true; - - break; - } - - if (str[i] == ' ' || str[i] == '>') - { - break; - } - } - - if (j != i && i < len) - { - int cmdLen = i - j; - - int startIndex = j; - - j = i; - - while (i < len && str[i] != '>') - { - i++; - } - - ReadOnlySpan span = str.Slice(startIndex, cmdLen); - - if (span.Equals("b".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_B; - } - else if (span.Equals("i".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_I; - } - else if (span.Equals("a".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_A; - } - else if (span.Equals("u".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_U; - } - else if (span.Equals("p".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_P; - } - else if (span.Equals("big".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_BIG; - } - else if (span.Equals("small".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_SMALL; - } - else if (span.Equals("body".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_BODY; - } - else if ( - span.Equals("basefont".AsSpan(), StringComparison.InvariantCultureIgnoreCase) - ) - { - tag = HTML_TAG_TYPE.HTT_BASEFONT; - } - else if (span.Equals("h1".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_H1; - } - else if (span.Equals("h2".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_H2; - } - else if (span.Equals("h3".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_H3; - } - else if (span.Equals("h4".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_H4; - } - else if (span.Equals("h5".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_H5; - } - else if (span.Equals("h6".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_H6; - } - else if (span.Equals("br".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_BR; - } - else if (span.Equals("bq".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_BQ; - } - else if (span.Equals("left".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_LEFT; - } - else if ( - span.Equals("center".AsSpan(), StringComparison.InvariantCultureIgnoreCase) - ) - { - tag = HTML_TAG_TYPE.HTT_CENTER; - } - else if (span.Equals("right".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_RIGHT; - } - else if (span.Equals("div".AsSpan(), StringComparison.InvariantCultureIgnoreCase)) - { - tag = HTML_TAG_TYPE.HTT_DIV; - } - else - { - if ( - str.IndexOf( - "bodybgcolor".AsSpan(), - StringComparison.InvariantCultureIgnoreCase - ) >= 0 - ) - { - tag = HTML_TAG_TYPE.HTT_BODYBGCOLOR; - j = str.IndexOf( - "bgcolor".AsSpan(), - StringComparison.InvariantCultureIgnoreCase - ); - endTag = false; - } - else if ( - str.IndexOf( - "basefont".AsSpan(), - StringComparison.InvariantCultureIgnoreCase - ) >= 0 - ) - { - tag = HTML_TAG_TYPE.HTT_BASEFONT; - j = str.IndexOf( - "color".AsSpan(), - StringComparison.InvariantCultureIgnoreCase - ); - endTag = false; - } - else if ( - str.IndexOf( - "bodytext".AsSpan(), - StringComparison.InvariantCultureIgnoreCase - ) >= 0 - ) - { - tag = HTML_TAG_TYPE.HTT_BODY; - j = str.IndexOf( - "text".AsSpan(), - StringComparison.InvariantCultureIgnoreCase - ); - endTag = false; - } - else - { - Log.Warn($"Unhandled HTML param:\t{str.ToString()}"); - } - } - - if (!endTag) - { - GetHTMLInfoFromTag(tag, ref info); - - if (i < len && j != i) - { - switch (tag) - { - case HTML_TAG_TYPE.HTT_BODYBGCOLOR: - case HTML_TAG_TYPE.HTT_BODY: - case HTML_TAG_TYPE.HTT_BASEFONT: - case HTML_TAG_TYPE.HTT_A: - case HTML_TAG_TYPE.HTT_DIV: - case HTML_TAG_TYPE.HTT_P: - cmdLen = i - j; - - if (str.Length != 0 && str.Length > j && str.Length >= cmdLen) - { - GetHTMLInfoFromContent(ref info, str, j, cmdLen); - } - - break; - } - } - } - } - - return tag; - } - - private unsafe void GetHTMLInfoFromContent( - ref HTMLDataInfo info, - ReadOnlySpan content, - int start, - int length - ) - { - int i = 0; - - if (!content.IsEmpty) - { - while (i < length && char.IsWhiteSpace(content[i + start])) - { - ++i; - } - } - else - { - return; - } - - char* bufferCmd = stackalloc char[128]; - char* bufferValue = stackalloc char[512]; - - for (int cmdLenght = 0; i < length; ++i) - { - char c = content[i + start]; - - bufferCmd[cmdLenght++] = /*char.IsLetter(c) ? char.ToLowerInvariant(c) :*/ - c; - - if (c == ' ' || c == '=' || c == '\\') - { - ++i; - bool inside = false; - int valueLength = 0; - for (; i < length; ++i) - { - c = content[i + start]; - - if (c == ' ' || c == '\\' || c == '<' || c == '>' || (c == '=' && !inside)) - { - break; - } - - if (c != '"') - { - bufferValue[valueLength++] = /*char.IsLetter(c) ? char.ToLowerInvariant(c) :*/ - c; - } - else - { - inside = !inside; - } - } - - if (valueLength != 0) - { - switch (info.Tag) - { - case HTML_TAG_TYPE.HTT_BODY: - case HTML_TAG_TYPE.HTT_BODYBGCOLOR: - - if (StringHelper.UnsafeCompare(bufferCmd, "text", cmdLenght)) - { - ReadColorFromTextBuffer( - bufferValue, - valueLength, - ref info.Color - ); - } - else if ( - StringHelper.UnsafeCompare(bufferCmd, "bgcolor", cmdLenght) - ) - { - if (_htmlStatus.IsHtmlBackgroundColored) - { - ReadColorFromTextBuffer( - bufferValue, - valueLength, - ref _htmlStatus.BackgroundColor - ); - } - } - else if (StringHelper.UnsafeCompare(bufferCmd, "link", cmdLenght)) - { - ReadColorFromTextBuffer( - bufferValue, - valueLength, - ref _htmlStatus.WebLinkColor - ); - } - else if (StringHelper.UnsafeCompare(bufferCmd, "vlink", cmdLenght)) - { - ReadColorFromTextBuffer( - bufferValue, - valueLength, - ref _htmlStatus.VisitedWebLinkColor - ); - } - else if ( - StringHelper.UnsafeCompare(bufferCmd, "leftmargin", cmdLenght) - ) - { - _htmlStatus.Margins.X = int.Parse( - new string(bufferValue, 0, valueLength) - ); - } - else if ( - StringHelper.UnsafeCompare(bufferCmd, "topmargin", cmdLenght) - ) - { - _htmlStatus.Margins.Y = int.Parse( - new string(bufferValue, 0, valueLength) - ); - } - else if ( - StringHelper.UnsafeCompare(bufferCmd, "rightmargin", cmdLenght) - ) - { - _htmlStatus.Margins.Width = int.Parse( - new string(bufferValue, 0, valueLength) - ); - } - else if ( - StringHelper.UnsafeCompare(bufferCmd, "bottommargin", cmdLenght) - ) - { - _htmlStatus.Margins.Height = int.Parse( - new string(bufferValue, 0, valueLength) - ); - } - - break; - - case HTML_TAG_TYPE.HTT_BASEFONT: - - if (StringHelper.UnsafeCompare(bufferCmd, "color", cmdLenght)) - { - ReadColorFromTextBuffer( - bufferValue, - valueLength, - ref info.Color - ); - } - else if (StringHelper.UnsafeCompare(bufferCmd, "size", cmdLenght)) - { - byte font = byte.Parse(new string(bufferValue, 0, valueLength)); - - if (font == 0 || font == 4) - { - info.Font = 1; - } - else if (font < 4) - { - info.Font = 2; - } - else - { - info.Font = 0; - } - } - - break; - - case HTML_TAG_TYPE.HTT_A: - - if (StringHelper.UnsafeCompare(bufferCmd, "href", cmdLenght)) - { - info.Flags = UOFONT_UNDERLINE; - info.Color = _htmlStatus.WebLinkColor; - info.Link = GetWebLinkID( - bufferValue, - valueLength, - ref info.Color - ); - } - - break; - - case HTML_TAG_TYPE.HTT_P: - case HTML_TAG_TYPE.HTT_DIV: - - if (StringHelper.UnsafeCompare(bufferCmd, "align", cmdLenght)) - { - if ( - StringHelper.UnsafeCompare(bufferValue, "left", valueLength) - ) - { - info.Align = TEXT_ALIGN_TYPE.TS_LEFT; - } - else if ( - StringHelper.UnsafeCompare( - bufferValue, - "center", - valueLength - ) - ) - { - info.Align = TEXT_ALIGN_TYPE.TS_CENTER; - } - else if ( - StringHelper.UnsafeCompare( - bufferValue, - "right", - valueLength - ) - ) - { - info.Align = TEXT_ALIGN_TYPE.TS_RIGHT; - } - } - - break; - } - } - - cmdLenght = 0; - } - } - } - - private unsafe ushort GetWebLinkID(char* link, int linkLength, ref uint color) - { - foreach (KeyValuePair ll in _webLinks) - { - if ( - ll.Value.Link.Length == linkLength - && StringHelper.UnsafeCompare(link, ll.Value.Link, linkLength) - ) - { - if (ll.Value.IsVisited) - { - color = _htmlStatus.VisitedWebLinkColor; - } - - return ll.Key; - } - } - - ushort linkID = (ushort)(_webLinks.Count + 1); - - if (!_webLinks.TryGetValue(linkID, out WebLink webLink)) - { - webLink = new WebLink(); - webLink.IsVisited = false; - webLink.Link = new string(link, 0, linkLength); - - _webLinks[linkID] = webLink; - } - - return linkID; - } - - public bool GetWebLink(ushort link, out WebLink result) - { - if (!_webLinks.TryGetValue(link, out result)) - { - return false; - } - - result.IsVisited = true; - - return true; - } - - private unsafe void ReadColorFromTextBuffer(char* buffer, int length, ref uint color) - { - color = 0x00_00_00_00; - - if (length > 0) - { - if (buffer[0] == '#') - { - if (length > 1) - { - int startIndex = buffer[1] == '0' && buffer[2] == 'x' ? 3 : 1; - - string temp = new string(buffer, startIndex, length - startIndex); - uint.TryParse( - temp, - NumberStyles.HexNumber, - CultureInfo.InvariantCulture, - out var cc - ); - - byte* clrbuf = (byte*)&cc; - color = (uint)( - (clrbuf[0] << 24) | (clrbuf[1] << 16) | (clrbuf[2] << 8) | 0xFF - ); - } - } - else if (char.IsNumber(buffer[0])) - { - color = Convert.ToUInt32(new string(buffer, 0, length), 16); - } - else - { - if (StringHelper.UnsafeCompare(buffer, "red", length)) - { - color = 0x0000FFFF; - } - else if (StringHelper.UnsafeCompare(buffer, "cyan", length)) - { - color = 0xFFFF00FF; - } - else if (StringHelper.UnsafeCompare(buffer, "blue", length)) - { - color = 0xFF0000FF; - } - else if (StringHelper.UnsafeCompare(buffer, "darkblue", length)) - { - color = 0xA00000FF; - } - else if (StringHelper.UnsafeCompare(buffer, "lightblue", length)) - { - color = 0xE6D8ADFF; - } - else if (StringHelper.UnsafeCompare(buffer, "purple", length)) - { - color = 0x800080FF; - } - else if (StringHelper.UnsafeCompare(buffer, "yellow", length)) - { - color = 0x00FFFFFF; - } - else if (StringHelper.UnsafeCompare(buffer, "lime", length)) - { - color = 0x00FF00FF; - } - else if (StringHelper.UnsafeCompare(buffer, "magenta", length)) - { - color = 0xFF00FFFF; - } - else if (StringHelper.UnsafeCompare(buffer, "white", length)) - { - color = 0xFFFEFEFF; - } - else if (StringHelper.UnsafeCompare(buffer, "silver", length)) - { - color = 0xC0C0C0FF; - } - else if ( - StringHelper.UnsafeCompare(buffer, "gray", length) - || StringHelper.UnsafeCompare(buffer, "grey", length) - ) - { - color = 0x808080FF; - } - else if (StringHelper.UnsafeCompare(buffer, "black", length)) - { - color = 0x010101FF; - } - else if (StringHelper.UnsafeCompare(buffer, "orange", length)) - { - color = 0x00A5FFFF; - } - else if (StringHelper.UnsafeCompare(buffer, "brown", length)) - { - color = 0x2A2AA5FF; - } - else if (StringHelper.UnsafeCompare(buffer, "maroon", length)) - { - color = 0x000080FF; - } - else if (StringHelper.UnsafeCompare(buffer, "green", length)) - { - color = 0x008000FF; - } - else if (StringHelper.UnsafeCompare(buffer, "olive", length)) - { - color = 0x008080FF; - } - } - } - } - - private void GetHTMLInfoFromTag(HTML_TAG_TYPE tag, ref HTMLDataInfo info) - { - info.Tag = tag; - info.Align = TEXT_ALIGN_TYPE.TS_LEFT; - info.Flags = 0; - info.Font = 0xFF; - info.Color = 0; - info.Link = 0; - - switch (tag) - { - case HTML_TAG_TYPE.HTT_B: - info.Flags = UOFONT_SOLID; - - break; - - case HTML_TAG_TYPE.HTT_I: - info.Flags = UOFONT_ITALIC; - - break; - - case HTML_TAG_TYPE.HTT_U: - info.Flags = UOFONT_UNDERLINE; - - break; - - case HTML_TAG_TYPE.HTT_P: - info.Flags = UOFONT_INDENTION; - - break; - - case HTML_TAG_TYPE.HTT_BIG: - info.Font = 0; - - break; - - case HTML_TAG_TYPE.HTT_SMALL: - info.Font = 2; - - break; - - case HTML_TAG_TYPE.HTT_H1: - info.Flags = UOFONT_SOLID | UOFONT_UNDERLINE; - info.Font = 0; - - break; - - case HTML_TAG_TYPE.HTT_H2: - info.Flags = UOFONT_SOLID; - info.Font = 0; - - break; - - case HTML_TAG_TYPE.HTT_H3: - info.Font = 0; - - break; - - case HTML_TAG_TYPE.HTT_H4: - info.Flags = UOFONT_SOLID; - info.Font = 2; - - break; - - case HTML_TAG_TYPE.HTT_H5: - info.Flags = UOFONT_ITALIC; - info.Font = 2; - - break; - - case HTML_TAG_TYPE.HTT_H6: - info.Font = 2; - - break; - - case HTML_TAG_TYPE.HTT_BQ: - info.Flags = UOFONT_BQ; - info.Color = 0x008000FF; - - break; - - case HTML_TAG_TYPE.HTT_LEFT: - info.Align = TEXT_ALIGN_TYPE.TS_LEFT; - - break; - - case HTML_TAG_TYPE.HTT_CENTER: - info.Align = TEXT_ALIGN_TYPE.TS_CENTER; - - break; - - case HTML_TAG_TYPE.HTT_RIGHT: - info.Align = TEXT_ALIGN_TYPE.TS_RIGHT; - - break; - } - } - - private int GetHeightUnicode(MultilinesFontInfo info) - { - int textHeight = 0; - - for (; info != null; info = info.Next) - { - if (IsUsingHTML) - { - textHeight += MAX_HTML_TEXT_HEIGHT; - } - else - { - textHeight += info.MaxHeight; - } - } - - return textHeight; - } - - public int GetHeightUnicode( - byte font, - string str, - int width, - TEXT_ALIGN_TYPE align, - ushort flags - ) - { - if (font >= 20 || _unicodeFontAddress[font] == IntPtr.Zero || string.IsNullOrEmpty(str)) - { - return 0; - } - - if (width <= 0) - { - width = GetWidthUnicode(font, str.AsSpan()); - } - - MultilinesFontInfo info = GetInfoUnicode(font, str, str.Length, align, flags, width); - - int textHeight = 0; - - while (info != null) - { - if (IsUsingHTML) - { - textHeight += MAX_HTML_TEXT_HEIGHT; - } - else - { - textHeight += info.MaxHeight; - } - - MultilinesFontInfo ptr = info; - info = info.Next; - ptr.Data.Clear(); - ptr = null; - } - - return textHeight; - } - - public unsafe (int, int) GetCaretPosUnicode( - byte font, - string str, - int pos, - int width, - TEXT_ALIGN_TYPE align, - ushort flags - ) - { - int x = 0; - int y = 0; - - switch (align) - { - case TEXT_ALIGN_TYPE.TS_CENTER: - x = width >> 1; - - break; - - case TEXT_ALIGN_TYPE.TS_RIGHT: - x = width; - - break; - } - - if (font >= 20 || _unicodeFontAddress[font] == IntPtr.Zero || string.IsNullOrEmpty(str)) - { - return (x, y); - } - - if (width == 0) - { - width = GetWidthUnicode(font, str.AsSpan()); - } - - MultilinesFontInfo info = GetInfoUnicode(font, str, str.Length, align, flags, width); - - if (info == null) - { - return (x, y); - } - - uint* table = (uint*)_unicodeFontAddress[font]; - - while (info != null) - { - switch (info.Align) - { - case TEXT_ALIGN_TYPE.TS_CENTER: - x = (width - info.Width) >> 1; - - if (x < 0) - { - x = 0; - } - - break; - - case TEXT_ALIGN_TYPE.TS_RIGHT: - x = width; - - break; - - default: - x = 0; - - break; - } - - int len = info.CharCount; - - if (info.CharStart == pos) - { - return (x, y); - } - - if (pos <= info.CharStart + len && info.Data.Length >= len) - { - for (int i = 0; i < len; i++) - { - char ch = info.Data[i].Item; - - uint offset = table[ch]; - - if (ch != '\r' && offset != 0 && offset != 0xFFFFFFFF) - { - byte* cptr = (byte*)((IntPtr)table + (int)offset); - x += (sbyte)cptr[0] + (sbyte)cptr[2] + 1; - } - else if (ch == ' ') - { - x += UNICODE_SPACE_WIDTH; - } - - if (info.CharStart + i + 1 == pos) - { - return (x, y); - } - } - } - else - { - x = width; - } - - if (info.Next != null) - { - y += info.MaxHeight; - } - - MultilinesFontInfo ptr = info; - info = info.Next; - ptr.Data.Clear(); - ptr = null; - } - - return (x, y); - } - - public (int, int) GetCaretPosASCII( - byte font, - string str, - int pos, - int width, - TEXT_ALIGN_TYPE align, - ushort flags - ) - { - int x = 0; - int y = 0; - - switch (align) - { - case TEXT_ALIGN_TYPE.TS_CENTER: - x = width >> 1; - - break; - - case TEXT_ALIGN_TYPE.TS_RIGHT: - x = width; - - break; - } - - if (font >= FontCount || string.IsNullOrEmpty(str)) - { - return (x, y); - } - - if (width == 0) - { - width = GetWidthASCII(font, str); - } - - MultilinesFontInfo info = GetInfoASCII(font, str, str.Length, align, flags, width); - - if (info == null) - { - return (x, y); - } - - while (info != null) - { - switch (info.Align) - { - case TEXT_ALIGN_TYPE.TS_CENTER: - x = (width - info.Width) >> 1; - - if (x < 0) - { - x = 0; - } - - break; - - case TEXT_ALIGN_TYPE.TS_RIGHT: - x = width; - - break; - - default: - x = 0; - - break; - } - - int len = info.CharCount; - - if (info.CharStart == pos) - { - return (x, y); - } - - if (pos <= info.CharStart + len && info.Data.Length >= len) - { - for (int i = 0; i < len; i++) - { - x += _fontData[font, GetASCIIIndex(info.Data[i].Item)].Width; - - if (info.CharStart + i + 1 == pos) - { - return (x, y); - } - } - } - else - { - x = width; - } - - if (info.Next != null) - { - y += info.MaxHeight; - } - - MultilinesFontInfo ptr1 = info; - info = info.Next; - ptr1.Data.Clear(); - ptr1 = null; - } - - return (x, y); - } - } - - public enum TEXT_ALIGN_TYPE - { - TS_LEFT = 0, - TS_CENTER, - TS_RIGHT - } - - public enum HTML_TAG_TYPE - { - HTT_NONE = 0, - HTT_B, - HTT_I, - HTT_A, - HTT_U, - HTT_P, - HTT_BIG, - HTT_SMALL, - HTT_BODY, - HTT_BASEFONT, - HTT_H1, - HTT_H2, - HTT_H3, - HTT_H4, - HTT_H5, - HTT_H6, - HTT_BR, - HTT_BQ, - HTT_LEFT, - HTT_CENTER, - HTT_RIGHT, - HTT_DIV, - - HTT_BODYBGCOLOR - } - - [StructLayout(LayoutKind.Sequential)] - public ref struct FontHeader - { - public byte Width, - Height, - Unknown; - } - - public unsafe struct FontCharacterData - { - public FontCharacterData(byte w, byte h, ushort* data) - { - Width = w; - Height = h; - Data = data; - } - - public byte Width, - Height; - public ushort* Data; - } - - public sealed class MultilinesFontInfo - { - public TEXT_ALIGN_TYPE Align; - public int CharCount; - public int CharStart; - public FastList Data = new FastList(); - public int IndentionOffset; - public int MaxHeight; - public MultilinesFontInfo Next; - public int Width; - - public void Reset() - { - Width = 0; - IndentionOffset = 0; - MaxHeight = 0; - CharStart = 0; - CharCount = 0; - Align = TEXT_ALIGN_TYPE.TS_LEFT; - Next = null; - } - } - - public struct MultilinesFontData - { - public MultilinesFontData(uint color, ushort flags, byte font, char item, ushort linkid) - { - Color = color; - Flags = flags; - Font = font; - Item = item; - LinkID = linkid; - } - - public uint Color; - public ushort Flags; - public byte Font; - public char Item; - public ushort LinkID; - //public MultilinesFontData Next; - } - - public struct WebLinkRect - { - public ushort LinkID; - public FontsLoader.Margin Bounds; - } - - public class WebLink - { - public bool IsVisited; - public string Link; - } - - public struct HTMLChar - { - public char Char; - public byte Font; - public TEXT_ALIGN_TYPE Align; - public ushort Flags; - public uint Color; - public ushort LinkID; - } - - public struct HTMLDataInfo - { - public HTML_TAG_TYPE Tag; - public TEXT_ALIGN_TYPE Align; - public ushort Flags; - public byte Font; - public uint Color; - public ushort Link; - } -} diff --git a/src/ClassicUO.Assets/GumpsLoader.cs b/src/ClassicUO.Assets/GumpsLoader.cs deleted file mode 100644 index c43f25686..000000000 --- a/src/ClassicUO.Assets/GumpsLoader.cs +++ /dev/null @@ -1,257 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using System; -using System.IO; -using System.Runtime.InteropServices; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class GumpsLoader : UOFileLoader - { - private static GumpsLoader _instance; - private UOFile _file; - - public const int MAX_GUMP_DATA_INDEX_COUNT = 0x10000; - - private GumpsLoader(int count) { } - - public static GumpsLoader Instance => - _instance ?? (_instance = new GumpsLoader(MAX_GUMP_DATA_INDEX_COUNT)); - - public bool UseUOPGumps = false; - - public override Task Load() - { - return Task.Run(() => - { - string path = UOFileManager.GetUOFilePath("gumpartLegacyMUL.uop"); - - if (UOFileManager.IsUOPInstallation && File.Exists(path)) - { - _file = new UOFileUop(path, "build/gumpartlegacymul/{0:D8}.tga", true); - Entries = new UOFileIndex[ - Math.Max(((UOFileUop)_file).TotalEntriesCount, MAX_GUMP_DATA_INDEX_COUNT) - ]; - UseUOPGumps = true; - } - else - { - path = UOFileManager.GetUOFilePath("gumpart.mul"); - string pathidx = UOFileManager.GetUOFilePath("gumpidx.mul"); - - if (!File.Exists(path)) - { - path = UOFileManager.GetUOFilePath("Gumpart.mul"); - } - - if (!File.Exists(pathidx)) - { - pathidx = UOFileManager.GetUOFilePath("Gumpidx.mul"); - } - - _file = new UOFileMul(path, pathidx, MAX_GUMP_DATA_INDEX_COUNT, 12); - - UseUOPGumps = false; - } - - _file.FillEntries(ref Entries); - - string pathdef = UOFileManager.GetUOFilePath("gump.def"); - - if (!File.Exists(pathdef)) - { - return; - } - - using (DefReader defReader = new DefReader(pathdef, 3)) - { - while (defReader.Next()) - { - int ingump = defReader.ReadInt(); - - if ( - ingump < 0 - || ingump >= MAX_GUMP_DATA_INDEX_COUNT - || ingump >= Entries.Length - || Entries[ingump].Length > 0 - ) - { - continue; - } - - int[] group = defReader.ReadGroup(); - - if (group == null) - { - continue; - } - - for (int i = 0; i < group.Length; i++) - { - int checkIndex = group[i]; - - if ( - checkIndex < 0 - || checkIndex >= MAX_GUMP_DATA_INDEX_COUNT - || checkIndex >= Entries.Length - || Entries[checkIndex].Length <= 0 - ) - { - continue; - } - - Entries[ingump] = Entries[checkIndex]; - - Entries[ingump].Hue = (ushort)defReader.ReadInt(); - - break; - } - } - } - }); - } - - public unsafe GumpInfo GetGump(uint index) - { - ref UOFileIndex entry = ref GetValidRefEntry((int)index); - - if (entry.Width <= 0 && entry.Height <= 0) - { - return default; - } - - ushort color = entry.Hue; - - _file.SetData(entry.Address, entry.FileSize); - _file.Seek(entry.Offset); - - IntPtr dataStart = _file.PositionAddress; - - var pixels = new uint[entry.Width * entry.Height]; - - int* lookuplist = (int*)dataStart; - - int gsize; - - for (int y = 0, half_len = entry.Length >> 2; y < entry.Height; y++) - { - if (y < entry.Height - 1) - { - gsize = lookuplist[y + 1] - lookuplist[y]; - } - else - { - gsize = half_len - lookuplist[y]; - } - - GumpBlock* gmul = (GumpBlock*)(dataStart + (lookuplist[y] << 2)); - - int pos = y * entry.Width; - - for (int i = 0; i < gsize; i++) - { - uint val = gmul[i].Value; - - if (color != 0 && val != 0) - { - val = HuesLoader.Instance.ApplyHueRgba5551(gmul[i].Value, color); - } - - if (val != 0) - { - //val = 0x8000 | val; - val = HuesHelper.Color16To32(gmul[i].Value) | 0xFF_00_00_00; - } - - var count = gmul[i].Run; - pixels.AsSpan().Slice(pos, count).Fill(val); - pos += count; - } - } - - return new GumpInfo() - { - Pixels = pixels, - Width = entry.Width, - Height = entry.Height - }; - } - - //private unsafe void AddPNGSpriteToAtlas(TextureAtlas atlas, uint index, Texture2D texture) - //{ - // uint[] buffer = null; - - // Span pixels = texture.Width * texture.Height <= 1024 ? stackalloc uint[1024] : (buffer = System.Buffers.ArrayPool.Shared.Rent(texture.Width * texture.Height)); - - // Color[] pixelColors = new Color[texture.Width * texture.Height]; - // texture.GetData(pixelColors); - - // for (int i = 0; i < pixelColors.Length; i++) - // { - // pixels[i] = pixelColors[i].PackedValue; - // } - - // try - // { - // ref var spriteInfo = ref _spriteInfos[index]; - - // spriteInfo.Texture = atlas.AddSprite(pixels, texture.Width, texture.Height, out spriteInfo.UV); - // _picker.Set(index, texture.Width, texture.Height, pixels); - // } - // finally - // { - // if (buffer != null) - // { - // System.Buffers.ArrayPool.Shared.Return(buffer, true); - // } - // } - //} - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - private ref struct GumpBlock - { - public readonly ushort Value; - public readonly ushort Run; - } - } - - public ref struct GumpInfo - { - public Span Pixels; - public int Width; - public int Height; - } -} diff --git a/src/ClassicUO.Assets/HuesLoader.cs b/src/ClassicUO.Assets/HuesLoader.cs deleted file mode 100644 index 84891cdeb..000000000 --- a/src/ClassicUO.Assets/HuesLoader.cs +++ /dev/null @@ -1,238 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using System; -using System.IO; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class HuesLoader : UOFileLoader - { - private static HuesLoader _instance; - - private HuesLoader() - { - } - - public static HuesLoader Instance => _instance ?? (_instance = new HuesLoader()); - - public HuesGroup[] HuesRange { get; private set; } - - public int HuesCount { get; private set; } - - public ushort[] RadarCol { get; private set; } - - public override unsafe Task Load() - { - return Task.Run - ( - () => - { - string path = UOFileManager.GetUOFilePath("hues.mul"); - - FileSystemHelper.EnsureFileExists(path); - - UOFileMul file = new UOFileMul(path); - int groupSize = Marshal.SizeOf(); - int entrycount = (int) file.Length / groupSize; - HuesCount = entrycount * 8; - HuesRange = new HuesGroup[entrycount]; - ulong addr = (ulong) file.StartAddress; - - for (int i = 0; i < entrycount; i++) - { - HuesRange[i] = Marshal.PtrToStructure((IntPtr)(addr + (ulong) (i * groupSize))); - } - - path = UOFileManager.GetUOFilePath("radarcol.mul"); - - FileSystemHelper.EnsureFileExists(path); - - UOFileMul radarcol = new UOFileMul(path); - RadarCol = new ushort[(int)(radarcol.Length >> 1)]; - - fixed (ushort* ptr = RadarCol) - { - Unsafe.CopyBlockUnaligned((void*)(byte*)ptr, radarcol.PositionAddress.ToPointer(), (uint)radarcol.Length); - } - - file.Dispose(); - radarcol.Dispose(); - } - ); - } - - public void CreateShaderColors(uint[] buffer) - { - int len = HuesRange.Length; - - int idx = 0; - - for (int r = 0; r < len; r++) - { - for (int y = 0; y < 8; y++) - { - for (int x = 0; x < 32; x++) - { - buffer[idx++] = HuesHelper.Color16To32(HuesRange[r].Entries[y].ColorTable[x]) | 0xFF_00_00_00; - - if (idx >= buffer.Length) - { - return; - } - } - } - } - } - - /* Look up the hue and return the color for the given index. Index must be between 0 and 31. - * The returned color is a 16 bit color in R5B5G5A1 format. */ - public ushort GetHueColorRgba5551(ushort index, ushort hue) - { - if (hue != 0 && hue < HuesCount) - { - hue -= 1; - int g = hue >> 3; - int e = hue % 8; - - return (ushort)(0x8000 | HuesRange[g].Entries[e].ColorTable[index]); - } - - return 0x8000; - } - - /* Look up the hue and return the color for the given index. Index must be between 0 and 31. - * The returned color is a 32 bit color in R8G8B8A8 format. */ - public uint GetHueColorRgba8888(ushort index, ushort hue) - { - return HuesHelper.Color16To32(GetHueColorRgba5551(index, hue)); - } - - /* Apply the hue to the given gray color, returning a 16 bit color. */ - public ushort ApplyHueRgba5551(ushort gray, ushort hue) - { - return GetHueColorRgba5551((ushort)((gray >> 10) & 0x1F), hue); - } - - /* Apply the hue to the given gray color, returning a 32 bit color. */ - public uint ApplyHueRgba8888(ushort gray, ushort hue) - { - return HuesHelper.Color16To32(ApplyHueRgba5551(gray, hue)); - } - - public uint GetPartialHueColor(ushort color, ushort hue) - { - uint cl = HuesHelper.Color16To32(color); - byte R = (byte)(cl & 0xFF); - byte G = (byte)((cl >> 8) & 0xFF); - byte B = (byte)((cl >> 16) & 0xFF); - - if (R != G || R != B) - { - /* Not gray. Don't apply hue. */ - return HuesHelper.Color16To32(color); - } - - if (hue == 0 || hue >= HuesCount) - { - /* Invalid hue. */ - return HuesHelper.Color16To32(color); - } - - return ApplyHueRgba8888(color, hue); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ushort GetRadarColorData(int c) - { - if (c >= 0 && c < RadarCol.Length) - { - return RadarCol[c]; - } - - return 0; - } - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct HuesBlock - { - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] - public ushort[] ColorTable; - public ushort TableStart; - public ushort TableEnd; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] - public char[] Name; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct HuesGroup - { - public uint Header; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] - public HuesBlock[] Entries; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public readonly struct VerdataHuesBlock - { - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] - public readonly ushort[] ColorTable; - public readonly ushort TableStart; - public readonly ushort TableEnd; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] - public readonly char[] Name; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] - public readonly ushort[] Unk; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public readonly struct VerdataHuesGroup - { - public readonly uint Header; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] - public readonly VerdataHuesBlock[] Entries; - } - - public struct FloatHues - { - //[MarshalAs(UnmanagedType.ByValArray, SizeConst = 96)] - public float[] Palette; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Assets/LightsLoader.cs b/src/ClassicUO.Assets/LightsLoader.cs deleted file mode 100644 index a0bb195e3..000000000 --- a/src/ClassicUO.Assets/LightsLoader.cs +++ /dev/null @@ -1,118 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using System; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class LightsLoader : UOFileLoader - { - private static LightsLoader _instance; - private UOFileMul _file; - - public const int MAX_LIGHTS_DATA_INDEX_COUNT = 100; - - private LightsLoader(int count) { } - - public static LightsLoader Instance => - _instance ?? (_instance = new LightsLoader(MAX_LIGHTS_DATA_INDEX_COUNT)); - - public UOFileMul File => _file; - - public override Task Load() - { - return Task.Run(() => - { - string path = UOFileManager.GetUOFilePath("light.mul"); - string pathidx = UOFileManager.GetUOFilePath("lightidx.mul"); - - FileSystemHelper.EnsureFileExists(path); - FileSystemHelper.EnsureFileExists(pathidx); - - _file = new UOFileMul(path, pathidx, MAX_LIGHTS_DATA_INDEX_COUNT); - _file.FillEntries(ref Entries); - }); - } - - public LightInfo GetLight(uint idx) - { - ref var entry = ref GetValidRefEntry((int)idx); - - if (entry.Width == 0 && entry.Height == 0) - { - return default; - } - - var buffer = new uint[entry.Width * entry.Height]; - _file.SetData(entry.Address, entry.FileSize); - _file.Seek(entry.Offset); - - for (int i = 0; i < entry.Height; i++) - { - int pos = i * entry.Width; - - for (int j = 0; j < entry.Width; j++) - { - ushort val = _file.ReadByte(); - // Light can be from -31 to 31. When they are below 0 they are bit inverted - if (val > 0x1F) - { - val = (ushort)(~val & 0x1F); - } - uint rgb24 = (uint)((val << 19) | (val << 11) | (val << 3)); - - if (val != 0) - { - buffer[pos + j] = rgb24 | 0xFF_00_00_00; - } - } - } - - return new LightInfo() - { - Pixels = buffer, - Width = entry.Width, - Height = entry.Height - }; - } - } - - public ref struct LightInfo - { - public Span Pixels; - public int Width; - public int Height; - } -} diff --git a/src/ClassicUO.Assets/MapLoader.cs b/src/ClassicUO.Assets/MapLoader.cs deleted file mode 100644 index f8388e5b0..000000000 --- a/src/ClassicUO.Assets/MapLoader.cs +++ /dev/null @@ -1,686 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using System; -using System.IO; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class MapLoader : UOFileLoader - { - private static MapLoader _instance; - private UOFileMul[] _mapDif; - private UOFileMul[] _mapDifl; - private UOFileMul[] _staDif; - private UOFileMul[] _staDifi; - private UOFileMul[] _staDifl; - - // cannot be a const, due to UOLive implementation - public static int MAPS_COUNT = 6; - - protected MapLoader() - { - } - - public static MapLoader Instance - { - get => _instance ?? (_instance = new MapLoader()); - set - { - _instance?.Dispose(); - _instance = value; - } - } - - public static string MapsLayouts { get; set; } - - public IndexMap[][] BlockData { get; private set; } - - public int[,] MapBlocksSize { get; private set; } - - // ReSharper disable RedundantExplicitArraySize - public int[,] MapsDefaultSize { get; protected set; } = new int[6, 2] - // ReSharper restore RedundantExplicitArraySize - { - { - 7168, 4096 - }, - { - 7168, 4096 - }, - { - 2304, 1600 - }, - { - 2560, 2048 - }, - { - 1448, 1448 - }, - { - 1280, 4096 - } - }; - - public int PatchesCount { get; private set; } - public int[] MapPatchCount { get; private set; } - public int[] StaticPatchCount { get; private set; } - - protected UOFileMul[] _filesIdxStatics; - protected UOFile[] _filesMap; - protected UOFileMul[] _filesStatics; - - protected static UOFile GetMapFile(int map) - { - return map < Instance._filesMap.Length ? Instance._filesMap[map] : null; - } - - protected void Initialize() - { - _filesMap = new UOFile[MAPS_COUNT]; - _filesStatics = new UOFileMul[MAPS_COUNT]; - _filesIdxStatics = new UOFileMul[MAPS_COUNT]; - - MapPatchCount = new int[MAPS_COUNT]; - StaticPatchCount = new int[MAPS_COUNT]; - MapBlocksSize = new int[MAPS_COUNT, 2]; - - BlockData = new IndexMap[MAPS_COUNT][]; - - _mapDif = new UOFileMul[MAPS_COUNT]; - _mapDifl = new UOFileMul[MAPS_COUNT]; - _staDif = new UOFileMul[MAPS_COUNT]; - _staDifi = new UOFileMul[MAPS_COUNT]; - _staDifl = new UOFileMul[MAPS_COUNT]; - } - - public override unsafe Task Load() - { - return Task.Run - ( - () => - { - bool foundOneMap = false; - - if (!string.IsNullOrEmpty(MapsLayouts)) - { - string[] values = MapsLayouts.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - - MAPS_COUNT = values.Length; - MapsDefaultSize = new int[values.Length, 2]; - - Log.Trace($"default maps size overraided. [count: {MAPS_COUNT}]"); - - - int index = 0; - - char[] splitchar = new char[1] { ',' }; - - foreach (string s in values) - { - string[] v = s.Split(splitchar, StringSplitOptions.RemoveEmptyEntries); - - if (v.Length >= 2 && int.TryParse(v[0], out int width) && int.TryParse(v[1], out int height)) - { - MapsDefaultSize[index, 0] = width; - MapsDefaultSize[index, 1] = height; - - Log.Trace($"overraided map size: {width},{height} [index: {index}]"); - } - else - { - Log.Error($"Error parsing 'width,height' values: '{s}'"); - } - - ++index; - } - } - - - Initialize(); - - for (var i = 0; i < MAPS_COUNT; ++i) - { - string path = UOFileManager.GetUOFilePath($"map{i}LegacyMUL.uop"); - - if (UOFileManager.IsUOPInstallation && File.Exists(path)) - { - _filesMap[i] = new UOFileUop(path, $"build/map{i}legacymul/{{0:D8}}.dat"); - foundOneMap = true; - } - else - { - path = UOFileManager.GetUOFilePath($"map{i}.mul"); - - if (File.Exists(path)) - { - _filesMap[i] = new UOFileMul(path); - - foundOneMap = true; - } - - path = UOFileManager.GetUOFilePath($"mapdifl{i}.mul"); - - if (File.Exists(path)) - { - _mapDifl[i] = new UOFileMul(path); - _mapDif[i] = new UOFileMul(UOFileManager.GetUOFilePath($"mapdif{i}.mul")); - _staDifl[i] = new UOFileMul(UOFileManager.GetUOFilePath($"stadifl{i}.mul")); - _staDifi[i] = new UOFileMul(UOFileManager.GetUOFilePath($"stadifi{i}.mul")); - _staDif[i] = new UOFileMul(UOFileManager.GetUOFilePath($"stadif{i}.mul")); - } - } - - path = UOFileManager.GetUOFilePath($"statics{i}.mul"); - - if (File.Exists(path)) - { - _filesStatics[i] = new UOFileMul(path); - } - - path = UOFileManager.GetUOFilePath($"staidx{i}.mul"); - - if (File.Exists(path)) - { - _filesIdxStatics[i] = new UOFileMul(path); - } - } - - if (!foundOneMap) - { - throw new FileNotFoundException("No maps found."); - } - - - int mapblocksize = sizeof(MapBlock); - - if (_filesMap[0].Length / mapblocksize == 393216 || UOFileManager.Version < ClientVersion.CV_4011D) - { - MapsDefaultSize[0, 0] = MapsDefaultSize[1, 0] = 6144; - } - - // This is an hack to patch correctly all maps when you have to fake map1 - if (_filesMap[1] == null || _filesMap[1].StartAddress == IntPtr.Zero) - { - _filesMap[1] = _filesMap[0]; - _filesStatics[1] = _filesStatics[0]; - _filesIdxStatics[1] = _filesIdxStatics[0]; - } - - var res = Parallel.For(0, MAPS_COUNT, i => - { - MapBlocksSize[i, 0] = MapsDefaultSize[i, 0] >> 3; - MapBlocksSize[i, 1] = MapsDefaultSize[i, 1] >> 3; - LoadMap(i); - }); - } - ); - } - - public unsafe void LoadMap(int i) - { - if (i < 0 || i + 1 > MAPS_COUNT || _filesMap[i] == null) - { - i = 0; - } - - if (BlockData[i] != null || _filesMap[i] == null) - { - return; - } - - int mapblocksize = sizeof(MapBlock); - int staticidxblocksize = sizeof(StaidxBlock); - int staticblocksize = sizeof(StaticsBlock); - int width = MapBlocksSize[i, 0]; - int height = MapBlocksSize[i, 1]; - int maxblockcount = width * height; - BlockData[i] = new IndexMap[maxblockcount]; - UOFile file = _filesMap[i]; - UOFile fileidx = _filesIdxStatics[i]; - UOFile staticfile = _filesStatics[i]; - - if (fileidx == null && i == 1) - { - fileidx = _filesIdxStatics[0]; - } - - if (staticfile == null && i == 1) - { - staticfile = _filesStatics[0]; - } - - ulong staticidxaddress = (ulong) fileidx.StartAddress; - ulong endstaticidxaddress = staticidxaddress + (ulong) fileidx.Length; - ulong staticaddress = (ulong) staticfile.StartAddress; - ulong endstaticaddress = staticaddress + (ulong) staticfile.Length; - ulong mapddress = (ulong) file.StartAddress; - ulong endmapaddress = mapddress + (ulong) file.Length; - ulong uopoffset = 0; - int fileNumber = -1; - bool isuop = file is UOFileUop; - - for (int block = 0; block < maxblockcount; block++) - { - ulong realmapaddress = 0, realstaticaddress = 0; - uint realstaticcount = 0; - int blocknum = block; - - if (isuop) - { - blocknum &= 4095; - int shifted = block >> 12; - - if (fileNumber != shifted) - { - fileNumber = shifted; - var uop = file as UOFileUop; - - if (shifted < uop.TotalEntriesCount) - { - var hash = UOFileUop.CreateHash(string.Format(uop.Pattern, shifted)); - - if (uop.TryGetUOPData(hash, out var dataIndex)) - { - uopoffset = (ulong)dataIndex.Offset; - } - } - } - } - - ulong address = mapddress + uopoffset + (ulong) (blocknum * mapblocksize); - - if (address < endmapaddress) - { - realmapaddress = address; - } - - ulong stidxaddress = staticidxaddress + (ulong) (block * staticidxblocksize); - StaidxBlock* bb = (StaidxBlock*) stidxaddress; - - if (stidxaddress < endstaticidxaddress && bb->Size > 0 && bb->Position != 0xFFFFFFFF) - { - ulong address1 = staticaddress + bb->Position; - - if (address1 < endstaticaddress) - { - realstaticaddress = address1; - realstaticcount = (uint) (bb->Size / staticblocksize); - - if (realstaticcount > 1024) - { - realstaticcount = 1024; - } - } - } - - ref IndexMap data = ref BlockData[i][block]; - data.MapAddress = realmapaddress; - data.StaticAddress = realstaticaddress; - data.StaticCount = realstaticcount; - data.OriginalMapAddress = realmapaddress; - data.OriginalStaticAddress = realstaticaddress; - data.OriginalStaticCount = realstaticcount; - } - - if (isuop) - { - // TODO: UOLive needs hashes! we need to find out a better solution, but keep 'em for the moment - //((UOFileUop)file)?.ClearHashes(); - } - } - - public void PatchMapBlock(ulong block, ulong address) - { - int w = MapBlocksSize[0, 0]; - int h = MapBlocksSize[0, 1]; - - int maxBlockCount = w * h; - - if (maxBlockCount < 1) - { - return; - } - - BlockData[0][block].OriginalMapAddress = address; - BlockData[0][block].MapAddress = address; - } - - - public unsafe void PatchStaticBlock(ulong block, ulong address, uint count) - { - int w = MapBlocksSize[0, 0]; - int h = MapBlocksSize[0, 1]; - - int maxBlockCount = w * h; - - if (maxBlockCount < 1) - { - return; - } - - BlockData[0][block].StaticAddress = BlockData[0][block].OriginalStaticAddress = address; - - count = (uint) (count / (sizeof(StaidxBlockVerdata))); - - if (count > 1024) - { - count = 1024; - } - - BlockData[0][block].StaticCount = BlockData[0][block].OriginalStaticCount = count; - } - - public unsafe bool ApplyPatches(ref StackDataReader reader) - { - ResetPatchesInBlockTable(); - - PatchesCount = (int) reader.ReadUInt32BE(); - - if (PatchesCount < 0) - { - PatchesCount = 0; - } - - if (PatchesCount > MAPS_COUNT) - { - PatchesCount = MAPS_COUNT; - } - - Array.Clear(MapPatchCount, 0, MapPatchCount.Length); - Array.Clear(StaticPatchCount, 0, StaticPatchCount.Length); - - bool result = false; - - for (int i = 0; i < PatchesCount; i++) - { - int idx = i; - - //SanitizeMapIndex(ref idx); - - if (_filesMap[idx] == null || _filesMap[idx].StartAddress == IntPtr.Zero) - { - reader.Skip(8); - - continue; - } - - int mapPatchesCount = (int) reader.ReadUInt32BE(); - MapPatchCount[i] = mapPatchesCount; - int staticPatchesCount = (int) reader.ReadUInt32BE(); - StaticPatchCount[i] = staticPatchesCount; - - int w = MapBlocksSize[i, 0]; - int h = MapBlocksSize[i, 1]; - - int maxBlockCount = w * h; - - if (mapPatchesCount != 0) - { - UOFileMul difl = _mapDifl[i]; - UOFileMul dif = _mapDif[i]; - - if (difl == null || dif == null || difl.Length == 0 || dif.Length == 0) - { - continue; - } - - mapPatchesCount = Math.Min(mapPatchesCount, (int) difl.Length >> 2); - - difl.Seek(0); - dif.Seek(0); - - for (int j = 0; j < mapPatchesCount; j++) - { - uint blockIndex = difl.ReadUInt(); - - if (blockIndex < maxBlockCount) - { - BlockData[idx][blockIndex].MapAddress = (ulong) dif.PositionAddress; - - result = true; - } - - dif.Skip(sizeof(MapBlock)); - } - } - - if (staticPatchesCount != 0) - { - UOFileMul difl = _staDifl[i]; - UOFileMul difi = _staDifi[i]; - - if (difl == null || difi == null || _staDif[i] == null || difl.Length == 0 || difi.Length == 0 || _staDif[i].Length == 0) - { - continue; - } - - ulong startAddress = (ulong) _staDif[i].StartAddress; - - staticPatchesCount = Math.Min(staticPatchesCount, (int) difl.Length >> 2); - - difl.Seek(0); - difi.Seek(0); - - int sizeOfStaicsBlock = sizeof(StaticsBlock); - int sizeOfStaidxBlock = sizeof(StaidxBlock); - - for (int j = 0; j < staticPatchesCount; j++) - { - if (difl.IsEOF || difi.IsEOF) - { - break; - } - - uint blockIndex = difl.ReadUInt(); - - StaidxBlock* sidx = (StaidxBlock*) difi.PositionAddress; - - difi.Skip(sizeOfStaidxBlock); - - if (blockIndex < maxBlockCount) - { - ulong realStaticAddress = 0; - int realStaticCount = 0; - - if (sidx->Size > 0 && sidx->Position != 0xFFFF_FFFF) - { - realStaticAddress = startAddress + sidx->Position; - realStaticCount = (int) (sidx->Size / sizeOfStaicsBlock); - - if (realStaticCount > 0) - { - if (realStaticCount > 1024) - { - realStaticCount = 1024; - } - } - } - - BlockData[idx][blockIndex].StaticAddress = realStaticAddress; - - BlockData[idx][blockIndex].StaticCount = (uint) realStaticCount; - - result = true; - } - } - } - } - - return result; - } - - private void ResetPatchesInBlockTable() - { - for (int i = 0; i < MAPS_COUNT; i++) - { - IndexMap[] list = BlockData[i]; - - if (list == null) - { - continue; - } - - int w = MapBlocksSize[i, 0]; - int h = MapBlocksSize[i, 1]; - - int maxBlockCount = w * h; - - if (maxBlockCount < 1) - { - return; - } - - if (_filesMap[i] is UOFileMul mul && mul.StartAddress != IntPtr.Zero) - { - if (_filesIdxStatics[i] is UOFileMul stIdxMul && stIdxMul.StartAddress != IntPtr.Zero) - { - if (_filesStatics[i] is UOFileMul stMul && stMul.StartAddress != IntPtr.Zero) - { - for (int block = 0; block < maxBlockCount; block++) - { - ref IndexMap index = ref list[block]; - index.MapAddress = index.OriginalMapAddress; - index.StaticAddress = index.OriginalStaticAddress; - index.StaticCount = index.OriginalStaticCount; - } - } - } - } - } - } - - public void SanitizeMapIndex(ref int map) - { - if (map == 1 && (_filesMap[1] == null || _filesMap[1].StartAddress == IntPtr.Zero || _filesStatics[1] == null || _filesStatics[1].StartAddress == IntPtr.Zero || _filesIdxStatics[1] == null || _filesIdxStatics[1].StartAddress == IntPtr.Zero)) - { - map = 0; - } - } - - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ref IndexMap GetIndex(int map, int x, int y) - { - int block = x * MapBlocksSize[map, 1] + y; - - return ref BlockData[map][block]; - } - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public ref struct StaticsBlock - { - public ushort Color; - public byte X; - public byte Y; - public sbyte Z; - public ushort Hue; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public ref struct StaidxBlock - { - public uint Position; - public uint Size; - public uint Unknown; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public ref struct StaidxBlockVerdata - { - public uint Position; - public ushort Size; - public byte Unknown; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public ref struct MapCells - { - public ushort TileID; - public sbyte Z; - } - - //[StructLayout(LayoutKind.Sequential, Pack = 1)] - //public struct MapBlock - //{ - // public readonly uint Header; - // [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] - // public MapCells[] Cells; - //} - - [StructLayout(LayoutKind.Sequential, Pack = 1, Size = 4 + 64 * 3)] - public ref struct MapBlock - { - public uint Header; - public unsafe MapCells* Cells; - } - - //[StructLayout(LayoutKind.Sequential, Pack = 1, Size = 4 + 64 * 3)] - //public struct MapBlock2 - //{ - // public readonly uint Header; - // public IntPtr Cells; - //} - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct RadarMapcells - { - public ushort Graphic; - public sbyte Z; - public bool IsLand; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct RadarMapBlock - { - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] - public RadarMapcells[,] Cells; - } - - public struct IndexMap - { - public ulong MapAddress; - public ulong OriginalMapAddress; - public ulong OriginalStaticAddress; - public uint OriginalStaticCount; - public ulong StaticAddress; - public uint StaticCount; - public static IndexMap Invalid = new IndexMap(); - } -} \ No newline at end of file diff --git a/src/ClassicUO.Assets/MultiLoader.cs b/src/ClassicUO.Assets/MultiLoader.cs deleted file mode 100644 index f81e64f74..000000000 --- a/src/ClassicUO.Assets/MultiLoader.cs +++ /dev/null @@ -1,113 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using System.Runtime.InteropServices; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class MultiLoader : UOFileLoader - { - private static MultiLoader _instance; - - public const int MAX_MULTI_DATA_INDEX_COUNT = 0x2200; - - private MultiLoader() - { - } - - public static MultiLoader Instance => _instance ?? (_instance = new MultiLoader()); - - public int Count { get; private set; } - public UOFile File { get; private set; } - - public bool IsUOP { get; private set; } - public int Offset { get; private set; } - - - public override unsafe Task Load() - { - return Task.Run - ( - () => - { - string uopPath = UOFileManager.GetUOFilePath("MultiCollection.uop"); - - if (UOFileManager.IsUOPInstallation && System.IO.File.Exists(uopPath)) - { - Count = MAX_MULTI_DATA_INDEX_COUNT; - File = new UOFileUop(uopPath, "build/multicollection/{0:D6}.bin"); - Entries = new UOFileIndex[Count]; - IsUOP = true; - } - else - { - string path = UOFileManager.GetUOFilePath("multi.mul"); - string pathidx = UOFileManager.GetUOFilePath("multi.idx"); - - if (System.IO.File.Exists(path) && System.IO.File.Exists(pathidx)) - { - File = new UOFileMul(path, pathidx, MAX_MULTI_DATA_INDEX_COUNT, 14); - - Count = Offset = UOFileManager.Version >= ClientVersion.CV_7090 ? sizeof(MultiBlockNew) + 2 : sizeof(MultiBlock); - } - } - - File.FillEntries(ref Entries); - } - ); - } - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public ref struct MultiBlock - { - public ushort ID; - public short X; - public short Y; - public short Z; - public uint Flags; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public ref struct MultiBlockNew - { - public ushort ID; - public short X; - public short Y; - public short Z; - public ushort Flags; - public uint Unknown; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Assets/MultiMapLoader.cs b/src/ClassicUO.Assets/MultiMapLoader.cs deleted file mode 100644 index f1cc0e009..000000000 --- a/src/ClassicUO.Assets/MultiMapLoader.cs +++ /dev/null @@ -1,315 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using System; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; -using System.Text.RegularExpressions; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class MultiMapLoader : UOFileLoader - { - private static MultiMapLoader _instance; - private UOFileMul[] _facets; - private UOFile _file; - - private MultiMapLoader() - { - } - - public static MultiMapLoader Instance => _instance ?? (_instance = new MultiMapLoader()); - - public bool HasFacet(int map) - { - return map >= 0 && map < _facets.Length && _facets[map] != null; - } - - public override Task Load() - { - return Task.Run - ( - () => - { - string path = UOFileManager.GetUOFilePath("Multimap.rle"); - - if (File.Exists(path)) - { - _file = new UOFile(path, true); - } - - var facetFiles = Directory.GetFiles(UOFileManager.BasePath, "*.mul", SearchOption.TopDirectoryOnly) - .Select(s => Regex.Match(s, "facet0.*\\.mul", RegexOptions.IgnoreCase)) - .Where(s => s.Success) - .Select(s => Path.Combine(UOFileManager.BasePath, s.Value)) - .ToArray(); - - _facets = new UOFileMul[facetFiles.Length]; - - for (int i = 0; i < facetFiles.Length; i++) - { - _facets[i] = new UOFileMul(facetFiles[i]); - } - } - ); - } - - public unsafe MultiMapInfo LoadMap - ( - int width, - int height, - int startx, - int starty, - int endx, - int endy - ) - { - if (_file == null || _file.Length == 0) - { - Log.Warn("MultiMap.rle is not loaded!"); - - return default; - } - - _file.Seek(0); - - int w = _file.ReadInt(); - int h = _file.ReadInt(); - - if (w < 1 || h < 1) - { - Log.Warn("Failed to load bounds from MultiMap.rle"); - - return default; - } - - int mapSize = width * height; - - startx = startx >> 1; - endx = endx >> 1; - - int widthDivisor = endx - startx; - - if (widthDivisor == 0) - { - widthDivisor++; - } - - starty = starty >> 1; - endy = endy >> 1; - - int heightDivisor = endy - starty; - - if (heightDivisor == 0) - { - heightDivisor++; - } - - int pwidth = (width << 8) / widthDivisor; - int pheight = (height << 8) / heightDivisor; - - byte[] data = new byte[mapSize]; - - int x = 0, y = 0; - - int maxPixelValue = 1; - int startHeight = starty * pheight; - - while (_file.Position < _file.Length) - { - byte pic = _file.ReadByte(); - byte size = (byte) (pic & 0x7F); - bool colored = (pic & 0x80) != 0; - - int currentHeight = y * pheight; - int posY = width * ((currentHeight - startHeight) >> 8); - - for (int i = 0; i < size; i++) - { - if (colored && x >= startx && x < endx && y >= starty && y < endy) - { - int position = posY + ((pwidth * (x - startx)) >> 8); - - ref byte pixel = ref data[position]; - - if (pixel < 0xFF) - { - if (pixel == maxPixelValue) - { - maxPixelValue++; - } - - pixel++; - } - } - - x++; - - if (x >= w) - { - x = 0; - y++; - currentHeight += pheight; - posY = width * ((currentHeight - startHeight) >> 8); - } - } - } - - if (maxPixelValue <= 0) - { - return default; - } - - int s = Marshal.SizeOf(); - IntPtr ptr = Marshal.AllocHGlobal(s * HuesLoader.Instance.HuesRange.Length); - - for (int i = 0; i < HuesLoader.Instance.HuesRange.Length; i++) - { - Marshal.StructureToPtr(HuesLoader.Instance.HuesRange[i], ptr + i * s, false); - } - - ushort* huesData = (ushort*)(byte*)(ptr + 30800); - - Span colorTable = stackalloc uint[byte.MaxValue]; - var pixels = new uint[mapSize]; - - try - { - int colorOffset = 31 * maxPixelValue; - - for (int i = 0; i < maxPixelValue; i++) - { - colorOffset -= 31; - colorTable[i] = HuesHelper.Color16To32(huesData[colorOffset / maxPixelValue]) | 0xFF_00_00_00; - } - - for (int i = 0; i < mapSize; i++) - { - pixels[i] = data[i] != 0 ? colorTable[data[i] - 1] : 0; - } - } - finally - { - if (ptr != IntPtr.Zero) - Marshal.FreeHGlobal(ptr); - } - - return new MultiMapInfo() - { - Pixels = pixels, - Width = width, - Height = height, - }; - } - - public MultiMapInfo LoadFacet - ( - int facet, - int width, - int height, - int startx, - int starty, - int endx, - int endy - ) - { - if (_file == null || facet < 0 || facet > MapLoader.MAPS_COUNT || facet >= _facets.Length || _facets[facet] == null) - { - return default; - } - - _facets[facet].Seek(0); - - int w = _facets[facet].ReadShort(); - - int h = _facets[facet].ReadShort(); - - if (w < 1 || h < 1) - { - return default; - } - - int startX = startx; - int endX = endx <= 0 ? width : endx; - - int startY = starty; - int endY = endy <= 0 ? height : endy; - - int pwidth = endX - startX; - int pheight = endY - startY; - - var pixels = new uint[pwidth * pheight]; - - for (int y = 0; y < h; y++) - { - int x = 0; - - int colorCount = _facets[facet].ReadInt() / 3; - - for (int i = 0; i < colorCount; i++) - { - int size = _facets[facet].ReadByte(); - - uint color = HuesHelper.Color16To32(_facets[facet].ReadUShort()) | 0xFF_00_00_00; - - for (int j = 0; j < size; j++) - { - if (x >= startX && x < endX && y >= startY && y < endY) - { - pixels[(y - startY) * pwidth + (x - startX)] = color; - } - - x++; - } - } - } - - return new MultiMapInfo() - { - Pixels = pixels, - Width = pwidth, - Height = pheight, - }; - } - } - - public ref struct MultiMapInfo - { - public Span Pixels; - public int Width, Height; - } -} diff --git a/src/ClassicUO.Assets/PNGLoader.cs b/src/ClassicUO.Assets/PNGLoader.cs deleted file mode 100644 index 22eba727e..000000000 --- a/src/ClassicUO.Assets/PNGLoader.cs +++ /dev/null @@ -1,187 +0,0 @@ -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using System; -using System.Collections.Generic; -using System.IO; -using System.Runtime.Remoting.Messaging; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class PNGLoader - { - private const string IMAGES_FOLDER = "ExternalImages", GUMP_EXTERNAL_FOLDER = "gumps", ART_EXTERNAL_FOLDER = "art"; - - private string exePath; - - private uint[] gump_availableIDs; - private Dictionary gump_textureCache = new Dictionary(); - - private uint[] art_availableIDs; - private Dictionary art_textureCache = new Dictionary(); - - public GraphicsDevice GraphicsDevice { set; get; } - - public static PNGLoader _instance; - public static PNGLoader Instance => _instance ?? (_instance = new PNGLoader()); - - public Texture2D GetImageTexture(string fullImagePath) - { - Texture2D texture = null; - - if (GraphicsDevice != null && File.Exists(fullImagePath)) - { - FileStream titleStream = File.OpenRead(fullImagePath); - texture = Texture2D.FromStream(GraphicsDevice, titleStream); - titleStream.Close(); - Color[] buffer = new Color[texture.Width * texture.Height]; - texture.GetData(buffer); - for (int i = 0; i < buffer.Length; i++) - buffer[i] = Color.FromNonPremultiplied(buffer[i].R, buffer[i].G, buffer[i].B, buffer[i].A); - texture.SetData(buffer); - } - - return texture; - } - - public GumpInfo LoadGumpTexture(uint graphic) - { - Texture2D texture; - - if (gump_availableIDs == null) - return new GumpInfo(); - int index = Array.IndexOf(gump_availableIDs, graphic); - if (index == -1) return new GumpInfo(); - - gump_textureCache.TryGetValue(graphic, out texture); - - if (exePath != null && texture == null && GraphicsDevice != null) - { - string fullImagePath = Path.Combine(exePath, IMAGES_FOLDER, GUMP_EXTERNAL_FOLDER, ((int)graphic).ToString() + ".png"); - - if (File.Exists(fullImagePath)) - { - FileStream titleStream = File.OpenRead(fullImagePath); - texture = Texture2D.FromStream(GraphicsDevice, titleStream); - titleStream.Close(); - Color[] buffer = new Color[texture.Width * texture.Height]; - texture.GetData(buffer); - for (int i = 0; i < buffer.Length; i++) - buffer[i] = Color.FromNonPremultiplied(buffer[i].R, buffer[i].G, buffer[i].B, buffer[i].A); - texture.SetData(buffer); - - gump_textureCache.Add(graphic, texture); - } - } - - if(texture == null) - { - return new GumpInfo(); - } - - return new GumpInfo() - { - Pixels = GetPixels(texture), - Width = texture.Width, - Height = texture.Height - }; - } - - public ArtInfo LoadArtTexture(uint graphic) - { - Texture2D texture; - - if (art_availableIDs == null) - return new ArtInfo(); - - int index = Array.IndexOf(art_availableIDs, graphic); - if (index == -1) return new ArtInfo(); - - art_textureCache.TryGetValue(graphic, out texture); - - if (exePath != null && texture == null && GraphicsDevice != null) - { - string fullImagePath = Path.Combine(exePath, IMAGES_FOLDER, ART_EXTERNAL_FOLDER, (graphic -= 0x4000).ToString() + ".png"); - - if (File.Exists(fullImagePath)) - { - FileStream titleStream = File.OpenRead(fullImagePath); - texture = Texture2D.FromStream(GraphicsDevice, titleStream); - titleStream.Close(); - Color[] buffer = new Color[texture.Width * texture.Height]; - texture.GetData(buffer); - for (int i = 0; i < buffer.Length; i++) - buffer[i] = Color.FromNonPremultiplied(buffer[i].R, buffer[i].G, buffer[i].B, buffer[i].A); - texture.SetData(buffer); - - art_textureCache.Add(graphic, texture); - } - } - - return new ArtInfo() - { - Pixels = GetPixels(texture), - Width = texture.Width, - Height = texture.Height, - }; - } - - private uint[] GetPixels(Texture2D texture) - { - if(texture == null) - { - return new uint[0]; - } - Span pixels = texture.Width * texture.Height <= 1024 ? stackalloc uint[1024] : stackalloc uint[texture.Width * texture.Height]; - - Color[] pixelColors = new Color[texture.Width * texture.Height]; - texture.GetData(pixelColors); - - for (int i = 0; i < pixelColors.Length; i++) - { - pixels[i] = pixelColors[i].PackedValue; - } - - return pixels.ToArray(); - } - - public Task Load() - { - return Task.Run - (() => - { - string strExeFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location; - exePath = Path.GetDirectoryName(strExeFilePath); - - string gumpPath = Path.Combine(exePath, IMAGES_FOLDER, GUMP_EXTERNAL_FOLDER); - if (Directory.Exists(gumpPath)) - { - string[] files = Directory.GetFiles(gumpPath, "*.png", SearchOption.TopDirectoryOnly); - gump_availableIDs = new uint[files.Length]; - - for (int i = 0; i < files.Length; i++) - { - string fname = Path.GetFileName(files[i]); - uint.TryParse(fname.Substring(0, fname.Length - 4), out gump_availableIDs[i]); - } - } - - string artPath = Path.Combine(exePath, IMAGES_FOLDER, ART_EXTERNAL_FOLDER); - if (Directory.Exists(artPath)) - { - string[] files = Directory.GetFiles(artPath, "*.png", SearchOption.TopDirectoryOnly); - art_availableIDs = new uint[files.Length]; - - for (int i = 0; i < files.Length; i++) - { - string fname = Path.GetFileName(files[i]); - if(uint.TryParse(fname.Substring(0, fname.Length - 4), out uint gfx)) - { - art_availableIDs[i] = gfx + 0x4000; - } - } - } - }); - } - } -} diff --git a/src/ClassicUO.Assets/ProfessionLoader.cs b/src/ClassicUO.Assets/ProfessionLoader.cs deleted file mode 100644 index d27d3deb9..000000000 --- a/src/ClassicUO.Assets/ProfessionLoader.cs +++ /dev/null @@ -1,434 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class ProfessionInfo - { - public static readonly int[,] _VoidSkills = new int[4, 2] - { - { 0, InitialSkillValue }, { 0, InitialSkillValue }, - { 0, UOFileManager.Version < ClientVersion.CV_70160 ? 0 : InitialSkillValue }, { 0, InitialSkillValue } - }; - public static readonly int[] _VoidStats = new int[3] { 60, RemainStatValue, RemainStatValue }; - public static int InitialSkillValue => UOFileManager.Version >= ClientVersion.CV_70160 ? 30 : 50; - public static int RemainStatValue => UOFileManager.Version >= ClientVersion.CV_70160 ? 15 : 10; - public string Name { get; set; } - public string TrueName { get; set; } - public int Localization { get; set; } - public int Description { get; set; } - public int DescriptionIndex { get; set; } - public ProfessionLoader.PROF_TYPE Type { get; set; } - - public ushort Graphic { get; set; } - - public bool TopLevel { get; set; } - public int[,] SkillDefVal { get; set; } = _VoidSkills; - public int[] StatsVal { get; set; } = _VoidStats; - public List Children { get; set; } - } - - public class ProfessionLoader : UOFileLoader - { - private static ProfessionLoader _instance; - private readonly string[] _Keys = - { - "begin", "name", "truename", "desc", "toplevel", "gump", "type", "children", "skill", - "stat", "str", "int", "dex", "end", "true", "category", "nameid", "descid" - }; - - private ProfessionLoader() - { - } - - public static ProfessionLoader Instance => _instance ?? (_instance = new ProfessionLoader()); - - public Dictionary> Professions { get; } = new Dictionary>(); - - public override Task Load() - { - return Task.Run - ( - () => - { - bool result = false; - - FileInfo file = new FileInfo(UOFileManager.GetUOFilePath("Prof.txt")); - - if (file.Exists) - { - if (file.Length > 0x100000) //1megabyte limit of string file - { - throw new InternalBufferOverflowException($"{file.FullName} exceeds the maximum 1Megabyte allowed size for a string text file, please, check that the file is correct and not corrupted -> {file.Length} file size"); - } - - //what if file doesn't exist? we skip section completely...directly into advanced selection - TextFileParser read = new TextFileParser(File.ReadAllText(file.FullName), new[] { ' ', '\t', ',' }, new[] { '#', ';' }, new[] { '"', '"' }); - - while (!read.IsEOF()) - { - List strings = read.ReadTokens(); - - if (strings.Count > 0) - { - if (strings[0].ToLower() == "begin") - { - result = ParseFilePart(read); - - if (!result) - { - break; - } - } - } - } - } - - Professions[new ProfessionInfo - { - Name = "Advanced", - Localization = 1061176, - Description = 1061226, - Graphic = 5545, - TopLevel = true, - Type = PROF_TYPE.PROFESSION, - DescriptionIndex = -1, - TrueName = "advanced" - }] = null; - - foreach (KeyValuePair> kvp in Professions) - { - kvp.Key.Children = null; - - if (kvp.Value != null) - { - foreach (ProfessionInfo info in kvp.Value) - { - info.Children = null; - } - } - } - } - ); - } - - private int GetKeyCode(string key) - { - key = key.ToLowerInvariant(); - int result = 0; - - for (int i = 0; i < _Keys.Length && result <= 0; i++) - { - if (key == _Keys[i]) - { - result = i + 1; - } - } - - return result; - } - - private bool ParseFilePart(TextFileParser file) - { - List childrens = new List(); - PROF_TYPE type = PROF_TYPE.NO_PROF; - string name = string.Empty; - string trueName = string.Empty; - int nameClilocID = 0; - int descriptionClilocID = 0; - int descriptionIndex = 0; - ushort gump = 0; - bool topLevel = false; - int[,] skillIndex = new int[4, 2] { { 0xFF, 0 }, { 0xFF, 0 }, { 0xFF, 0 }, { 0xFF, 0 } }; - int[] stats = new int[3] { 0, 0, 0 }; - - bool exit = false; - - while (!file.IsEOF() && !exit) - { - List strings = file.ReadTokens(); - - if (strings.Count < 1) - { - continue; - } - - int code = GetKeyCode(strings[0]); - - switch ((PM_CODE) code) - { - case PM_CODE.BEGIN: - case PM_CODE.END: - - { - exit = true; - - break; - } - - case PM_CODE.NAME: - - { - name = strings[1]; - - break; - } - - case PM_CODE.TRUENAME: - - { - trueName = strings[1]; - - break; - } - - case PM_CODE.DESC: - - { - int.TryParse(strings[1], out descriptionIndex); - - break; - } - - case PM_CODE.TOPLEVEL: - - { - topLevel = GetKeyCode(strings[1]) == (int) PM_CODE.TRUE; - - break; - } - - case PM_CODE.GUMP: - - { - ushort.TryParse(strings[1], out gump); - - break; - } - - case PM_CODE.TYPE: - - { - if (GetKeyCode(strings[1]) == (int) PM_CODE.CATEGORY) - { - type = PROF_TYPE.CATEGORY; - } - else - { - type = PROF_TYPE.PROFESSION; - } - - break; - } - - case PM_CODE.CHILDREN: - - { - for (int j = 1; j < strings.Count; j++) - { - childrens.Add(strings[j]); - } - - break; - } - - case PM_CODE.SKILL: - - { - if (strings.Count > 2) - { - int idx = 0; - - for (int i = 0, len = skillIndex.GetLength(0); i < len; i++) - { - if (skillIndex[i, 0] == 0xFF) - { - idx = i; - - break; - } - } - - for (int j = 0; j < SkillsLoader.Instance.SkillsCount; j++) - { - SkillEntry skill = SkillsLoader.Instance.Skills[j]; - - if (strings[1] == skill.Name || ((SkillEntry.HardCodedName) skill.Index).ToString().ToLower() == strings[1].ToLower()) - { - skillIndex[idx, 0] = j; - int.TryParse(strings[2], out skillIndex[idx, 1]); - - break; - } - } - } - - break; - } - - case PM_CODE.STAT: - - { - if (strings.Count > 2) - { - code = GetKeyCode(strings[1]); - int.TryParse(strings[2], out int val); - - if ((PM_CODE) code == PM_CODE.STR) - { - stats[0] = val; - } - else if ((PM_CODE) code == PM_CODE.INT) - { - stats[1] = val; - } - else if ((PM_CODE) code == PM_CODE.DEX) - { - stats[2] = val; - } - } - - break; - } - - case PM_CODE.NAME_CLILOC_ID: - - { - int.TryParse(strings[1], out nameClilocID); - name = ClilocLoader.Instance.GetString(nameClilocID, true, name); - - break; - } - - case PM_CODE.DESCRIPTION_CLILOC_ID: - - { - int.TryParse(strings[1], out descriptionClilocID); - - break; - } - } - } - - ProfessionInfo info = null; - List list = null; - - if (type == PROF_TYPE.CATEGORY) - { - info = new ProfessionInfo - { - Children = childrens - }; - - list = new List(); - } - else if (type == PROF_TYPE.PROFESSION) - { - info = new ProfessionInfo - { - StatsVal = stats, - SkillDefVal = skillIndex - }; - } - - bool result = type != PROF_TYPE.NO_PROF; - - if (info != null) - { - info.Localization = nameClilocID; - info.Description = descriptionClilocID; - info.Name = name; - info.TrueName = trueName; - info.DescriptionIndex = descriptionIndex; - info.TopLevel = topLevel; - info.Graphic = gump; - info.Type = type; - - if (topLevel) - { - Professions[info] = list; - } - else - { - foreach (KeyValuePair> kvp in Professions) - { - if (kvp.Key.Children != null && kvp.Value != null && kvp.Key.Children.Contains(trueName)) - { - Professions[kvp.Key].Add(info); - - result = true; - - break; - } - } - } - } - - return result; - } - - public enum PROF_TYPE - { - NO_PROF = 0, - CATEGORY, - PROFESSION - } - - private enum PM_CODE - { - BEGIN = 1, - NAME, - TRUENAME, - DESC, - TOPLEVEL, - GUMP, - TYPE, - CHILDREN, - SKILL, - STAT, - STR, - INT, - DEX, - END, - TRUE, - CATEGORY, - NAME_CLILOC_ID, - DESCRIPTION_CLILOC_ID - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Assets/Roboto-Regular.ttf b/src/ClassicUO.Assets/Roboto-Regular.ttf deleted file mode 100644 index 3033308a6..000000000 Binary files a/src/ClassicUO.Assets/Roboto-Regular.ttf and /dev/null differ diff --git a/src/ClassicUO.Assets/SkillsLoader.cs b/src/ClassicUO.Assets/SkillsLoader.cs deleted file mode 100644 index 563182f36..000000000 --- a/src/ClassicUO.Assets/SkillsLoader.cs +++ /dev/null @@ -1,190 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class SkillsLoader : UOFileLoader - { - private static SkillsLoader _instance; - private UOFileMul _file; - - private SkillsLoader() - { - } - - public static SkillsLoader Instance => _instance ?? (_instance = new SkillsLoader()); - - public int SkillsCount => Skills.Count; - public readonly List Skills = new List(); - public readonly List SortedSkills = new List(); - - public override unsafe Task Load() - { - return Task.Run - ( - () => - { - if (SkillsCount > 0) - { - return; - } - - string path = UOFileManager.GetUOFilePath("skills.mul"); - string pathidx = UOFileManager.GetUOFilePath("Skills.idx"); - - FileSystemHelper.EnsureFileExists(path); - FileSystemHelper.EnsureFileExists(pathidx); - - _file = new UOFileMul(path, pathidx, 0, 16); - _file.FillEntries(ref Entries); - - for (int i = 0, count = 0; i < Entries.Length; i++) - { - ref UOFileIndex entry = ref GetValidRefEntry(i); - - if (entry.Length > 0) - { - _file.SetData(entry.Address, entry.FileSize); - _file.Seek(entry.Offset); - - bool hasAction = _file.ReadBool(); - string name = Encoding.UTF8.GetString((byte*)_file.PositionAddress, entry.Length - 1).TrimEnd('\0'); - - Skills.Add(new SkillEntry(count++, name, hasAction)); - } - } - - SortedSkills.AddRange(Skills); - SortedSkills.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.InvariantCulture)); - } - ); - } - - public int GetSortedIndex(int index) - { - if (index < SkillsCount) - { - return SortedSkills[index].Index; - } - - return -1; - } - } - - public class SkillEntry - { - public SkillEntry(int index, string name, bool hasAction) - { - Index = index; - Name = name; - HasAction = hasAction; - } - - public bool HasAction; - public readonly int Index; - public string Name; - - public override string ToString() - { - return Name; - } - - public enum HardCodedName - { - Alchemy, - Anatomy, - AnimalLore, - ItemID, // T2A - ArmsLore, - Parrying, - Begging, - Blacksmith, - Bowcraft, - Peacemaking, - Camping, - Carpentry, - Cartography, - Cooking, - DetectHidden, - Enticement, - EvaluateIntelligence, - Healing, - Fishing, - ForensicEvaluation, - Herding, - Hiding, - Provocation, - Inscription, - Lockpicking, - Magery, - ResistingSpells, - Tactics, - Snooping, - Musicanship, - Poisoning, - Archery, - SpiritSpeak, - Stealing, - Tailoring, - AnimalTaming, - TasteIdentification, - Tinkering, - Tracking, - Veterinary, - Swordsmanship, - MaceFighting, - Fencing, - Wrestling, - Lumberjacking, - Mining, - Meditation, - Stealth, - Disarm, - Necromancy, - Focus, - Chivalry, - Bushido, - Ninjitsu, - Spellweaving, - Mysticism, - Imbuing, - Throwing - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Assets/SoundOverrideLoader.cs b/src/ClassicUO.Assets/SoundOverrideLoader.cs deleted file mode 100644 index 0d019bb8c..000000000 --- a/src/ClassicUO.Assets/SoundOverrideLoader.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - internal class SoundOverrideLoader - { - public static SoundOverrideLoader Instance { get; private set; } = new SoundOverrideLoader(); - - private const string SOUND_OVERRIDE_FOLDER = "SoundOverrides"; - private string exePath; - private Dictionary> soundCache = new Dictionary>(); - private bool loaded = false; - - private SoundOverrideLoader() - { - string strExeFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location; - exePath = Path.GetDirectoryName(strExeFilePath); - - Task.Factory.StartNew(() => - { - if (Directory.Exists(Path.Combine(exePath, SOUND_OVERRIDE_FOLDER))) - { - string[] files = Directory.GetFiles(Path.Combine(exePath, SOUND_OVERRIDE_FOLDER), "*.mp3", SearchOption.TopDirectoryOnly); - - for (int i = 0; i < files.Length; i++) - { - var fname = Path.GetFileName(files[i]); - if (int.TryParse(fname.Substring(0, fname.Length - 4), out int fID)) - { - soundCache.Add(fID, new Tuple(fname, File.ReadAllBytes(files[i]))); - } - } - - loaded = true; - } - }); - } - - public bool TryGetSoundOverride(int id, out byte[] data, out string name) - { - if (loaded) - { - if (soundCache.ContainsKey(id)) - { - data = soundCache[id].Item2; - name = soundCache[id].Item1; - return true; - } - } - name = null; - data = null; - return false; - } - } -} diff --git a/src/ClassicUO.Assets/SoundsLoader.cs b/src/ClassicUO.Assets/SoundsLoader.cs deleted file mode 100644 index a712fd4c2..000000000 --- a/src/ClassicUO.Assets/SoundsLoader.cs +++ /dev/null @@ -1,378 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class SoundsLoader : UOFileLoader - { - private static readonly char[] _configFileDelimiters = { ' ', ',', '\t' }; - private static readonly Dictionary> _musicData = new Dictionary>(); - - private static SoundsLoader _instance; - - public const int MAX_SOUND_DATA_INDEX_COUNT = 0xFFFF; - - private UOFile _file; - - private SoundsLoader() - { - } - - public static SoundsLoader Instance => _instance ?? (_instance = new SoundsLoader()); - - public override Task Load() - { - return Task.Run - ( - () => - { - string path = UOFileManager.GetUOFilePath("soundLegacyMUL.uop"); - - if (UOFileManager.IsUOPInstallation && File.Exists(path)) - { - _file = new UOFileUop(path, "build/soundlegacymul/{0:D8}.dat"); - Entries = new UOFileIndex[Math.Max(((UOFileUop) _file).TotalEntriesCount, MAX_SOUND_DATA_INDEX_COUNT)]; - } - else - { - path = UOFileManager.GetUOFilePath("sound.mul"); - string idxpath = UOFileManager.GetUOFilePath("soundidx.mul"); - - if (File.Exists(path) && File.Exists(idxpath)) - { - _file = new UOFileMul(path, idxpath, MAX_SOUND_DATA_INDEX_COUNT); - } - else - { - throw new FileNotFoundException("no sounds found"); - } - } - - _file.FillEntries(ref Entries); - - string def = UOFileManager.GetUOFilePath("Sound.def"); - - if (File.Exists(def)) - { - using (DefReader reader = new DefReader(def)) - { - while (reader.Next()) - { - int index = reader.ReadInt(); - - if (index < 0 || index >= MAX_SOUND_DATA_INDEX_COUNT || index >= _file.Length || Entries[index].Length != 0) - { - continue; - } - - int[] group = reader.ReadGroup(); - - if (group == null) - { - continue; - } - - for (int i = 0; i < group.Length; i++) - { - int checkIndex = group[i]; - - if (checkIndex < -1 || checkIndex >= MAX_SOUND_DATA_INDEX_COUNT) - { - continue; - } - - ref UOFileIndex ind = ref Entries[index]; - - if (checkIndex == -1) - { - ind = default; - } - else - { - ref readonly UOFileIndex outInd = ref Entries[checkIndex]; - - if (outInd.Length == 0) - { - continue; - } - - Entries[index] = Entries[checkIndex]; - } - } - } - } - } - - path = UOFileManager.GetUOFilePath(UOFileManager.Version >= ClientVersion.CV_4011C ? @"Music/Digital/Config.txt" : @"Music/Config.txt"); - - if (File.Exists(path)) - { - using (StreamReader reader = new StreamReader(path)) - { - string line; - - while ((line = reader.ReadLine()) != null) - { - if (TryParseConfigLine(line, out Tuple songData)) - { - _musicData[songData.Item1] = new Tuple(songData.Item2, songData.Item3); - } - } - } - } - else - { - _musicData.Add(0, new Tuple("oldult01", true)); - _musicData.Add(1, new Tuple("create1", false)); - _musicData.Add(2, new Tuple("dragflit", false)); - _musicData.Add(3, new Tuple("oldult02", true)); - _musicData.Add(4, new Tuple("oldult03", true)); - _musicData.Add(5, new Tuple("oldult04", true)); - _musicData.Add(6, new Tuple("oldult05", true)); - _musicData.Add(7, new Tuple("oldult06", true)); - _musicData.Add(8, new Tuple("stones2", true)); - _musicData.Add(9, new Tuple("britain1", true)); - _musicData.Add(10, new Tuple("britain2", true)); - _musicData.Add(11, new Tuple("bucsden", true)); - _musicData.Add(12, new Tuple("jhelom", false)); - _musicData.Add(13, new Tuple("lbcastle", false)); - _musicData.Add(14, new Tuple("linelle", false)); - _musicData.Add(15, new Tuple("magincia", true)); - _musicData.Add(16, new Tuple("minoc", true)); - _musicData.Add(17, new Tuple("ocllo", true)); - _musicData.Add(18, new Tuple("samlethe", false)); - _musicData.Add(19, new Tuple("serpents", true)); - _musicData.Add(20, new Tuple("skarabra", true)); - _musicData.Add(21, new Tuple("trinsic", true)); - _musicData.Add(22, new Tuple("vesper", true)); - _musicData.Add(23, new Tuple("wind", true)); - _musicData.Add(24, new Tuple("yew", true)); - _musicData.Add(25, new Tuple("cave01", false)); - _musicData.Add(26, new Tuple("dungeon9", false)); - _musicData.Add(27, new Tuple("forest_a", false)); - _musicData.Add(28, new Tuple("intown01", false)); - _musicData.Add(29, new Tuple("jungle_a", false)); - _musicData.Add(30, new Tuple("mountn_a", false)); - _musicData.Add(31, new Tuple("plains_a", false)); - _musicData.Add(32, new Tuple("sailing", false)); - _musicData.Add(33, new Tuple("swamp_a", false)); - _musicData.Add(34, new Tuple("tavern01", false)); - _musicData.Add(35, new Tuple("tavern02", false)); - _musicData.Add(36, new Tuple("tavern03", false)); - _musicData.Add(37, new Tuple("tavern04", false)); - _musicData.Add(38, new Tuple("combat1", false)); - _musicData.Add(39, new Tuple("combat2", false)); - _musicData.Add(40, new Tuple("combat3", false)); - _musicData.Add(41, new Tuple("approach", false)); - _musicData.Add(42, new Tuple("death", false)); - _musicData.Add(43, new Tuple("victory", false)); - _musicData.Add(44, new Tuple("btcastle", false)); - _musicData.Add(45, new Tuple("nujelm", true)); - _musicData.Add(46, new Tuple("dungeon2", false)); - _musicData.Add(47, new Tuple("cove", true)); - _musicData.Add(48, new Tuple("moonglow", true)); - _musicData.Add(49, new Tuple("zento", true)); - _musicData.Add(50, new Tuple("tokunodungeon", true)); - _musicData.Add(51, new Tuple("Taiko", true)); - _musicData.Add(52, new Tuple("dreadhornarea", true)); - _musicData.Add(53, new Tuple("elfcity", true)); - _musicData.Add(54, new Tuple("grizzledungeon", true)); - _musicData.Add(55, new Tuple("melisandeslair", true)); - _musicData.Add(56, new Tuple("paroxysmuslair", true)); - _musicData.Add(57, new Tuple("gwennoconversation", true)); - _musicData.Add(58, new Tuple("goodendgame", true)); - _musicData.Add(59, new Tuple("goodvsevil", true)); - _musicData.Add(60, new Tuple("greatearthserpents", true)); - _musicData.Add(61, new Tuple("humanoids_u9", true)); - _musicData.Add(62, new Tuple("minocnegative", true)); - _musicData.Add(63, new Tuple("paws", true)); - _musicData.Add(64, new Tuple("selimsbar", true)); - _musicData.Add(65, new Tuple("serpentislecombat_u7", true)); - _musicData.Add(66, new Tuple("valoriaships", true)); - } - } - ); - } - - public unsafe bool TryGetSound(int sound, out byte[] data, out string name) - { - data = null; - name = null; - - if (sound < 0) - { - return false; - } - - if (SoundOverrideLoader.Instance.TryGetSoundOverride(sound, out data, out name)) - { - return true; - } - - ref UOFileIndex entry = ref GetValidRefEntry(sound); - - _file.SetData(entry.Address, entry.FileSize); - _file.Seek(entry.Offset); - - long offset = _file.Position; - - if (offset < 0 || entry.Length <= 0) - { - return false; - } - - _file.Seek(offset); - - const int STRING_BUFFER_SIZE = 40; - - for (int i = 0; i < STRING_BUFFER_SIZE; ++i) - { - if (_file.ReadByte() == 0) - { - name = Encoding.UTF8.GetString((byte*)(_file.StartAddress.ToInt64() + offset), i); - - break; - } - } - - _file.Seek(offset + STRING_BUFFER_SIZE); - - data = new byte[entry.Length - STRING_BUFFER_SIZE]; - - for (int i = 0; i < data.Length; ++i) - { - data[i] = _file.ReadByte(); - } - - return true; - } - - /// - /// Attempts to parse a line from UO's music Config.txt. - /// - /// A line from the file. - /// If successful, contains a tuple with these fields: int songIndex, string songName, bool doesLoop - /// true if line could be parsed, false otherwise. - private bool TryParseConfigLine(string line, out Tuple songData) - { - songData = null; - - string[] splits = line.Split(_configFileDelimiters); - - if (splits.Length < 2 || splits.Length > 3) - { - return false; - } - - int index = int.Parse(splits[0]); - - // check if name exists as file, ignoring case since UO isn't consistent with file case (necessary for *nix) - // also, not every filename in Config.txt has a file extension, so let's strip it out just in case. - string name = GetTrueFileName(Path.GetFileNameWithoutExtension(splits[1])); - - bool doesLoop = splits.Length == 3 && splits[2] == "loop"; - - songData = new Tuple(index, name, doesLoop); - - return true; - } - - /// - /// Returns true filename from name, ignoring case since UO isn't consistent with file case (necessary for *nix) - /// - /// The filename from the music Config.txt - /// a string with the true case sensitive filename - private static string GetTrueFileName(string name) - { - // don't worry about subdirectories, we'll recursively search them all - string dir = UOFileManager.BasePath + $"/Music"; - - // Enumerate all files in the directory, using the file name as a pattern - // This will list all case variants of the filename even on file systems that - // are case sensitive. - Regex pattern = new Regex($"^{name}.mp3", RegexOptions.IgnoreCase); - //string[] fileList = Directory.GetFiles(dir, "*.mp3", SearchOption.AllDirectories).Where(path => pattern.IsMatch(Path.GetFileName(path))).ToArray(); - string[] fileList = Directory.GetFiles(dir, "*.mp3", SearchOption.AllDirectories); - fileList = Array.FindAll(fileList, path => pattern.IsMatch(Path.GetFileName(path))); - - if (fileList != null && fileList.Length != 0) - { - if (fileList.Length > 1) - { - // More than one file with the same name but different case spelling found - Log.Warn($"Ambiguous File reference for {name}. More than one file found with different spellings."); - } - - Log.Debug($"Loading music:\t\t{fileList[0]}"); - - return Path.GetFileName(fileList[0]); - } - - // If we've made it this far, there is no file with that name, regardless of case spelling - // return name and GetMusic will fail gracefully (play nothing) - Log.Warn($"No File found known as {name}"); - return name; - } - - public bool TryGetMusicData(int index, out string name, out bool doesLoop) - { - name = null; - doesLoop = false; - - if (_musicData.ContainsKey(index)) - { - name = _musicData[index].Item1; - - doesLoop = _musicData[index].Item2; - - return true; - } - - return false; - } - - public override void ClearResources() - { - _musicData.Clear(); - } - } -} diff --git a/src/ClassicUO.Assets/SpeechesLoader.cs b/src/ClassicUO.Assets/SpeechesLoader.cs deleted file mode 100644 index be2412c5a..000000000 --- a/src/ClassicUO.Assets/SpeechesLoader.cs +++ /dev/null @@ -1,202 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class SpeechesLoader : UOFileLoader - { - private static SpeechesLoader _instance; - private SpeechEntry[] _speech; - - private SpeechesLoader() - { - } - - public static SpeechesLoader Instance => _instance ?? (_instance = new SpeechesLoader()); - - public override unsafe Task Load() - { - return Task.Run - ( - () => - { - string path = UOFileManager.GetUOFilePath("speech.mul"); - - if (!File.Exists(path)) - { - _speech = Array.Empty(); - - return; - } - - UOFileMul file = new UOFileMul(path); - List entries = new List(); - - while (file.Position < file.Length) - { - int id = file.ReadUShortReversed(); - int length = file.ReadUShortReversed(); - - if (length > 0) - { - entries.Add(new SpeechEntry(id, string.Intern(Encoding.UTF8.GetString((byte*) file.PositionAddress, length)))); - - file.Skip(length); - } - } - - _speech = entries.ToArray(); - file.Dispose(); - } - ); - } - - public bool IsMatch(string input, in SpeechEntry entry) - { - string[] split = entry.Keywords; - //string[] words = input.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries); - - for (int i = 0; i < split.Length; i++) - { - if (split[i].Length > input.Length || split[i].Length == 0) - { - continue; - } - - if (!entry.CheckStart) - { - if (input.IndexOf(split[i], 0, split[i].Length, StringComparison.InvariantCultureIgnoreCase) == -1) - { - continue; - } - } - - if (!entry.CheckEnd) - { - if (input.IndexOf(split[i], input.Length - split[i].Length, StringComparison.InvariantCultureIgnoreCase) == -1) - { - continue; - } - } - - int idx = input.IndexOf(split[i], StringComparison.InvariantCultureIgnoreCase); - while (idx >= 0) - { - // "bank" or " bank" or "bank " or " bank " or "!bank" or "bank!" - if ((idx - 1 < 0 || char.IsWhiteSpace(input[idx - 1]) || !char.IsLetter(input[idx - 1])) && - (idx + split[i].Length >= input.Length || char.IsWhiteSpace(input[idx + split[i].Length]) || !char.IsLetter(input[idx + split[i].Length]) )) - { - return true; - } - - - - idx = input.IndexOf(split[i], idx + 1, StringComparison.InvariantCultureIgnoreCase); - } - } - - return false; - } - - public List GetKeywords(string text) - { - List list = new List(); - - if (UOFileManager.Version < ClientVersion.CV_305D) - { - return list; - } - - text = text.TrimStart(' ').TrimEnd(' '); - - for (int i = 0; i < _speech.Length; i++) - { - SpeechEntry entry = _speech[i]; - - if (IsMatch(text, in entry)) - { - list.Add(entry); - } - } - - list.Sort(); - - return list; - } - } - - public readonly struct SpeechEntry : IComparable - { - public SpeechEntry(int id, string keyword) - { - KeywordID = (short) id; - - Keywords = keyword.Split - ( - new[] - { - '*' - }, - StringSplitOptions.RemoveEmptyEntries - ); - - CheckStart = keyword.Length > 0 && keyword[0] == '*'; - CheckEnd = keyword.Length > 0 && keyword[keyword.Length - 1] == '*'; - } - - public string[] Keywords { get; } - - public short KeywordID { get; } - - public bool CheckStart { get; } - - public bool CheckEnd { get; } - - public int CompareTo(SpeechEntry obj) - { - if (KeywordID < obj.KeywordID) - { - return -1; - } - - return KeywordID > obj.KeywordID ? 1 : 0; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Assets/TexmapsLoader.cs b/src/ClassicUO.Assets/TexmapsLoader.cs deleted file mode 100644 index 3f769705c..000000000 --- a/src/ClassicUO.Assets/TexmapsLoader.cs +++ /dev/null @@ -1,144 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using System; -using System.IO; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class TexmapsLoader : UOFileLoader - { - private static TexmapsLoader _instance; - private UOFile _file; - - public const int MAX_LAND_TEXTURES_DATA_INDEX_COUNT = 0x4000; - - private TexmapsLoader(int count) { } - - public static TexmapsLoader Instance => - _instance ?? (_instance = new TexmapsLoader(MAX_LAND_TEXTURES_DATA_INDEX_COUNT)); - - public override Task Load() - { - return Task.Run(() => - { - string path = UOFileManager.GetUOFilePath("texmaps.mul"); - string pathidx = UOFileManager.GetUOFilePath("texidx.mul"); - - FileSystemHelper.EnsureFileExists(path); - FileSystemHelper.EnsureFileExists(pathidx); - - _file = new UOFileMul(path, pathidx, MAX_LAND_TEXTURES_DATA_INDEX_COUNT, 10); - _file.FillEntries(ref Entries); - string pathdef = UOFileManager.GetUOFilePath("TexTerr.def"); - - if (File.Exists(pathdef)) - { - using (DefReader defReader = new DefReader(pathdef)) - { - while (defReader.Next()) - { - int index = defReader.ReadInt(); - - if (index < 0 || index >= Entries.Length) - { - continue; - } - - int[] group = defReader.ReadGroup(); - - if (group == null) - { - continue; - } - - for (int i = 0; i < group.Length; i++) - { - int checkindex = group[i]; - - if (checkindex < 0 || checkindex >= Entries.Length) - { - continue; - } - - Entries[index] = Entries[checkindex]; - } - } - } - } - }); - } - - public TexmapInfo GetTexmap(uint idx) - { - ref UOFileIndex entry = ref GetValidRefEntry((int)idx); - - if (entry.Length <= 0) - { - return default; - } - - _file.SetData(entry.Address, entry.FileSize); - _file.Seek(entry.Offset); - - var size = entry.Length == 0x2000 ? 64 : 128; - var data = new uint[size * size]; - - for (int i = 0; i < size; ++i) - { - int pos = i * size; - - for (int j = 0; j < size; ++j) - { - data[pos + j] = HuesHelper.Color16To32(_file.ReadUShort()) | 0xFF_00_00_00; - } - } - - return new TexmapInfo() - { - Pixels = data, - Width = size, - Height = size - }; - } - } - - public ref struct TexmapInfo - { - public Span Pixels; - public int Width; - public int Height; - } -} diff --git a/src/ClassicUO.Assets/TileDataLoader.cs b/src/ClassicUO.Assets/TileDataLoader.cs deleted file mode 100644 index 106cd6b00..000000000 --- a/src/ClassicUO.Assets/TileDataLoader.cs +++ /dev/null @@ -1,627 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using System; -using System.Runtime.InteropServices; -using System.Text; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class TileDataLoader : UOFileLoader - { - private static TileDataLoader _instance; - - private static StaticTiles[] _staticData; - private static LandTiles[] _landData; - - private TileDataLoader() - { - } - - public static TileDataLoader Instance => _instance ?? (_instance = new TileDataLoader()); - - public ref LandTiles[] LandData => ref _landData; - public ref StaticTiles[] StaticData => ref _staticData; - - public override unsafe Task Load() - { - return Task.Run - ( - () => - { - string path = UOFileManager.GetUOFilePath("tiledata.mul"); - - FileSystemHelper.EnsureFileExists(path); - - UOFileMul tileData = new UOFileMul(path); - - - bool isold = UOFileManager.Version < ClientVersion.CV_7090; - const int LAND_SIZE = 512; - - int land_group = isold ? Marshal.SizeOf() : Marshal.SizeOf(); - int static_group = isold ? Marshal.SizeOf() : Marshal.SizeOf(); - int staticscount = (int) ((tileData.Length - LAND_SIZE * land_group) / static_group); - - if (staticscount > 2048) - { - staticscount = 2048; - } - - tileData.Seek(0); - - _landData = new LandTiles[ArtLoader.MAX_LAND_DATA_INDEX_COUNT]; - _staticData = new StaticTiles[staticscount * 32]; - - byte* bufferString = stackalloc byte[20]; - - for (int i = 0; i < 512; i++) - { - tileData.Skip(4); - - for (int j = 0; j < 32; j++) - { - if (tileData.Position + (isold ? 4 : 8) + 2 + 20 > tileData.Length) - { - goto END; - } - - int idx = i * 32 + j; - ulong flags = isold ? tileData.ReadUInt() : tileData.ReadULong(); - ushort textId = tileData.ReadUShort(); - - for (int k = 0; k < 20; ++k) - { - bufferString[k] = tileData.ReadByte(); - } - - string name = string.Intern(Encoding.UTF8.GetString(bufferString, 20).TrimEnd('\0')); - - LandData[idx] = new LandTiles(flags, textId, name); - } - } - - END: - - for (int i = 0; i < staticscount; i++) - { - if (tileData.Position >= tileData.Length) - { - break; - } - - tileData.Skip(4); - - for (int j = 0; j < 32; j++) - { - if (tileData.Position + (isold ? 4 : 8) + 13 + 20 > tileData.Length) - { - goto END_2; - } - - int idx = i * 32 + j; - - ulong flags = isold ? tileData.ReadUInt() : tileData.ReadULong(); - byte weight = tileData.ReadByte(); - byte layer = tileData.ReadByte(); - int count = tileData.ReadInt(); - ushort animId = tileData.ReadUShort(); - ushort hue = tileData.ReadUShort(); - ushort lightIndex = tileData.ReadUShort(); - byte height = tileData.ReadByte(); - - for (int k = 0; k < 20; ++k) - { - bufferString[k] = tileData.ReadByte(); - } - - string name = string.Intern(Encoding.UTF8.GetString(bufferString, 20).TrimEnd('\0')); - - StaticData[idx] = new StaticTiles - ( - flags, - weight, - layer, - count, - animId, - hue, - lightIndex, - height, - name - ); - } - } - - - //path = Path.Combine(FileManager.UoFolderPath, "tileart.uop"); - - //if (File.Exists(path)) - //{ - // UOFileUop uop = new UOFileUop(path, ".bin"); - // DataReader reader = new DataReader(); - // for (int i = 0; i < uop.Entries.Length; i++) - // { - // long offset = uop.Entries[i].Offset; - // int csize = uop.Entries[i].Length; - // int dsize = uop.Entries[i].DecompressedLength; - - // if (offset == 0) - // continue; - - // uop.Seek(offset); - // byte[] cdata = uop.ReadArray(csize); - // byte[] ddata = new byte[dsize]; - - // ZLib.Decompress(cdata, 0, ddata, dsize); - - // reader.SetData(ddata, dsize); - - // ushort version = reader.ReadUShort(); - // uint stringDicOffset = reader.ReadUInt(); - // uint tileID = reader.ReadUInt(); - - // reader.Skip(1 + // bool unk - // 1 + // unk - // 4 + // float unk - // 4 + // float unk - // 4 + // fixed zero ? - // 4 + // old id ? - // 4 + // unk - // 4 + // unk - // 1 + // unk - // 4 + // 3F800000 - // 4 + // unk - // 4 + // float light - // 4 + // float light - // 4 // unk - // ); - - // ulong flags = reader.ReadULong(); - // ulong flags2 = reader.ReadULong(); - - // reader.Skip(4); // unk - - // reader.Skip(24); // EC IMAGE OFFSET - // byte[] imageOffset = reader.ReadArray(24); // 2D IMAGE OFFSET - - - // if (tileID + 0x4000 == 0xa28d) - // { - // TileFlag f = (TileFlag) flags; - - // } - - // int count = reader.ReadByte(); - // for (int j = 0; j < count; j++) - // { - // byte prop = reader.ReadByte(); - // uint value = reader.ReadUInt(); - // } - - // count = reader.ReadByte(); - // for (int j = 0; j < count; j++) - // { - // byte prop = reader.ReadByte(); - // uint value = reader.ReadUInt(); - // } - - // count = reader.ReadInt(); // Gold Silver - // for (int j = 0; j < count; j++) - // { - // uint amount = reader.ReadUInt(); - // uint id = reader.ReadUInt(); - // } - - // count = reader.ReadInt(); - - // for (int j = 0; j < count; j++) - // { - // byte val = reader.ReadByte(); - - // if (val != 0) - // { - // if (val == 1) - // { - // byte unk = reader.ReadByte(); - // uint unk1 = reader.ReadUInt(); - // } - - // } - // else - // { - // int subCount = reader.ReadInt(); - - // for (int k = 0; k < subCount; k++) - // { - // uint unk = reader.ReadUInt(); - // uint unk1 = reader.ReadUInt(); - // } - // } - // } - - // count = reader.ReadByte(); - - // if (count != 0) - // { - // uint unk = reader.ReadUInt(); - // uint unk1 = reader.ReadUInt(); - // uint unk2 = reader.ReadUInt(); - // uint unk3 = reader.ReadUInt(); - // } - - - // if (StaticData[tileID].AnimID == 0) - // { - // //StaticData[tileID] = new StaticTiles(flags, 0, 0, 0, ); - // } - - - // } - - // uop.Dispose(); - // reader.ReleaseData(); - //} - - - - END_2: - tileData.Dispose(); - } - ); - } - } - - public struct LandTiles - { - public LandTiles(ulong flags, ushort textId, string name) - { - Flags = (TileFlag) flags; - TexID = textId; - Name = name; - } - - public TileFlag Flags; - public ushort TexID; - public string Name; - - public bool IsWet => (Flags & TileFlag.Wet) != 0; - public bool IsImpassable => (Flags & TileFlag.Impassable) != 0; - public bool IsNoDiagonal => (Flags & TileFlag.NoDiagonal) != 0; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct LandGroup - { - public uint Unknown; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] - public LandTiles[] Tiles; - } - - public struct StaticTiles - { - public StaticTiles - ( - ulong flags, - byte weight, - byte layer, - int count, - ushort animId, - ushort hue, - ushort lightIndex, - byte height, - string name - ) - { - Flags = (TileFlag) flags; - Weight = weight; - Layer = layer; - Count = count; - AnimID = animId; - Hue = hue; - LightIndex = lightIndex; - Height = height; - Name = name; - } - - public TileFlag Flags; - public byte Weight; - public byte Layer; - public int Count; - public ushort AnimID; - public ushort Hue; - public ushort LightIndex; - public byte Height; - public string Name; - - public bool IsAnimated => (Flags & TileFlag.Animation) != 0; - public bool IsBridge => (Flags & TileFlag.Bridge) != 0; - public bool IsImpassable => (Flags & TileFlag.Impassable) != 0; - public bool IsSurface => (Flags & TileFlag.Surface) != 0; - public bool IsWearable => (Flags & TileFlag.Wearable) != 0; - public bool IsInternal => (Flags & TileFlag.Internal) != 0; - public bool IsBackground => (Flags & TileFlag.Background) != 0; - public bool IsNoDiagonal => (Flags & TileFlag.NoDiagonal) != 0; - public bool IsWet => (Flags & TileFlag.Wet) != 0; - public bool IsFoliage => (Flags & TileFlag.Foliage) != 0; - public bool IsRoof => (Flags & TileFlag.Roof) != 0; - public bool IsTranslucent => (Flags & TileFlag.Translucent) != 0; - public bool IsPartialHue => (Flags & TileFlag.PartialHue) != 0; - public bool IsStackable => (Flags & TileFlag.Generic) != 0; - public bool IsTransparent => (Flags & TileFlag.Transparent) != 0; - public bool IsContainer => (Flags & TileFlag.Container) != 0; - public bool IsDoor => (Flags & TileFlag.Door) != 0; - public bool IsWall => (Flags & TileFlag.Wall) != 0; - public bool IsLight => (Flags & TileFlag.LightSource) != 0; - public bool IsNoShoot => (Flags & TileFlag.NoShoot) != 0; - public bool IsWeapon => (Flags & TileFlag.Weapon) != 0; - public bool IsMultiMovable => (Flags & TileFlag.MultiMovable) != 0; - public bool IsWindow => (Flags & TileFlag.Window) != 0; - } - - // old - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct LandGroupOld - { - public uint Unknown; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] - public LandTilesOld[] Tiles; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct LandTilesOld - { - public uint Flags; - public ushort TexID; - [MarshalAs(UnmanagedType.LPStr, SizeConst = 20)] - public string Name; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct StaticGroupOld - { - public uint Unk; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] - public StaticTilesOld[] Tiles; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct StaticTilesOld - { - public uint Flags; - public byte Weight; - public byte Layer; - public int Count; - public ushort AnimID; - public ushort Hue; - public ushort LightIndex; - public byte Height; - [MarshalAs(UnmanagedType.LPStr, SizeConst = 20)] - public string Name; - } - - // new - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct LandGroupNew - { - public uint Unknown; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] - public LandTilesNew[] Tiles; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct LandTilesNew - { - public TileFlag Flags; - public ushort TexID; - [MarshalAs(UnmanagedType.LPStr, SizeConst = 20)] - public string Name; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct StaticGroupNew - { - public uint Unk; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] - public StaticTilesNew[] Tiles; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct StaticTilesNew - { - public TileFlag Flags; - public byte Weight; - public byte Layer; - public int Count; - public ushort AnimID; - public ushort Hue; - public ushort LightIndex; - public byte Height; - [MarshalAs(UnmanagedType.LPStr, SizeConst = 20)] - public string Name; - } - - [Flags] - public enum TileFlag : ulong - { - /// - /// Nothing is flagged. - /// - None = 0x00000000, - /// - /// Not yet documented. - /// - Background = 0x00000001, - /// - /// Not yet documented. - /// - Weapon = 0x00000002, - /// - /// Not yet documented. - /// - Transparent = 0x00000004, - /// - /// The tile is rendered with partial alpha-transparency. - /// - Translucent = 0x00000008, - /// - /// The tile is a wall. - /// - Wall = 0x00000010, - /// - /// The tile can cause damage when moved over. - /// - Damaging = 0x00000020, - /// - /// The tile may not be moved over or through. - /// - Impassable = 0x00000040, - /// - /// Not yet documented. - /// - Wet = 0x00000080, - /// - /// Unknown. - /// - Unknown1 = 0x00000100, - /// - /// The tile is a surface. It may be moved over, but not through. - /// - Surface = 0x00000200, - /// - /// The tile is a stair, ramp, or ladder. - /// - Bridge = 0x00000400, - /// - /// The tile is stackable - /// - Generic = 0x00000800, - /// - /// The tile is a window. Like , tiles with this flag block line of sight. - /// - Window = 0x00001000, - /// - /// The tile blocks line of sight. - /// - NoShoot = 0x00002000, - /// - /// For single-amount tiles, the string "a " should be prepended to the tile name. - /// - ArticleA = 0x00004000, - /// - /// For single-amount tiles, the string "an " should be prepended to the tile name. - /// - ArticleAn = 0x00008000, - /// - /// Not yet documented. - /// - Internal = 0x00010000, - /// - /// The tile becomes translucent when walked behind. Boat masts also have this flag. - /// - Foliage = 0x00020000, - /// - /// Only gray pixels will be hued - /// - PartialHue = 0x00040000, - /// - /// Unknown. - /// - NoHouse = 0x00080000, - /// - /// The tile is a map--in the cartography sense. Unknown usage. - /// - Map = 0x00100000, - /// - /// The tile is a container. - /// - Container = 0x00200000, - /// - /// The tile may be equiped. - /// - Wearable = 0x00400000, - /// - /// The tile gives off light. - /// - LightSource = 0x00800000, - /// - /// The tile is animated. - /// - Animation = 0x01000000, - /// - /// Gargoyles can fly over - /// - NoDiagonal = 0x02000000, - /// - /// Unknown. - /// - Unknown2 = 0x04000000, - /// - /// Not yet documented. - /// - Armor = 0x08000000, - /// - /// The tile is a slanted roof. - /// - Roof = 0x10000000, - /// - /// The tile is a door. Tiles with this flag can be moved through by ghosts and GMs. - /// - Door = 0x20000000, - /// - /// Not yet documented. - /// - StairBack = 0x40000000, - /// - /// Not yet documented. - /// - StairRight = 0x80000000, - /// Blend Alphas, tile blending. - AlphaBlend = 0x0100000000, - /// Uses new art style? - UseNewArt = 0x0200000000, - /// Has art being used? - ArtUsed = 0x0400000000, - /// Disallow shadow on this tile, lightsource? lava? - NoShadow = 0x1000000000, - /// Let pixels bleed in to other tiles? Is this Disabling Texture Clamp? - PixelBleed = 0x2000000000, - /// Play tile animation once. - PlayAnimOnce = 0x4000000000, - /// Movable multi? Cool ships and vehicles etc? - MultiMovable = 0x10000000000 - } -} \ No newline at end of file diff --git a/src/ClassicUO.Assets/TrueTypeLoader.cs b/src/ClassicUO.Assets/TrueTypeLoader.cs deleted file mode 100644 index 2477fb800..000000000 --- a/src/ClassicUO.Assets/TrueTypeLoader.cs +++ /dev/null @@ -1,116 +0,0 @@ -#region license - -// Copyright (c) 2021, jaedan -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using FontStashSharp; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public class TrueTypeLoader - { - public const string EMBEDDED_FONT = "Roboto-Regular"; - - private Dictionary _fonts = new(); - - private TrueTypeLoader() - { - } - - private static TrueTypeLoader _instance; - public static TrueTypeLoader Instance => _instance ??= new TrueTypeLoader(); - - public Task Load() - { - var settings = new FontSystemSettings - { - FontResolutionFactor = 1, - KernelWidth = 1, - KernelHeight = 1 - }; - - string _fontPath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Fonts"); - - if (!Directory.Exists(_fontPath)) - Directory.CreateDirectory(_fontPath); - - foreach (var ttf in Directory.GetFiles(_fontPath, "*.ttf")) - { - var fontSystem = new FontSystem(settings); - fontSystem.AddFont(File.ReadAllBytes(ttf)); - - _fonts[Path.GetFileNameWithoutExtension(ttf)] = fontSystem; - } - - if (!_fonts.ContainsKey("Roboto-Regular")) - { - var assembly = this.GetType().Assembly; - var resourceName = assembly.GetName().Name + ".Roboto-Regular.ttf"; - System.Console.WriteLine(resourceName); - Stream stream = assembly.GetManifestResourceStream(resourceName); - if (stream != null) - { - var memoryStream = new MemoryStream(); - - stream.CopyTo(memoryStream); - var fontSystem = new FontSystem(settings); - fontSystem.AddFont(memoryStream.ToArray()); - _fonts["Roboto-Regular"] = fontSystem; - } - } - - return Task.CompletedTask; - } - - public SpriteFontBase GetFont(string name, float size) - { - if (_fonts.TryGetValue(name, out var font)) - { - return font.GetFont(size); - } - - if (_fonts.Count > 0) - return _fonts.First().Value.GetFont(size); - - return null; - } - - public SpriteFontBase GetFont(string name) - { - return GetFont(name, 12); - } - - public string[] Fonts => _fonts.Keys.ToArray(); - } -} \ No newline at end of file diff --git a/src/ClassicUO.Assets/UOFileManager.cs b/src/ClassicUO.Assets/UOFileManager.cs deleted file mode 100644 index 3204ade05..000000000 --- a/src/ClassicUO.Assets/UOFileManager.cs +++ /dev/null @@ -1,395 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using ClassicUO.Utility.Platforms; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Runtime.InteropServices; -using System.Threading.Tasks; - -namespace ClassicUO.Assets -{ - public static class UOFileManager - { - public static string GetUOFilePath(string file) - { - if (!UOFilesOverrideMap.Instance.TryGetValue(file.ToLowerInvariant(), out string uoFilePath)) - { - uoFilePath = Path.Combine(BasePath, file); - } - - //If the file with the given name doesn't exist, check for it with alternative casing if not on windows - if (!PlatformHelper.IsWindows && !File.Exists(uoFilePath)) - { - FileInfo finfo = new FileInfo(uoFilePath); - var dir = Path.GetFullPath(finfo.DirectoryName ?? BasePath); - - if (Directory.Exists(dir)) - { - var files = Directory.GetFiles(dir); - var matches = 0; - - foreach (var f in files) - { - if (string.Equals(f, uoFilePath, StringComparison.OrdinalIgnoreCase)) - { - matches++; - uoFilePath = f; - } - } - - if (matches > 1) - { - Log.Warn($"Multiple files with ambiguous case found for {file}, using {Path.GetFileName(uoFilePath)}. Check your data directory for duplicate files."); - } - } - } - - return uoFilePath; - } - - public static ClientVersion Version; - public static string BasePath; - public static bool IsUOPInstallation; - - public static void Load(ClientVersion version, string basePath, bool useVerdata, string lang) - { - Stopwatch stopwatch = Stopwatch.StartNew(); - - Version = version; - BasePath = basePath; - - UOFilesOverrideMap.Instance.Load(); // need to load this first so that it manages can perform the file overrides if needed - - IsUOPInstallation = Version >= ClientVersion.CV_7000 && File.Exists(GetUOFilePath("MainMisc.uop")); - - List tasks = new List - { - AnimationsLoader.Instance.Load(), - AnimDataLoader.Instance.Load(), - ArtLoader.Instance.Load(), - MapLoader.Instance.Load(), - ClilocLoader.Instance.Load(lang), - GumpsLoader.Instance.Load(), - FontsLoader.Instance.Load(), - HuesLoader.Instance.Load(), - TileDataLoader.Instance.Load(), - MultiLoader.Instance.Load(), - SkillsLoader.Instance.Load().ContinueWith(t => ProfessionLoader.Instance.Load()), - TexmapsLoader.Instance.Load(), - SpeechesLoader.Instance.Load(), - LightsLoader.Instance.Load(), - SoundsLoader.Instance.Load(), - MultiMapLoader.Instance.Load(), - PNGLoader.Instance.Load(), - TrueTypeLoader.Instance.Load() - }; - - if (!Task.WhenAll(tasks).Wait(TimeSpan.FromSeconds(15))) - { - Log.Panic("Loading files timeout."); - } - - Read_Art_def(); - - UOFileMul verdata = Verdata.File; - - bool forceVerdata = Version < ClientVersion.CV_500A || verdata != null && verdata.Length != 0 && Verdata.Patches.Length != 0; - - if (!useVerdata && forceVerdata) - { - useVerdata = true; - } - - Log.Trace($"Use verdata.mul: {(useVerdata ? "Yes" : "No")}"); - - if (useVerdata) - { - if (verdata != null && Verdata.Patches.Length != 0) - { - Log.Info(">> PATCHING WITH VERDATA.MUL"); - - for (int i = 0; i < Verdata.Patches.Length; i++) - { - ref UOFileIndex5D vh = ref Verdata.Patches[i]; - Log.Info($">>> patching FileID: {vh.FileID} - BlockID: {vh.BlockID}"); - - if (vh.FileID == 0) - { - MapLoader.Instance.PatchMapBlock(vh.BlockID, vh.Position); - } - else if (vh.FileID == 2) - { - MapLoader.Instance.PatchStaticBlock(vh.BlockID, ((ulong) verdata.StartAddress.ToInt64() + vh.Position), vh.Length); - } - else if (vh.FileID == 4) - { - if (vh.BlockID < ArtLoader.Instance.Entries.Length) - { - ArtLoader.Instance.Entries[vh.BlockID] = new UOFileIndex - ( - verdata.StartAddress, - (uint) verdata.Length, - vh.Position, - (int) vh.Length, - 0 - ); - } - } - else if (vh.FileID == 12) - { - GumpsLoader.Instance.Entries[vh.BlockID] = new UOFileIndex - ( - verdata.StartAddress, - (uint) verdata.Length, - vh.Position, - (int) vh.Length, - 0, - (short) (vh.GumpData >> 16), - (short) (vh.GumpData & 0xFFFF) - ); - } - else if (vh.FileID == 14 && vh.BlockID < MultiLoader.Instance.Count) - { - MultiLoader.Instance.Entries[vh.BlockID] = new UOFileIndex - ( - verdata.StartAddress, - (uint) verdata.Length, - vh.Position, - (int) vh.Length, - 0 - ); - } - else if (vh.FileID == 16 && vh.BlockID < SkillsLoader.Instance.SkillsCount) - { - SkillEntry skill = SkillsLoader.Instance.Skills[(int) vh.BlockID]; - - if (skill != null) - { - unsafe - { - StackDataReader reader = new StackDataReader(new ReadOnlySpan((byte*)verdata.StartAddress, (int) verdata.Length)); - - skill.HasAction = reader.ReadUInt8() != 0; - skill.Name = reader.ReadASCII((int)(vh.Length - 1)); - - reader.Release(); - } - } - } - else if (vh.FileID == 30) - { - verdata.Seek(0); - verdata.Skip((int) vh.Position); - - if (vh.Length == 836) - { - int offset = (int) (vh.BlockID * 32); - - if (offset + 32 > TileDataLoader.Instance.LandData.Length) - { - continue; - } - - verdata.ReadUInt(); - - for (int j = 0; j < 32; j++) - { - ulong flags; - - if (Version < ClientVersion.CV_7090) - { - flags = verdata.ReadUInt(); - } - else - { - flags = verdata.ReadULong(); - } - - TileDataLoader.Instance.LandData[offset + j] = new LandTiles(flags, verdata.ReadUShort(), verdata.ReadASCII(20)); - } - } - else if (vh.Length == 1188) - { - int offset = (int) ((vh.BlockID - 0x0200) * 32); - - if (offset + 32 > TileDataLoader.Instance.StaticData.Length) - { - continue; - } - - verdata.ReadUInt(); - - for (int j = 0; j < 32; j++) - { - ulong flags; - - if (Version < ClientVersion.CV_7090) - { - flags = verdata.ReadUInt(); - } - else - { - flags = verdata.ReadULong(); - } - - TileDataLoader.Instance.StaticData[offset + j] = new StaticTiles - ( - flags, - verdata.ReadByte(), - verdata.ReadByte(), - verdata.ReadInt(), - verdata.ReadUShort(), - verdata.ReadUShort(), - verdata.ReadUShort(), - verdata.ReadByte(), - verdata.ReadASCII(20) - ); - } - } - } - else if (vh.FileID == 32) - { - if (vh.BlockID < HuesLoader.Instance.HuesCount) - { - VerdataHuesGroup group = Marshal.PtrToStructure(verdata.StartAddress + (int) vh.Position); - - HuesGroup[] hues = HuesLoader.Instance.HuesRange; - - hues[vh.BlockID].Header = group.Header; - - for (int j = 0; j < 8; j++) - { - Array.Copy(group.Entries[j].ColorTable, hues[vh.BlockID].Entries[j].ColorTable, 32); - } - } - } - else if (vh.FileID != 5 && vh.FileID != 6) - { - Log.Warn($"Unused verdata block\tFileID: {vh.FileID}\tBlockID: {vh.BlockID}"); - } - } - - Log.Info("<< PATCHED."); - } - } - - - Log.Trace($"Files loaded in: {stopwatch.ElapsedMilliseconds} ms!"); - stopwatch.Stop(); - } - - public static void MapLoaderReLoad(MapLoader newloader) - { - MapLoader.Instance?.Dispose(); - MapLoader.Instance = newloader; - } - - private static void Read_Art_def() - { - string pathdef = GetUOFilePath("art.def"); - - if (File.Exists(pathdef)) - { - TileDataLoader tiledataLoader = TileDataLoader.Instance; - ArtLoader artLoader = ArtLoader.Instance; - - using (DefReader reader = new DefReader(pathdef, 1)) - { - while (reader.Next()) - { - int index = reader.ReadInt(); - - if (index < 0 || index >= ArtLoader.MAX_LAND_DATA_INDEX_COUNT + tiledataLoader.StaticData.Length) - { - continue; - } - - int[] group = reader.ReadGroup(); - - if (group == null) - { - continue; - } - - for (int i = 0; i < group.Length; i++) - { - int checkIndex = group[i]; - - if (checkIndex < 0 || checkIndex >= ArtLoader.MAX_LAND_DATA_INDEX_COUNT + tiledataLoader.StaticData.Length) - { - continue; - } - - if (index < artLoader.Entries.Length && checkIndex < artLoader.Entries.Length) - { - ref UOFileIndex currentEntry = ref artLoader.GetValidRefEntry(index); - ref UOFileIndex checkEntry = ref artLoader.GetValidRefEntry(checkIndex); - - if (currentEntry.Equals(UOFileIndex.Invalid) && !checkEntry.Equals(UOFileIndex.Invalid)) - { - artLoader.Entries[index] = artLoader.Entries[checkIndex]; - } - } - - if (index < ArtLoader.MAX_LAND_DATA_INDEX_COUNT && - checkIndex < ArtLoader.MAX_LAND_DATA_INDEX_COUNT && - checkIndex < tiledataLoader.LandData.Length && - index < tiledataLoader.LandData.Length && - !tiledataLoader.LandData[checkIndex].Equals(default) && - tiledataLoader.LandData[index].Equals(default)) - { - tiledataLoader.LandData[index] = tiledataLoader.LandData[checkIndex]; - - break; - } - - if (index >= ArtLoader.MAX_LAND_DATA_INDEX_COUNT && checkIndex >= ArtLoader.MAX_LAND_DATA_INDEX_COUNT && - index < tiledataLoader.StaticData.Length && checkIndex < tiledataLoader.StaticData.Length && - tiledataLoader.StaticData[index].Equals(default) && !tiledataLoader.StaticData[checkIndex].Equals(default)) - { - tiledataLoader.StaticData[index] = tiledataLoader.StaticData[checkIndex]; - - break; - } - } - } - } - } - } - } -} diff --git a/src/ClassicUO.Assets/Verdata.cs b/src/ClassicUO.Assets/Verdata.cs deleted file mode 100644 index 1abcde70f..000000000 --- a/src/ClassicUO.Assets/Verdata.cs +++ /dev/null @@ -1,96 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using System.Runtime.CompilerServices; - -namespace ClassicUO.Assets -{ - public static class Verdata - { - unsafe static Verdata() - { - string path = UOFileManager.GetUOFilePath("verdata.mul"); - - if (!System.IO.File.Exists(path)) - { - Patches = new UOFileIndex5D[0]; - File = null; - } - else - { - File = new UOFileMul(path); - - // the scope of this try/catch is to avoid unexpected crashes if servers redestribuite wrong verdata - try - { - int len = File.ReadInt(); - Patches = new UOFileIndex5D[len]; - - fixed (UOFileIndex5D* ptr = Patches) - { - Unsafe.CopyBlockUnaligned((void*)ptr, (void*) File.PositionAddress, (uint) (len * Unsafe.SizeOf())); - } - } - catch - { - Patches = new UOFileIndex5D[0]; - } - } - } - - // FileIDs - //0 - map0.mul - //1 - staidx0.mul - //2 - statics0.mul - //3 - artidx.mul - //4 - art.mul - //5 - anim.idx - //6 - anim.mul - //7 - soundidx.mul - //8 - sound.mul - //9 - texidx.mul - //10 - texmaps.mul - //11 - gumpidx.mul - //12 - gumps.mul - //13 - multi.idx - //14 - multi.mul - //15 - skills.idx - //16 - skills.mul - //30 - tiledata.mul - //31 - animdata.mul - - public static UOFileIndex5D[] Patches { get; } - - public static UOFileMul File { get; } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/CUOEnviroment.cs b/src/ClassicUO.Client/CUOEnviroment.cs deleted file mode 100644 index 04fc42f3c..000000000 --- a/src/ClassicUO.Client/CUOEnviroment.cs +++ /dev/null @@ -1,65 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.IO; -using System.Reflection; -using System.Threading; - -namespace ClassicUO -{ - internal static class CUOEnviroment - { - public static Thread GameThread; - public static float DPIScaleFactor = 1.0f; - public static bool NoSound; - public static string[] Args; - public static string[] Plugins; - public static bool Debug; - public static bool IsHighDPI; - public static uint CurrentRefreshRate; - public static bool SkipLoginScreen; - public static bool IsOutlands; - public static bool NoServerPing; - public static Assembly Assembly => Assembly.GetEntryAssembly(); - - public static readonly bool IsUnix = Environment.OSVersion.Platform != PlatformID.Win32NT && Environment.OSVersion.Platform != PlatformID.Win32Windows && Environment.OSVersion.Platform != PlatformID.Win32S && Environment.OSVersion.Platform != PlatformID.WinCE; - - public static readonly Version Version = Assembly.GetExecutingAssembly().GetName().Version; - public static readonly string ExecutablePath = -#if NETFRAMEWORK - Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location); -#else - Environment.CurrentDirectory; -#endif - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/ClassicUO.Client.csproj b/src/ClassicUO.Client/ClassicUO.Client.csproj deleted file mode 100644 index e37413e13..000000000 --- a/src/ClassicUO.Client/ClassicUO.Client.csproj +++ /dev/null @@ -1,126 +0,0 @@ - - - - WinExe - cuoicon.ico - ClassicUO - ClassicUO - 3.19.0 - 3.19.0 - - - - $(ProjectDir)..\..\bin\Release\ - $(ProjectDir)..\..\bin\dist\ - true - - - - $(ProjectDir)..\..\bin\Debug\ - $(DefineConstants)TRACE - - - - WinExe - - - - - <_Parameter1>ClassicUO.UnitTests - - - - - - - - - - - - - - - - - - - - - True - True - ResErrorMessages.resx - - - True - True - ResGeneral.resx - - - True - True - ResGumps.resx - - - - - - PublicResXFileCodeGenerator - ResErrorMessages.Designer.cs - - - PublicResXFileCodeGenerator - ResGeneral.Designer.cs - - - PublicResXFileCodeGenerator - ResGumps.Designer.cs - - - - - - - - - - - - - - - - - ..\..\external\cuoapi\cuoapi.dll - - - ..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Net.Http.dll - - - ..\..\..\..\..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Windows.Forms.dll - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ClassicUO.Client/Client.cs b/src/ClassicUO.Client/Client.cs deleted file mode 100644 index 902899366..000000000 --- a/src/ClassicUO.Client/Client.cs +++ /dev/null @@ -1,212 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Game; -using ClassicUO.Game.Data; -using ClassicUO.Network; -using ClassicUO.Network.Encryption; -using ClassicUO.Resources; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using ClassicUO.Utility.Platforms; -using SDL2; -using System; -using System.Diagnostics; -using System.IO; - -namespace ClassicUO -{ - internal static class Client - { - public static ClientVersion Version { get; private set; } - public static ClientFlags Protocol { get; set; } - public static string ClientPath { get; private set; } - public static GameController Game { get; private set; } - - - public static void Run() - { - Debug.Assert(Game == null); - - ScriptCompiler.InvokeAfterCompiling("Configure"); - - Load(); - - Log.Trace("Running game..."); - - using (Game = new GameController()) - { - // https://github.com/FNA-XNA/FNA/wiki/7:-FNA-Environment-Variables#fna_graphics_enable_highdpi - CUOEnviroment.IsHighDPI = Environment.GetEnvironmentVariable("FNA_GRAPHICS_ENABLE_HIGHDPI") == "1"; - - if (CUOEnviroment.IsHighDPI) - { - Log.Trace("HIGH DPI - ENABLED"); - } - - Log.Trace("Loading plugins..."); - - foreach (string p in Settings.GlobalSettings.Plugins) - { - Plugin.Create(p); - } - - Log.Trace("Done!"); - - UoAssist.Start(); - - ScriptCompiler.InvokeAfterCompiling("Initialize"); - - Game.Run(); - } - - Log.Trace("Exiting game..."); - } - - public static void ShowErrorMessage(string msg) - { - SDL.SDL_ShowSimpleMessageBox(SDL.SDL_MessageBoxFlags.SDL_MESSAGEBOX_ERROR, "ERROR", msg, IntPtr.Zero); - } - - - private static void Load() - { - string clientPath = Settings.GlobalSettings.UltimaOnlineDirectory; - Log.Trace($"Ultima Online installation folder: {clientPath}"); - - Log.Trace("Loading files..."); - - if (!string.IsNullOrWhiteSpace(Settings.GlobalSettings.ClientVersion)) - { - // sanitize client version - Settings.GlobalSettings.ClientVersion = Settings.GlobalSettings.ClientVersion.Replace(",", ".").Replace(" ", "").ToLower(); - } - - string clientVersionText = Settings.GlobalSettings.ClientVersion; - - // check if directory is good - if (!Directory.Exists(clientPath)) - { - Log.Error("Invalid client directory: " + clientPath); - ShowErrorMessage(string.Format(ResErrorMessages.ClientPathIsNotAValidUODirectory, clientPath)); - - throw new InvalidClientDirectory($"'{clientPath}' is not a valid directory"); - } - - // try to load the client version - if (!ClientVersionHelper.IsClientVersionValid(clientVersionText, out ClientVersion clientVersion)) - { - Log.Warn($"Client version [{clientVersionText}] is invalid, let's try to read the client.exe"); - - // mmm something bad happened, try to load from client.exe - if (!ClientVersionHelper.TryParseFromFile(Path.Combine(clientPath, "client.exe"), out clientVersionText) || !ClientVersionHelper.IsClientVersionValid(clientVersionText, out clientVersion)) - { - Log.Error("Invalid client version: " + clientVersionText); - ShowErrorMessage(string.Format(ResGumps.ImpossibleToDefineTheClientVersion0, clientVersionText)); - - throw new InvalidClientVersion($"Invalid client version: '{clientVersionText}'"); - } - - Log.Trace($"Found a valid client.exe [{clientVersionText} - {clientVersion}]"); - - // update the wrong/missing client version in settings.json - Settings.GlobalSettings.ClientVersion = clientVersionText; - } - - Version = clientVersion; - ClientPath = clientPath; - - Protocol = ClientFlags.CF_T2A; - - if (Version >= ClientVersion.CV_200) - { - Protocol |= ClientFlags.CF_RE; - } - - if (Version >= ClientVersion.CV_300) - { - Protocol |= ClientFlags.CF_TD; - } - - if (Version >= ClientVersion.CV_308) - { - Protocol |= ClientFlags.CF_LBR; - } - - if (Version >= ClientVersion.CV_308Z) - { - Protocol |= ClientFlags.CF_AOS; - } - - if (Version >= ClientVersion.CV_405A) - { - Protocol |= ClientFlags.CF_SE; - } - - if (Version >= ClientVersion.CV_60144) - { - Protocol |= ClientFlags.CF_SA; - } - - Log.Trace($"Client path: '{clientPath}'"); - Log.Trace($"Client version: {clientVersion}"); - Log.Trace($"Protocol: {Protocol}"); - - // ok now load uo files - UOFileManager.Load(Version, Settings.GlobalSettings.UltimaOnlineDirectory, Settings.GlobalSettings.UseVerdata, Settings.GlobalSettings.Language); - StaticFilters.Load(); - - BuffTable.Load(); - ChairTable.Load(); - - Log.Trace("Network calibration..."); - //ATTENTION: you will need to enable ALSO ultimalive server-side, or this code will have absolutely no effect! - UltimaLive.Enable(); - PacketsTable.AdjustPacketSizeByVersion(Version); - - if (Settings.GlobalSettings.Encryption != 0) - { - Log.Trace("Calculating encryption by client version..."); - EncryptionHelper.CalculateEncryption(Version); - Log.Trace($"encryption: {EncryptionHelper.Type}"); - - if (EncryptionHelper.Type != (ENCRYPTION_TYPE)Settings.GlobalSettings.Encryption) - { - Log.Warn($"Encryption found: {EncryptionHelper.Type}"); - Settings.GlobalSettings.Encryption = (byte)EncryptionHelper.Type; - } - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/ClientException.cs b/src/ClassicUO.Client/ClientException.cs deleted file mode 100644 index 11b2df6ca..000000000 --- a/src/ClassicUO.Client/ClientException.cs +++ /dev/null @@ -1,50 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; - -namespace ClassicUO -{ - internal class InvalidClientVersion : Exception - { - public InvalidClientVersion(string msg) : base(msg) - { - } - } - - internal class InvalidClientDirectory : Exception - { - public InvalidClientDirectory(string msg) : base(msg) - { - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Configuration/ConfigurationResolver.cs b/src/ClassicUO.Client/Configuration/ConfigurationResolver.cs deleted file mode 100644 index e5074fe07..000000000 --- a/src/ClassicUO.Client/Configuration/ConfigurationResolver.cs +++ /dev/null @@ -1,88 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.IO; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Text.RegularExpressions; -using ClassicUO.Utility.Logging; - -namespace ClassicUO.Configuration -{ - internal static class ConfigurationResolver - { - public static T Load(string file, JsonSerializerContext ctx) where T : class - { - if (!File.Exists(file)) - { - Log.Warn(file + " not found."); - - return null; - } - - var text = File.ReadAllText(file); - - text = Regex.Replace - ( - text, - @"(?(T obj, string file, JsonSerializerContext ctx) where T : class - { - // this try catch is necessary when multiples cuo instances points to this file. - try - { - var fileInfo = new FileInfo(file); - - if (fileInfo.Directory != null && !fileInfo.Directory.Exists) - { - fileInfo.Directory.Create(); - } - - var json = JsonSerializer.Serialize(obj, typeof(T), ctx); - File.WriteAllText(file, json); - } - catch (IOException e) - { - Log.Error(e.ToString()); - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Configuration/Json/FNAPointJsonConverter.cs b/src/ClassicUO.Client/Configuration/Json/FNAPointJsonConverter.cs deleted file mode 100644 index 3153f754d..000000000 --- a/src/ClassicUO.Client/Configuration/Json/FNAPointJsonConverter.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Configuration.Json -{ - sealed class Point2Converter : JsonConverter - { - public override Point Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - if (reader.TokenType != JsonTokenType.StartObject) - { - return Point.Zero; - } - - reader.Read(); - - if (reader.TokenType != JsonTokenType.PropertyName) - { - return Point.Zero; - } - - reader.Read(); - - if (reader.TokenType != JsonTokenType.Number) - { - return Point.Zero; - } - - var point = new Point(); - - point.X = reader.GetInt32(); - - reader.Read(); - - if (reader.TokenType != JsonTokenType.PropertyName) - { - return Point.Zero; - } - - reader.Read(); - - if (reader.TokenType != JsonTokenType.Number) - { - return Point.Zero; - } - - point.Y = reader.GetInt32(); - - reader.Read(); - - if (reader.TokenType != JsonTokenType.EndObject) - { - return Point.Zero; - } - - return point; - } - - public override void Write(Utf8JsonWriter writer, Point value, JsonSerializerOptions options) - { - writer.WriteStartObject(); - writer.WriteNumber("X", value.X); - writer.WriteNumber("Y", value.Y); - writer.WriteEndObject(); - } - } - - sealed class NullablePoint2Converter : JsonConverter - { - public override Point? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - if (reader.TokenType != JsonTokenType.StartObject) - { - return Point.Zero; - } - - reader.Read(); - - if (reader.TokenType != JsonTokenType.PropertyName) - { - return Point.Zero; - } - - reader.Read(); - - if (reader.TokenType != JsonTokenType.Number) - { - return Point.Zero; - } - - var point = new Point(); - - point.X = reader.GetInt32(); - - reader.Read(); - - if (reader.TokenType != JsonTokenType.PropertyName) - { - return Point.Zero; - } - - reader.Read(); - - if (reader.TokenType != JsonTokenType.Number) - { - return Point.Zero; - } - - point.Y = reader.GetInt32(); - - reader.Read(); - - if (reader.TokenType != JsonTokenType.EndObject) - { - return Point.Zero; - } - - return point; - } - - public override void Write(Utf8JsonWriter writer, Point? value, JsonSerializerOptions options) - { - writer.WriteStartObject(); - writer.WriteNumber("X", value.Value.X); - writer.WriteNumber("Y", value.Value.Y); - writer.WriteEndObject(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Configuration/Language.cs b/src/ClassicUO.Client/Configuration/Language.cs deleted file mode 100644 index 80afb8117..000000000 --- a/src/ClassicUO.Client/Configuration/Language.cs +++ /dev/null @@ -1,575 +0,0 @@ -using System.IO; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace ClassicUO.Configuration -{ - public class Language - { - public ModernOptionsGumpLanguage GetModernOptionsGumpLanguage { get; set; } = new ModernOptionsGumpLanguage(); - public ErrorsLanguage ErrorsLanguage { get; set; } = new ErrorsLanguage(); - public MapLanguage MapLanguage { get; set; } = new MapLanguage(); - - [JsonIgnore] - public static Language Instance { get; private set; } = new Language(); - - public static void Load() - { - if (File.Exists(languageFilePath)) - { - Language f = JsonSerializer.Deserialize(File.ReadAllText(languageFilePath)); - Instance = f; - Save(); //To update language file with new additions as needed - } - else - { - CreateNewLanguageFile(); - } - } - - private static void CreateNewLanguageFile() - { - Directory.CreateDirectory(Path.Combine(CUOEnviroment.ExecutablePath, "Data")); - - string defaultLanguage = JsonSerializer.Serialize(Instance, new JsonSerializerOptions() { WriteIndented = true }); - File.WriteAllText(languageFilePath, defaultLanguage); - } - - private static void Save() - { - string language = JsonSerializer.Serialize(Instance, new JsonSerializerOptions() { WriteIndented = true }); - File.WriteAllText(languageFilePath, language); - } - - private static string languageFilePath { get { return Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Language.json"); } } - } - - public class ModernOptionsGumpLanguage - { - public string OptionsTitle { get; set; } = "Options"; - public string Search { get; set; } = "Search"; - - public string ButtonGeneral { get; set; } = "General"; - public string ButtonSound { get; set; } = "Sound"; - public string ButtonVideo { get; set; } = "Video"; - public string ButtonMacros { get; set; } = "Macros"; - public string ButtonTooltips { get; set; } = "Tooltips"; - public string ButtonSpeech { get; set; } = "Speech"; - public string ButtonCombatSpells { get; set; } = "Combat & Spells"; - public string ButtonCounters { get; set; } = "Counters"; - public string ButtonInfobar { get; set; } = "Infobar"; - public string ButtonContainers { get; set; } = "Containers"; - public string ButtonExperimental { get; set; } = "Experimental"; - public string ButtonIgnoreList { get; set; } = "Ignore List"; - public string ButtonNameplates { get; set; } = "Nameplate Options"; - public string ButtonCooldowns { get; set; } = "Cooldown bars"; - public string ButtonTazUO { get; set; } = "TazUO Specific"; - public string ButtonMobiles { get; set; } = "Mobiles"; - public string ButtonGumpContext { get; set; } = "Gumps & Context"; - public string ButtonMisc { get; set; } = "Misc"; - public string ButtonTerrainStatics { get; set; } = "Terrain & Statics"; - public string ButtonGameWindow { get; set; } = "Game window"; - public string ButtonZoom { get; set; } = "Zoom"; - public string ButtonLighting { get; set; } = "Lighting"; - public string ButtonShadows { get; set; } = "Shadows"; - - public General GetGeneral { get; set; } = new General(); - public Video GetVideo { get; set; } = new Video(); - public Sound GetSound { get; set; } = new Sound(); - public Macros GetMacros { get; set; } = new Macros(); - public ToolTips GetToolTips { get; set; } = new ToolTips(); - public Speech GetSpeech { get; set; } = new Speech(); - public CombatSpells GetCombatSpells { get; set; } = new CombatSpells(); - public Counters GetCounters { get; set; } = new Counters(); - public InfoBars GetInfoBars { get; set; } = new InfoBars(); - public Containers GetContainers { get; set; } = new Containers(); - public Experimental GetExperimental { get; set; } = new Experimental(); - public NamePlates GetNamePlates { get; set; } = new NamePlates(); - public Cooldowns GetCooldowns { get; set; } = new Cooldowns(); - public TazUO GetTazUO { get; set; } = new TazUO(); - - public class General - { - public string SharedNone { get; set; } = "None"; - public string SharedShift { get; set; } = "Shift"; - public string SharedCtrl { get; set; } = "Ctrl"; - - #region General->General - public string HighlightObjects { get; set; } = "Highlight objects under cursor"; - public string Pathfinding { get; set; } = "Enable pathfinding"; - public string ShiftPathfinding { get; set; } = "Use shift for pathfinding"; - public string SingleClickPathfind { get; set; } = "Single click for pathfinding"; - public string AlwaysRun { get; set; } = "Always run"; - public string RunUnlessHidden { get; set; } = "Unless hidden"; - public string AutoOpenDoors { get; set; } = "Automatically open doors"; - public string AutoOpenPathfinding { get; set; } = "Open doors while pathfinding"; - public string AutoOpenCorpse { get; set; } = "Automatically open corpses"; - public string CorpseOpenDistance { get; set; } = "Corpse open distance"; - public string CorpseSkipEmpty { get; set; } = "Skip empty corpses"; - public string CorpseOpenOptions { get; set; } = "Corpse open options"; - public string CorpseOptNone { get; set; } = "None"; - public string CorpseOptNotTarg { get; set; } = "Not targeting"; - public string CorpseOptNotHiding { get; set; } = "Not hiding"; - public string CorpseOptBoth { get; set; } = "Both"; - public string OutRangeColor { get; set; } = "No color for out of range objects"; - public string SallosEasyGrab { get; set; } = "Enable sallos easy grab"; - public string SallosTooltip { get; set; } = "Sallos easy grab is not recommended with grid containers enabled."; - public string ShowHouseContent { get; set; } = "Show house content"; - public string SmoothBoat { get; set; } = "Smooth boat movements"; - #endregion - - #region General->Mobiles - public string ShowMobileHP { get; set; } = "Show mobile's HP"; - public string MobileHPType { get; set; } = "Type"; - public string HPTypePerc { get; set; } = "Percentage"; - public string HPTypeBar { get; set; } = "Bar"; - public string HPTypeNBoth { get; set; } = "Both"; - public string HPShowWhen { get; set; } = "Show when"; - public string HPShowWhen_Always { get; set; } = "Always"; - public string HPShowWhen_Less100 { get; set; } = "Less than 100%"; - public string HPShowWhen_Smart { get; set; } = "Smart"; - public string HighlightPoisoned { get; set; } = "Highlight poisoned mobiles"; - public string PoisonHighlightColor { get; set; } = "Highlight color"; - public string HighlightPara { get; set; } = "Highlight paralyzed mobiles"; - public string ParaHighlightColor { get; set; } = "Highlight color"; - public string HighlightInvul { get; set; } = "Highlight invulnerable mobiles"; - public string InvulHighlightColor { get; set; } = "Highlight color"; - public string IncomingMobiles { get; set; } = "Show incoming mobile names"; - public string IncomingCorpses { get; set; } = "Show incoming corpse names"; - public string AuraUnderFeet { get; set; } = "Show aura under feet"; - public string AuraOptDisabled { get; set; } = "Disabled"; - public string AuroOptWarmode { get; set; } = "Warmode"; - public string AuraOptCtrlShift { get; set; } = "Ctrl + Shift"; - public string AuraOptAlways { get; set; } = "Always"; - public string AuraForParty { get; set; } = "Use a custom color for party members"; - public string AuraPartyColor { get; set; } = "Party aura color"; - #endregion - - #region General->Gumps - public string DisableTopMenu { get; set; } = "Disable top menu bar"; - public string AltForAnchorsGumps { get; set; } = "Require alt to close anchored gumps"; - public string AltToMoveGumps { get; set; } = "Require alt to move gumps"; - public string CloseEntireAnchorWithRClick { get; set; } = "Close entire group of anchored gumps with right click"; - public string OriginalSkillsGump { get; set; } = "Use original skills gump"; - public string OldStatusGump { get; set; } = "Use old status gump"; - public string PartyInviteGump { get; set; } = "Show party invite gump"; - public string ModernHealthBars { get; set; } = "Use modern health bar gumps"; - public string ModernHPBlackBG { get; set; } = "Use black background"; - public string SaveHPBars { get; set; } = "Save health bars on logout"; - public string CloseHPGumpsWhen { get; set; } = "Close health bars when"; - public string CloseHPOptDisable { get; set; } = "Disabled"; - public string CloseHPOptOOR { get; set; } = "Out of range"; - public string CloseHPOptDead { get; set; } = "Dead"; - public string CloseHPOptBoth { get; set; } = "Both"; - public string GridLoot { get; set; } = "Grid Loot"; - public string GridLootOptDisable { get; set; } = "Disabled"; - public string GridLootOptOnly { get; set; } = "Grid loot only"; - public string GridLootOptBoth { get; set; } = "Grid loot and normal container"; - public string GridLootTooltip { get; set; } = "This is not the same as Grid Containers, this is a simple grid gump used for looting corpses."; - public string ShiftContext { get; set; } = "Require shift to open context menus"; - public string ShiftSplit { get; set; } = "Require shift to split stacks of items"; - - #endregion - - #region General->Misc - public string EnableCOT { get; set; } = "Enable circle of transparency"; - public string COTDistance { get; set; } = "Distance"; - public string COTType { get; set; } = "Type"; - public string COTTypeOptFull { get; set; } = "Full"; - public string COTTypeOptGrad { get; set; } = "Gradient"; - public string COTTypeOptModern { get; set; } = "Modern"; - public string HideScreenshotMessage { get; set; } = "Hide 'screenshot stored in' message"; - public string ObjFade { get; set; } = "Enable object fading"; - public string TextFade { get; set; } = "Enable text fading"; - public string CursorRange { get; set; } = "Show target range indicator"; - public string DragSelectHP { get; set; } = "Enable drag select for health bars"; - public string DragKeyMod { get; set; } = "Key modifier"; - public string DragPlayersOnly { get; set; } = "Players only"; - public string DragMobsOnly { get; set; } = "Monsters only"; - public string DragNameplatesOnly { get; set; } = "Visible nameplates only"; - public string DragX { get; set; } = "X Position of healthbars"; - public string DragY { get; set; } = "Y Position of healthbars"; - public string DragAnchored { get; set; } = "Anchor opened health bars together"; - public string ShowStatsChangedMsg { get; set; } = "Show stats changed messages"; - public string ShowSkillsChangedMsg { get; set; } = "Show skills changed messages"; - public string ChangeVolume { get; set; } = "Changed by"; - #endregion - - #region General->TerrainStatics - public string HideRoof { get; set; } = "Hide roof tiles"; - public string TreesToStump { get; set; } = "Change trees to stumps"; - public string HideVegetation { get; set; } = "Hide vegetation"; - public string MagicFieldType { get; set; } = "Field types"; - public string MagicFieldOpt_Normal { get; set; } = "Normal"; - public string MagicFieldOpt_Static { get; set; } = "Static"; - public string MagicFieldOpt_Tile { get; set; } = "Tile"; - #endregion - } - - public class Sound - { - public string SharedVolume { get; set; } = "Volume"; - - public string EnableSound { get; set; } = "Enable sound"; - public string EnableMusic { get; set; } = "Enable music"; - public string LoginMusic { get; set; } = "Enable login page music"; - public string PlayFootsteps { get; set; } = "Play footsteps"; - public string CombatMusic { get; set; } = "Combat music"; - public string BackgroundMusic { get; set; } = "Play sound when UO is not in focus"; - } - - public class Video - { - #region GameWindow - public string FPSCap { get; set; } = "FPS Cap"; - public string BackgroundFPS { get; set; } = "Reduce FPS when game is not in focus"; - public string FullsizeViewport { get; set; } = "Always use fullsize game world viewport"; - public string FullScreen { get; set; } = "Fullscreen window"; - public string LockViewport { get; set; } = "Lock game world viewport position/size"; - public string ViewportX { get; set; } = "Viewport position X"; - public string ViewportY { get; set; } = "Viewport position Y"; - public string ViewportW { get; set; } = "Viewport width"; - public string ViewportH { get; set; } = "Viewport height"; - #endregion - - #region Zoom - public string DefaultZoom { get; set; } = "Default zoom"; - public string ZoomWheel { get; set; } = "Enable zooming with ctrl + mousewheel"; - public string ReturnDefaultZoom { get; set; } = "Return to default zoom after ctrl is released"; - #endregion - - #region Lighting - public string AltLights { get; set; } = "Alternative lights"; - public string CustomLLevel { get; set; } = "Custom light level"; - public string Level { get; set; } = "Light level"; - public string LightType { get; set; } = "Light level type"; - public string LightType_Absolute { get; set; } = "Absolute"; - public string LightType_Minimum { get; set; } = "Minimum"; - public string DarkNight { get; set; } = "Dark nights"; - public string ColoredLight { get; set; } = "Colored lighting"; - #endregion - - #region Misc - public string EnableDeathScreen { get; set; } = "Enable death screen"; - public string BWDead { get; set; } = "Black and white mode while dead"; - public string MouseThread { get; set; } = "Run mouse in seperate thread"; - public string TargetAura { get; set; } = "Aura on mouse target"; - public string AnimWater { get; set; } = "Animated water effect"; - #endregion - - #region Shadows - public string EnableShadows { get; set; } = "Enable shadows"; - public string RockTreeShadows { get; set; } = "Rock and tree shadows"; - public string TerrainShadowLevel { get; set; } = "Terrain shadow level"; - #endregion - } - - public class Macros - { - public string NewMacro { get; set; } = "New Macro"; - public string DelMacro { get; set; } = "Delete Macro"; - } - - public class ToolTips - { - public string EnableToolTips { get; set; } = "Enable tooltips"; - public string ToolTipDelay { get; set; } = "Tooltip delay"; - public string ToolTipBG { get; set; } = "Tooltip background opacity"; - public string ToolTipFont { get; set; } = "Default tooltip font color"; - } - - public class Speech - { - public string ScaleSpeechDelay { get; set; } = "Scale speech delay"; - public string SpeechDelay { get; set; } = "Delay"; - public string SaveJournalE { get; set; } = "Save journal entries to file"; - public string ChatEnterActivation { get; set; } = "Activate chat by pressing Enter"; - public string ChatEnterSpecial { get; set; } = "Also activate with common keys( ! ; : / \\ \\ , . [ | ~ )"; - public string ShiftEnterChat { get; set; } = "Use Shift + Enter to send message without closing chat"; - public string ChatGradient { get; set; } = "Hide chat gradient"; - public string HideGuildChat { get; set; } = "Hide guild chat"; - public string HideAllianceChat { get; set; } = "Hide alliance chat"; - public string SpeechColor { get; set; } = "Speech color"; - public string YellColor { get; set; } = "Yell color"; - public string PartyColor { get; set; } = "Party color"; - public string AllianceColor { get; set; } = "Alliance color"; - public string EmoteColor { get; set; } = "Emote color"; - public string WhisperColor { get; set; } = "Whisper color"; - public string GuildColor { get; set; } = "Guild color"; - public string CharColor { get; set; } = "Chat color"; - } - - public class CombatSpells - { - public string HoldTabForCombat { get; set; } = "Hold tab for combat"; - public string QueryBeforeAttack { get; set; } = "Query before attack"; - public string QueryBeforeBeneficial { get; set; } = "Query before beneficial acts on murderers/criminals/gray"; - public string EnableOverheadSpellFormat { get; set; } = "Enable overhead spell format"; - public string EnableOverheadSpellHue { get; set; } = "Enable overhead spell hue"; - public string SingleClickForSpellIcons { get; set; } = "Single click for spell icons"; - public string ShowBuffDurationOnOldStyleBuffBar { get; set; } = "Show buff duration on old style buff bar"; - public string EnableFastSpellHotkeyAssigning { get; set; } = "Enable fast spell hotkey assigning"; - public string TooltipFastSpellAssign { get; set; } = "Ctrl + Alt + Click a spell icon the open a gump to set a hotkey"; - public string InnocentColor { get; set; } = "Innocent color"; - public string BeneficialSpell { get; set; } = "Beneficial spell"; - public string FriendColor { get; set; } = "Friend color"; - public string HarmfulSpell { get; set; } = "Harmful spell"; - public string Criminal { get; set; } = "Criminal"; - public string NeutralSpell { get; set; } = "Neutral spell"; - public string CanBeAttackedHue { get; set; } = "Can be attacked hue"; - public string Murderer { get; set; } = "Murderer"; - public string Enemy { get; set; } = "Enemy"; - public string SpellOverheadFormat { get; set; } = "Spell overhead format"; - public string TooltipSpellFormat { get; set; } = "{power} for powerword, {spell} for spell name"; - } - - public class Counters - { - public string EnableCounters { get; set; } = "Enable counters"; - public string HighlightItemsOnUse { get; set; } = "Highlight items on use"; - public string AbbreviatedValues { get; set; } = "Abbreviated values"; - public string AbbreviateIfAmountExceeds { get; set; } = "Abbreviate if amount exceeds"; - public string HighlightRedWhenAmountIsLow { get; set; } = "Highlight red when amount is low"; - public string HighlightRedIfAmountIsBelow { get; set; } = "Highlight red if amount is below"; - public string CounterLayout { get; set; } = "Counter layout"; - public string GridSize { get; set; } = "Grid size"; - public string Rows { get; set; } = "Rows"; - public string Columns { get; set; } = "Columns"; - } - - public class InfoBars - { - public string ShowInfoBar { get; set; } = "Show info bar"; - public string HighlightType { get; set; } = "Highlight type"; - public string HighLightOpt_TextColor { get; set; } = "Text color"; - public string HighLightOpt_ColoredBars { get; set; } = "Colored bars"; - public string AddItem { get; set; } = "+ Add item"; - public string Hp { get; set; } = "HP"; - public string Label { get; set; } = "Label"; - public string Color { get; set; } = "Color"; - public string Data { get; set; } = "Data"; - } - - public class Containers - { - public string Description { get; set; } = "These settings are for original container gumps, for grid container settings visit the TazUO section"; - public string CharacterBackpackStyle { get; set; } = "Character backpack style"; - public string BackpackOpt_Default { get; set; } = "Default"; - public string BackpackOpt_Suede { get; set; } = "Suede"; - public string BackpackOpt_PolarBear { get; set; } = "Polar bear"; - public string BackpackOpt_GhoulSkin { get; set; } = "Ghoul skin"; - public string ContainerScale { get; set; } = "Container scale"; - public string AlsoScaleItems { get; set; } = "Also scale items"; - public string UseLargeContainerGumps { get; set; } = "Use large container gumps"; - public string DoubleClickToLootItemsInsideContainers { get; set; } = "Double click to loot items inside containers"; - public string RelativeDragAndDropItemsInContainers { get; set; } = "Relative drag and drop items in containers"; - public string HighlightContainerOnGroundWhenMouseIsOverAContainerGump { get; set; } = "Highlight container on ground when mouse is over a container gump"; - public string RecolorContainerGumpByWithContainerHue { get; set; } = "Recolor container gump by with container hue"; - public string OverrideContainerGumpLocations { get; set; } = "Override container gump locations"; - public string OverridePosition { get; set; } = "Override position"; - public string PositionOpt_NearContainer { get; set; } = "Near container"; - public string PositionOpt_TopRight { get; set; } = "Top right"; - public string PositionOpt_LastDraggedPosition { get; set; } = "Last dragged position"; - public string RememberEachContainer { get; set; } = "Remember each container"; - public string RebuildContainersTxt { get; set; } = "Rebuild containers.txt"; - } - - public class Experimental - { - public string DisableDefaultUoHotkeys { get; set; } = "Disable default UO hotkeys"; - public string DisableArrowsNumlockArrowsPlayerMovement { get; set; } = "Disable arrows & numlock arrows(player movement)"; - public string DisableTabToggleWarmode { get; set; } = "Disable tab (toggle warmode)"; - public string DisableCtrlQWMessageHistory { get; set; } = "Disable Ctrl + Q/W (message history)"; - public string DisableRightLeftClickAutoMove { get; set; } = "Disable right + left click auto move"; - } - - public class NamePlates - { - public string NewEntry { get; set; } = "New entry"; - public string NameOverheadEntryName { get; set; } = "Name overhead entry name"; - public string DeleteEntry { get; set; } = "Delete entry"; - } - - public class Cooldowns - { - public string CustomCooldownBars { get; set; } = "Custom cooldown bars"; - public string PositionX { get; set; } = "Position X"; - public string PositionY { get; set; } = "Position Y"; - public string UseLastMovedBarPosition { get; set; } = "Use last moved bar position"; - public string Conditions { get; set; } = "Conditions"; - public string AddCondition { get; set; } = "+ Add condition"; - } - - public class TazUO - { - #region General - public string GridContainers { get; set; } = "Grid containers"; - public string EnableGridContainers { get; set; } = "Enable grid containers"; - public string GridContainerScale { get; set; } = "Grid container scale"; - public string AlsoScaleItems { get; set; } = "Also scale items"; - public string GridItemBorderOpacity { get; set; } = "Grid item border opacity"; - public string BorderColor { get; set; } = "Border color"; - public string ContainerOpacity { get; set; } = "Container opacity"; - public string BackgroundColor { get; set; } = "Background color"; - public string UseContainersHue { get; set; } = "Use container's hue"; - public string SearchStyle { get; set; } = "Search style"; - public string OnlyShow { get; set; } = "Only show"; - public string Highlight { get; set; } = "Highlight"; - public string EnableContainerPreview { get; set; } = "Enable container preview"; - public string TooltipPreview { get; set; } = "This only works on containers that you have opened, otherwise the client does not have that information yet."; - public string MakeAnchorable { get; set; } = "Make anchorable"; - public string TooltipGridAnchor { get; set; } = "This will allow grid containers to be anchored to other containers/world map/journal"; - public string ContainerStyle { get; set; } = "Container style"; - public string HideBorders { get; set; } = "Hide borders"; - public string DefaultGridRows { get; set; } = "Default grid rows"; - public string DefaultGridColumns { get; set; } = "Default grid columns"; - public string GridHighlightSettings { get; set; } = "Grid highlight settings"; - public string GridHighlightSize { get; set; } = "Grid highlight size"; - #endregion - - #region Journal - public string Journal { get; set; } = "Journal"; - public string MaxJournalEntries { get; set; } = "Max journal entries"; - public string JournalOpacity { get; set; } = "Journal opacity"; - public string JournalBackgroundColor { get; set; } = "Background color"; - public string JournalStyle { get; set; } = "Journal style"; - public string JournalHideBorders { get; set; } = "Hide borders"; - public string HideTimestamp { get; set; } = "Hide timestamp"; - #endregion - - #region ModernPaperdoll - public string ModernPaperdoll { get; set; } = "Modern paperdoll"; - public string EnableModernPaperdoll { get; set; } = "Enable modern paperdoll"; - public string PaperdollHue { get; set; } = "Paperdoll hue"; - public string DurabilityBarHue { get; set; } = "Durability bar hue"; - public string ShowDurabilityBarBelow { get; set; } = "Show durability bar below %"; - #endregion - - #region Nameplates - public string Nameplates { get; set; } = "Nameplates"; - public string NameplatesAlsoActAsHealthBars { get; set; } = "Nameplates also act as health bars"; - public string HpOpacity { get; set; } = "HP opacity"; - public string HideNameplatesIfFullHealth { get; set; } = "Hide nameplates if full health"; - public string OnlyInWarmode { get; set; } = "Only in warmode"; - public string BorderOpacity { get; set; } = "Border opacity"; - public string BackgroundOpacity { get; set; } = "Background opacity"; - #endregion - - #region Mobile - public string Mobiles { get; set; } = "Mobiles"; - public string DamageToSelf { get; set; } = "Damage to self"; - public string DamageToOthers { get; set; } = "Damage to others"; - public string DamageToPets { get; set; } = "Damage to pets"; - public string DamageToAllies { get; set; } = "Damage to allies"; - public string DamageToLastAttack { get; set; } = "Damage to last attack"; - public string DisplayPartyChatOverPlayerHeads { get; set; } = "Display party chat over player heads"; - public string TooltipPartyChat { get; set; } = "If a party member uses party chat their text will also show above their head to you"; - public string OverheadTextWidth { get; set; } = "Overhead text width"; - public string TooltipOverheadText { get; set; } = "This adjusts the maximum width for text over players, setting to 0 will allow it to use any width needed to stay one line"; - public string BelowMobileHealthBarScale { get; set; } = "Below mobile health bar scale"; - public string AutomaticallyOpenHealthBarsForLastAttack { get; set; } = "Automatically open health bars for last attack"; - public string UpdateOneBarAsLastAttack { get; set; } = "Update one bar as last attack"; - public string HiddenPlayerOpacity { get; set; } = "Hidden player opacity"; - public string HiddenPlayerHue { get; set; } = "Hidden player hue"; - public string RegularPlayerOpacity { get; set; } = "Regular player opacity"; - public string AutoFollowDistance { get; set; } = "Auto follow distance"; - public string DisableMouseInteractionsForOverheadText { get; set; } = "Disable mouse interactions for overhead text"; - public string OverridePartyMemberHues { get; set; } = "Override party member body hues with friendly hue"; - #endregion - - #region Misc - public string Misc { get; set; } = "Misc"; - public string DisableSystemChat { get; set; } = "Disable system chat"; - public string EnableImprovedBuffGump { get; set; } = "Enable improved buff gump"; - public string BuffGumpHue { get; set; } = "Buff gump hue"; - public string MainGameWindowBackground { get; set; } = "Main game window background"; - public string EnableHealthIndicatorBorder { get; set; } = "Enable health indicator border"; - public string OnlyShowBelowHp { get; set; } = "Only show below hp %"; - public string Size { get; set; } = "Size"; - public string SpellIconScale { get; set; } = "Spell icon scale"; - public string DisplayMatchingHotkeysOnSpellIcons { get; set; } = "Display matching hotkeys on spell icons"; - public string HotkeyTextHue { get; set; } = "Hotkey text hue"; - public string EnableGumpOpacityAdjustViaAltScroll { get; set; } = "Enable gump opacity adjust via Alt + Scroll"; - public string EnableAdvancedShopGump { get; set; } = "Enable advanced shop gump"; - public string DisplaySkillProgressBarOnSkillChanges { get; set; } = "Display skill progress bar on skill changes"; - public string TextFormat { get; set; } = "Text format"; - public string EnableSpellIndicatorSystem { get; set; } = "Enable spell indicator system"; - public string ImportFromUrl { get; set; } = "Import from url"; - public string InputRequestUrl { get; set; } = "Enter the url for the spell config. /c[red]This will override your current config."; - public string Download { get; set; } = "Download"; - public string Cancel { get; set; } = "Cancel"; - public string AttemptingToDownloadSpellConfig { get; set; } = "Attempting to download spell config.."; - public string SuccesfullyDownloadedNewSpellConfig { get; set; } = "Succesfully downloaded new spell config."; - public string FailedToDownloadTheSpellConfigExMessage { get; set; } = "Failed to download the spell config. ({0})"; - public string AlsoCloseAnchoredHealthbarsWhenAutoClosingHealthbars { get; set; } = "Also close anchored healthbars when auto closing healthbars"; - public string EnableAutoResyncOnHangDetection { get; set; } = "Enable auto resync on hang detection"; - public string PlayerOffsetX { get; set; } = "Player Offset X"; - public string PlayerOffsetY { get; set; } = "Player Offset Y"; - public string UseLandTexturesWhereAvailable { get; set; } = "Use land textures where available(Experimental)"; - public string SOSGumpID { get; set; } = "SOS Gump ID"; - #endregion - - #region Tooltips - public string Tooltips { get; set; } = "Tooltips"; - public string AlignTooltipsToTheLeftSide { get; set; } = "Align tooltips to the left side"; - public string AlignMobileTooltipsToCenter { get; set; } = "Align mobile tooltips to center"; - public string BackgroundHue { get; set; } = "Background hue"; - public string HeaderFormatItemName { get; set; } = "Header format(Item name)"; - public string TooltipOverrideSettings { get; set; } = "Tooltip override settings"; - #endregion - - #region Fontsettings - public string FontSettings { get; set; } = "Font settings"; - public string TtfFontBorder { get; set; } = "TTF Font border"; - public string InfobarFont { get; set; } = "Infobar font"; - public string SharedSize { get; set; } = "Size"; - public string SystemChatFont { get; set; } = "System chat font"; - public string TooltipFont { get; set; } = "Tooltip font"; - public string OverheadFont { get; set; } = "Overhead font"; - public string JournalFont { get; set; } = "Journal font"; - #endregion - - #region Controller - public string Controller { get; set; } = "Controller"; - public string MouseSesitivity { get; set; } = "Mouse Sensitivity"; - #endregion - - #region SettingsTransfer - public string SettingsTransfers { get; set; } = "Settings transfers"; - public string SettingsWarning { get; set; } = "/es/c[red]! Warning !/cd\n" + - "This will override other character's profile options!\n" + - "This is not reversable!\n" + - "You have {0} other profiles that will may overridden with the settings in this profile.\n\n" + - "This will not override: Macros, skill groups, info bar, grid container data, or gump saved positions."; - public string OverrideAll { get; set; } = "Override {0} other profiles with this one."; - public string OverrideSuccess { get; set; } = "{0} profiles overriden."; - public string OverrideSame { get; set; } = "Override {0} other profiles on this same server with this one."; - #endregion - - #region GumpScaling - public string GumpScaling { get; set; } = "Gump scaling"; - public string ScalingInfo { get; set; } = "Some of these settings may only take effect after closing and reopening. Visual bugs may occur until the gump is closed and reopened."; - public string PaperdollGump { get; set; } = "Paperdoll Gump"; - #endregion - - public string AutoLoot { get; set; } = "Autoloot"; - - #region VisibileLayers - public string VisibleLayers { get; set; } = "Visible Layers"; - public string VisLayersInfo { get; set; } = "These settings are to hide layers on in-game mobiles. Check the box to hide that layer."; - public string OnlyForYourself { get; set; } = "Only for yourself"; - #endregion - } - } - - public class ErrorsLanguage - { - public string CommandNotFound { get; set; } = "Command was not found: {0}"; - } - - public class MapLanguage - { - public string Follow { get; set; } = "Follow"; - public string Yourself { get; set; } = "Yourself"; - } -} diff --git a/src/ClassicUO.Client/Configuration/Profile.cs b/src/ClassicUO.Client/Configuration/Profile.cs deleted file mode 100644 index e4b45057c..000000000 --- a/src/ClassicUO.Client/Configuration/Profile.cs +++ /dev/null @@ -1,1074 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration.Json; -using ClassicUO.Game; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Utility.Logging; -using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Xml; - -namespace ClassicUO.Configuration -{ - //[JsonSourceGenerationOptions(WriteIndented = true, PropertyNamingPolicy = JsonKnownNamingPolicy.Unspecified)] - [JsonSerializable(typeof(Profile), GenerationMode = JsonSourceGenerationMode.Metadata)] - sealed partial class ProfileJsonContext : JsonSerializerContext - { - sealed class SnakeCaseNamingPolicy : JsonNamingPolicy - { - public static SnakeCaseNamingPolicy Instance { get; } = new SnakeCaseNamingPolicy(); - - public override string ConvertName(string name) - { - // Conversion to other naming convention goes here. Like SnakeCase, KebabCase etc. - return string.Concat(name.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower(); - } - } - - private static Lazy _jsonOptions { get; } = new Lazy(() => - { - var options = new JsonSerializerOptions(); - options.WriteIndented = true; - options.PropertyNamingPolicy = SnakeCaseNamingPolicy.Instance; - return options; - }); - - public static ProfileJsonContext DefaultToUse { get; } = new ProfileJsonContext(_jsonOptions.Value); - } - - - - public sealed class Profile - { - [JsonIgnore] public string Username { get; set; } - [JsonIgnore] public string ServerName { get; set; } - [JsonIgnore] public string CharacterName { get; set; } - - // sounds - public bool EnableSound { get; set; } = true; - public int SoundVolume { get; set; } = 100; - public bool EnableMusic { get; set; } = true; - public int MusicVolume { get; set; } = 100; - public bool EnableFootstepsSound { get; set; } = true; - public bool EnableCombatMusic { get; set; } = true; - public bool ReproduceSoundsInBackground { get; set; } - - // fonts and speech - public byte ChatFont { get; set; } = 1; - public int SpeechDelay { get; set; } = 100; - public bool ScaleSpeechDelay { get; set; } = true; - public bool SaveJournalToFile { get; set; } = false; - public bool ForceUnicodeJournal { get; set; } - public bool IgnoreAllianceMessages { get; set; } - public bool IgnoreGuildMessages { get; set; } - - // hues - public ushort SpeechHue { get; set; } = 0x02B2; - public ushort WhisperHue { get; set; } = 0x0033; - public ushort EmoteHue { get; set; } = 0x0021; - public ushort YellHue { get; set; } = 0x0021; - public ushort PartyMessageHue { get; set; } = 0x0044; - public ushort GuildMessageHue { get; set; } = 0x0044; - public ushort AllyMessageHue { get; set; } = 0x0057; - public ushort ChatMessageHue { get; set; } = 0x0256; - public ushort InnocentHue { get; set; } = 0x005A; - public ushort PartyAuraHue { get; set; } = 0x0044; - public ushort FriendHue { get; set; } = 0x0044; - public ushort CriminalHue { get; set; } = 0x03B2; - public ushort CanAttackHue { get; set; } = 0x03B2; - public ushort EnemyHue { get; set; } = 0x0031; - public ushort MurdererHue { get; set; } = 0x0023; - public ushort BeneficHue { get; set; } = 0x0059; - public ushort HarmfulHue { get; set; } = 0x0020; - public ushort NeutralHue { get; set; } = 0x03B1; - public bool EnabledSpellHue { get; set; } - public bool EnabledSpellFormat { get; set; } - public string SpellDisplayFormat { get; set; } = "{power} [{spell}]"; - public ushort PoisonHue { get; set; } = 0x0044; - public ushort ParalyzedHue { get; set; } = 0x014C; - public ushort InvulnerableHue { get; set; } = 0x0030; - public ushort AltJournalBackgroundHue { get; set; } = 0x0000; - public ushort AltGridContainerBackgroundHue { get; set; } = 0x0000; - public bool OverridePartyAndGuildHue { get; set; } = false; - - // visual - public bool EnabledCriminalActionQuery { get; set; } = true; - public bool EnabledBeneficialCriminalActionQuery { get; set; } = false; - public bool EnableStatReport { get; set; } = true; - public bool EnableSkillReport { get; set; } = true; - public bool UseOldStatusGump { get; set; } - public int BackpackStyle { get; set; } - public bool HighlightGameObjects { get; set; } - public bool HighlightMobilesByParalize { get; set; } = true; - public bool HighlightMobilesByPoisoned { get; set; } = true; - public bool HighlightMobilesByInvul { get; set; } = true; - public bool ShowMobilesHP { get; set; } - public int MobileHPType { get; set; } // 0 = %, 1 = line, 2 = both - public int MobileHPShowWhen { get; set; } // 0 = Always, 1 - <100% - public bool DrawRoofs { get; set; } = true; - public bool TreeToStumps { get; set; } - public bool EnableCaveBorder { get; set; } - public bool HideVegetation { get; set; } - public int FieldsType { get; set; } // 0 = normal, 1 = static, 2 = tile - public bool NoColorObjectsOutOfRange { get; set; } - public bool UseCircleOfTransparency { get; set; } - public int CircleOfTransparencyRadius { get; set; } = Constants.MAX_CIRCLE_OF_TRANSPARENCY_RADIUS / 2; - public int CircleOfTransparencyType { get; set; } // 0 = normal, 1 = like original client - public int VendorGumpHeight { get; set; } = 60; //original vendor gump size - public float DefaultScale { get; set; } = 1.0f; - public bool EnableMousewheelScaleZoom { get; set; } - public bool SaveScaleAfterClose { get; set; } - public bool RestoreScaleAfterUnpressCtrl { get; set; } - public bool BandageSelfOld { get; set; } = true; - public bool EnableDeathScreen { get; set; } = true; - public bool EnableBlackWhiteEffect { get; set; } = true; - public ushort HiddenBodyHue { get; set; } = 0x038E; - public byte HiddenBodyAlpha { get; set; } = 40; - public int PlayerConstantAlpha { get; set; } = 100; - - // tooltip - public bool UseTooltip { get; set; } = true; - public ushort TooltipTextHue { get; set; } = 0xFFFF; - public int TooltipDelayBeforeDisplay { get; set; } = 250; - public int TooltipDisplayZoom { get; set; } = 100; - public int TooltipBackgroundOpacity { get; set; } = 70; - public byte TooltipFont { get; set; } = 1; - - // movements - public bool EnablePathfind { get; set; } - public bool UseShiftToPathfind { get; set; } - public bool PathfindSingleClick { get; set; } - public bool AlwaysRun { get; set; } - public bool AlwaysRunUnlessHidden { get; set; } - public bool SmoothMovements { get; set; } = true; - public bool HoldDownKeyTab { get; set; } = true; - public bool HoldShiftForContext { get; set; } = false; - public bool HoldShiftToSplitStack { get; set; } = false; - - // general - [JsonConverter(typeof(Point2Converter))] public Point WindowClientBounds { get; set; } = new Point(600, 480); - [JsonConverter(typeof(Point2Converter))] public Point ContainerDefaultPosition { get; set; } = new Point(24, 24); - [JsonConverter(typeof(Point2Converter))] public Point GameWindowPosition { get; set; } = new Point(10, 10); - public bool GameWindowLock { get; set; } - public bool GameWindowFullSize { get; set; } - public bool WindowBorderless { get; set; } = false; - [JsonConverter(typeof(Point2Converter))] public Point GameWindowSize { get; set; } = new Point(600, 480); - [JsonConverter(typeof(Point2Converter))] public Point TopbarGumpPosition { get; set; } = new Point(0, 0); - public bool TopbarGumpIsMinimized { get; set; } - public bool TopbarGumpIsDisabled { get; set; } - public bool UseAlternativeLights { get; set; } - public bool UseCustomLightLevel { get; set; } - public byte LightLevel { get; set; } - public int LightLevelType { get; set; } // 0 = absolute, 1 = minimum - public bool UseColoredLights { get; set; } = true; - public bool UseDarkNights { get; set; } - public int CloseHealthBarType { get; set; } // 0 = none, 1 == not exists, 2 == is dead - public bool ActivateChatAfterEnter { get; set; } - public bool ActivateChatAdditionalButtons { get; set; } = true; - public bool ActivateChatShiftEnterSupport { get; set; } = true; - public bool UseObjectsFading { get; set; } = true; - public bool HoldDownKeyAltToCloseAnchored { get; set; } = true; - public bool CloseAllAnchoredGumpsInGroupWithRightClick { get; set; } = false; - public bool HoldAltToMoveGumps { get; set; } - public byte JournalOpacity { get; set; } = 50; - public int JournalStyle { get; set; } = 0; - public bool HideScreenshotStoredInMessage { get; set; } - public bool UseModernPaperdoll { get; set; } = false; - public bool OpenModernPaperdollAtMinimizeLoc { get; set; } = false; - - // Experimental - public bool CastSpellsByOneClick { get; set; } - public bool BuffBarTime { get; set; } - public bool FastSpellsAssign { get; set; } - public bool AutoOpenDoors { get; set; } - public bool SmoothDoors { get; set; } - public bool AutoOpenCorpses { get; set; } - public int AutoOpenCorpseRange { get; set; } = 2; - public int CorpseOpenOptions { get; set; } = 3; - public bool SkipEmptyCorpse { get; set; } - public bool DisableDefaultHotkeys { get; set; } - public bool DisableArrowBtn { get; set; } - public bool DisableTabBtn { get; set; } - public bool DisableCtrlQWBtn { get; set; } - public bool DisableAutoMove { get; set; } - public bool EnableDragSelect { get; set; } - public int DragSelectModifierKey { get; set; } // 0 = none, 1 = control, 2 = shift - public int DragSelect_PlayersModifier { get; set; } = 0; - public int DragSelect_MonstersModifier { get; set; } = 0; - public int DragSelect_NameplateModifier { get; set; } = 0; - public bool OverrideContainerLocation { get; set; } - - public int OverrideContainerLocationSetting { get; set; } // 0 = container position, 1 = top right of screen, 2 = last dragged position, 3 = remember every container - - [JsonConverter(typeof(Point2Converter))] public Point OverrideContainerLocationPosition { get; set; } = new Point(200, 200); - public bool HueContainerGumps { get; set; } = true; - public bool DragSelectHumanoidsOnly { get; set; } - public int DragSelectStartX { get; set; } = 100; - public int DragSelectStartY { get; set; } = 100; - public bool DragSelectAsAnchor { get; set; } = false; - public string LastActiveNameOverheadOption { get; set; } = "All"; - public bool NameOverheadToggled { get; set; } = false; - public bool ShowTargetRangeIndicator { get; set; } - public bool PartyInviteGump { get; set; } - public bool CustomBarsToggled { get; set; } - public bool CBBlackBGToggled { get; set; } - - public bool ShowInfoBar { get; set; } - public int InfoBarHighlightType { get; set; } // 0 = text colour changes, 1 = underline - - public bool CounterBarEnabled { get; set; } - public bool CounterBarHighlightOnUse { get; set; } - public bool CounterBarHighlightOnAmount { get; set; } - public bool CounterBarDisplayAbbreviatedAmount { get; set; } - public int CounterBarAbbreviatedAmount { get; set; } = 1000; - public int CounterBarHighlightAmount { get; set; } = 5; - public int CounterBarCellSize { get; set; } = 40; - public int CounterBarRows { get; set; } = 1; - public int CounterBarColumns { get; set; } = 1; - - public bool ShowSkillsChangedMessage { get; set; } = true; - public int ShowSkillsChangedDeltaValue { get; set; } = 1; - public bool ShowStatsChangedMessage { get; set; } = true; - - - public bool ShadowsEnabled { get; set; } = true; - public bool ShadowsStatics { get; set; } = true; - public int TerrainShadowsLevel { get; set; } = 15; - public int AuraUnderFeetType { get; set; } // 0 = NO, 1 = in warmode, 2 = ctrl+shift, 3 = always - public bool AuraOnMouse { get; set; } = true; - public bool AnimatedWaterEffect { get; set; } = false; - - public bool PartyAura { get; set; } - - public bool UseXBR { get; set; } = true; - - public bool HideChatGradient { get; set; } = false; - - public bool StandardSkillsGump { get; set; } = true; - - public bool ShowNewMobileNameIncoming { get; set; } = true; - public bool ShowNewCorpseNameIncoming { get; set; } = true; - - public uint GrabBagSerial { get; set; } - - public int GridLootType { get; set; } // 0 = none, 1 = only grid, 2 = both - - public bool ReduceFPSWhenInactive { get; set; } = true; - - public bool OverrideAllFonts { get; set; } - public bool OverrideAllFontsIsUnicode { get; set; } = true; - - public bool SallosEasyGrab { get; set; } - - public bool JournalDarkMode { get; set; } - - public byte ContainersScale { get; set; } = 100; - - public byte ContainerOpacity { get; set; } = 50; - - public bool ScaleItemsInsideContainers { get; set; } - - public bool DoubleClickToLootInsideContainers { get; set; } - - public bool UseLargeContainerGumps { get; set; } = false; - - public bool RelativeDragAndDropItems { get; set; } - - public bool HighlightContainerWhenSelected { get; set; } - - public bool ShowHouseContent { get; set; } - public bool SaveHealthbars { get; set; } - public bool TextFading { get; set; } = true; - - public bool UseSmoothBoatMovement { get; set; } = false; - - public bool IgnoreStaminaCheck { get; set; } = false; - - public bool ShowJournalClient { get; set; } = true; - public bool ShowJournalObjects { get; set; } = true; - public bool ShowJournalSystem { get; set; } = true; - public bool ShowJournalGuildAlly { get; set; } = true; - - public int WorldMapWidth { get; set; } = 400; - public int WorldMapHeight { get; set; } = 400; - public int WorldMapFont { get; set; } = 3; - public bool WorldMapFlipMap { get; set; } = true; - public bool WorldMapTopMost { get; set; } - public bool WorldMapFreeView { get; set; } - public bool WorldMapShowParty { get; set; } = true; - public int WorldMapZoomIndex { get; set; } = 4; - public bool WorldMapShowCoordinates { get; set; } = true; - public bool WorldMapShowMouseCoordinates { get; set; } = true; - public bool WorldMapShowCorpse { get; set; } = true; - public bool WorldMapShowMobiles { get; set; } = true; - public bool WorldMapShowPlayerName { get; set; } = true; - public bool WorldMapShowPlayerBar { get; set; } = true; - public bool WorldMapShowGroupName { get; set; } = true; - public bool WorldMapShowGroupBar { get; set; } = true; - public bool WorldMapShowMarkers { get; set; } = true; - public bool WorldMapShowMarkersNames { get; set; } = true; - public bool WorldMapShowMultis { get; set; } = true; - public string WorldMapHiddenMarkerFiles { get; set; } = string.Empty; - public string WorldMapHiddenZoneFiles { get; set; } = string.Empty; - public bool WorldMapShowGridIfZoomed { get; set; } = true; - public bool WorldMapAllowPositionalTarget { get; set; } = true; - - public int AutoFollowDistance { get; set; } = 2; - [JsonConverter(typeof(Point2Converter))] public Point ResizeJournalSize { get; set; } = new Point(410, 350); - public bool FollowingMode { get; set; } = false; - public uint FollowingTarget { get; set; } - public bool NamePlateHealthBar { get; set; } = true; - public byte NamePlateOpacity { get; set; } = 75; - public byte NamePlateHealthBarOpacity { get; set; } = 50; - public bool NamePlateHideAtFullHealth { get; set; } = true; - public bool NamePlateHideAtFullHealthInWarmode { get; set; } = true; - public byte NamePlateBorderOpacity { get; set; } = 50; - - public bool LeftAlignToolTips { get; set; } = false; - public bool ForceCenterAlignTooltipMobiles { get; set; } = false; - - public bool CorpseSingleClickLoot { get; set; } = false; - - public bool DisableSystemChat { get; set; } = false; - - #region GRID CONTAINER - public bool UseGridLayoutContainerGumps { get; set; } = true; - public int GridContainerSearchMode { get; set; } = 1; - public bool EnableGridContainerAnchor { get; set; } = false; - public byte GridBorderAlpha { get; set; } = 75; - public ushort GridBorderHue { get; set; } = 0; - public byte GridContainersScale { get; set; } = 100; - public bool GridContainerScaleItems { get; set; } = true; - public bool GridEnableContPreview { get; set; } = true; - public int Grid_BorderStyle { get; set; } = 0; - public int Grid_DefaultColumns { get; set; } = 4; - public int Grid_DefaultRows { get; set; } = 4; - public bool Grid_UseContainerHue { get; set; } = false; - public bool Grid_HideBorder { get; set; } = false; - #endregion - - #region COOLDOWNS - public int CoolDownX { get; set; } = 50; - public int CoolDownY { get; set; } = 50; - - public List Condition_Hue { get; set; } = new List(); - public List Condition_Label { get; set; } = new List(); - public List Condition_Duration { get; set; } = new List(); - public List Condition_Trigger { get; set; } = new List(); - public List Condition_Type { get; set; } = new List(); - public List Condition_ReplaceIfExists { get; set; } = new List(); - public int CoolDownConditionCount - { - get - { - return Condition_Hue.Count; - } - set { } - } - #endregion - - #region IMPROVED BUFF BAR - public bool UseImprovedBuffBar { get; set; } = true; - public ushort ImprovedBuffBarHue { get; set; } = 905; - #endregion - - #region DAMAGE NUMBER HUES - public ushort DamageHueSelf { get; set; } = 0x0034; - public ushort DamageHuePet { get; set; } = 0x0033; - public ushort DamageHueAlly { get; set; } = 0x0030; - public ushort DamageHueLastAttck { get; set; } = 0x1F; - public ushort DamageHueOther { get; set; } = 0x0021; - #endregion - - #region GridHighlightingProps - public List GridHighlight_Name { get; set; } = new List(); - public List GridHighlight_Hue { get; set; } = new List(); - public List> GridHighlight_PropNames { get; set; } = new List>(); - public List> GridHighlight_PropMinVal { get; set; } = new List>(); - public bool GridHighlight_CorpseOnly { get; set; } = false; - public int GridHightlightSize { get; set; } = 1; - #endregion - - #region Modern paperdoll - public ushort ModernPaperDollHue { get; set; } = 0; - public ushort ModernPaperDollDurabilityHue { get; set; } = 32; - public int ModernPaperDoll_DurabilityPercent { get; set; } = 90; - [JsonConverter(typeof(Point2Converter))] public Point ModernPaperdollPosition { get; set; } = new Point(100, 100); - #endregion - - #region Health indicator - public float ShowHealthIndicatorBelow { get; set; } = 0.9f; - public bool EnableHealthIndicator { get; set; } = true; - public int HealthIndicatorWidth { get; set; } = 10; - #endregion - - public ushort MainWindowBackgroundHue { get; set; } = 1; - - public int MoveMultiObjectDelay { get; set; } = 1000; - - public bool SpellIcon_DisplayHotkey { get; set; } = true; - public ushort SpellIcon_HotkeyHue { get; set; } = 1; - - public int SpellIconScale { get; set; } = 100; - - public bool EnableAlphaScrollingOnGumps { get; set; } = true; - - [JsonConverter(typeof(Point2Converter))] public Point WorldMapPosition { get; set; } = new Point(100, 100); - [JsonConverter(typeof(Point2Converter))] public Point PaperdollPosition { get; set; } = new Point(100, 100); - [JsonConverter(typeof(Point2Converter))] public Point JournalPosition { get; set; } = new Point(100, 100); - [JsonConverter(typeof(Point2Converter))] public Point StatusGumpPosition { get; set; } = new Point(100, 100); - [JsonConverter(typeof(Point2Converter))] public Point BackpackGridPosition { get; set; } = new Point(100, 100); - [JsonConverter(typeof(Point2Converter))] public Point BackpackGridSize { get; set; } = new Point(300, 300); - public bool WorldMapLocked { get; set; } = false; - public bool PaperdollLocked { get; set; } = false; - public bool JournalLocked { get; set; } = false; - public bool StatusGumpLocked { get; set; } = false; - public bool BackPackLocked { get; set; } = false; - - public bool DisplayPartyChatOverhead { get; set; } = true; - - public string SelectedTTFJournalFont { get; set; } = "avadonian"; - public int SelectedJournalFontSize { get; set; } = 20; - - public string SelectedToolTipFont { get; set; } = "Roboto-Regular"; - public int SelectedToolTipFontSize { get; set; } = 20; - - public string GameWindowSideChatFont { get; set; } = "avadonian"; - public int GameWindowSideChatFontSize { get; set; } = 20; - - public string OverheadChatFont { get; set; } = "avadonian"; - public int OverheadChatFontSize { get; set; } = 20; - public int OverheadChatWidth { get; set; } = 200; - - public string DefaultTTFFont { get; set; } = "Roboto-Regular"; - public int TextBorderSize { get; set; } = 1; - - public bool UseModernShopGump { get; set; } = false; - - public int MaxJournalEntries { get; set; } = 750; - public bool HideJournalBorder { get; set; } = false; - public bool HideJournalTimestamp { get; set; } = false; - - public int HealthLineSizeMultiplier { get; set; } = 1; - - public bool OpenHealthBarForLastAttack { get; set; } = true; - [JsonConverter(typeof(Point2Converter))] - public Point LastTargetHealthBarPos { get; set; } = Point.Zero; - public ushort ToolTipBGHue { get; set; } = 0; - - public string LastVersionHistoryShown { get; set; } - - public int AdvancedSkillsGumpHeight { get; set; } = 310; - - #region ToolTip Overrides - public List ToolTipOverride_SearchText { get; set; } = new List() { "Physical Res", "Fire Res", "Cold Res", "Poison Res", "Energy Res" }; - public List ToolTipOverride_NewFormat { get; set; } = new List() { "/c[#5f423c]Physical Resist {1}%", "/c[red]Fire Resist {1}%", "/c[blue]Cold Resist {1}%", "/c[green]Poison Resist {1}%", "/c[purple]Energy Resist {1}%" }; - public List ToolTipOverride_MinVal1 { get; set; } = new List() { -1, -1, -1, -1, -1 }; - public List ToolTipOverride_MinVal2 { get; set; } = new List() { -1, -1, -1, -1, -1 }; - public List ToolTipOverride_MaxVal1 { get; set; } = new List() { 100, 100, 100, 100, 100 }; - public List ToolTipOverride_MaxVal2 { get; set; } = new List() { 100, 100, 100, 100, 100 }; - public List ToolTipOverride_Layer { get; set; } = new List() { (byte)TooltipLayers.Any, (byte)TooltipLayers.Any, (byte)TooltipLayers.Any, (byte)TooltipLayers.Any, (byte)TooltipLayers.Any }; - #endregion - - public string TooltipHeaderFormat { get; set; } = "/c[yellow]{0}"; - - public bool DisplaySkillBarOnChange { get; set; } = true; - public string SkillBarFormat { get; set; } = "{0}: {1} / {2}"; - - public bool DisplayRadius { get; set; } = false; - public int DisplayRadiusDistance { get; set; } = 10; - public ushort DisplayRadiusHue { get; set; } = 22; - - public bool EnableSpellIndicators { get; set; } = true; - - public bool EnableAutoLoot { get; set; } = false; - - public static uint GumpsVersion { get; private set; } - - [JsonConverter(typeof(Point2Converter))] - public Point InfoBarSize { get; set; } = new Point(400, 20); - public bool InfoBarLocked { get; set; } = false; - public string InfoBarFont { get; set; } = "Roboto-Regular"; - public int InfoBarFontSize { get; set; } = 18; - - public int LastJournalTab { get; set; } = 0; - public Dictionary JournalTabs { get; set; } = new Dictionary() - { - { "All", new MessageType[] { - MessageType.Alliance, MessageType.Command, MessageType.Emote, - MessageType.Encoded, MessageType.Focus, MessageType.Guild, - MessageType.Label, MessageType.Limit3Spell, MessageType.Party, - MessageType.Regular, MessageType.Spell, MessageType.System, - MessageType.Whisper, MessageType.Yell, MessageType.ChatSystem } - }, - { "Chat", new MessageType[] { - MessageType.Regular, - MessageType.Guild, - MessageType.Alliance, - MessageType.Emote, - MessageType.Party, - MessageType.Whisper, - MessageType.Yell, - MessageType.ChatSystem } - }, - { - "Guild|Party", new MessageType[] { - MessageType.Guild, - MessageType.Alliance, - MessageType.Party } - }, - { - "System", new MessageType[] { - MessageType.System } - } - }; - - public bool UseLastMovedCooldownPosition { get; set; } = false; - public bool CloseHealthBarIfAnchored { get; set; } = false; - - [JsonConverter(typeof(Point2Converter))] - public Point SkillProgressBarPosition { get; set; } = Point.Zero; - - public bool ForceResyncOnHang { get; set; } = false; - - public bool UseOneHPBarForLastAttack { get; set; } = false; - - public bool DisableMouseInteractionOverheadText { get; set; } = false; - - public List HiddenLayers { get; set; } = new List(); - public bool HideLayersForSelf { get; set; } = true; - - public List AutoOpenXmlGumps { get; set; } = new List(); - - public int ControllerMouseSensativity { get => Input.Mouse.ControllerSensativity; set => Input.Mouse.ControllerSensativity = value; } - - [JsonConverter(typeof(Point2Converter))] - public Point PlayerOffset { get; set; } = new Point(0, 0); - - public bool UseLandTextures { get; set; } = false; - - public double PaperdollScale { get; set; } = 1f; - - public uint SOSGumpID { get; set; } = 1915258020; - - - public void Save(string path, bool saveGumps = true) - { - Log.Trace($"Saving path:\t\t{path}"); - - // Save profile settings - ConfigurationResolver.Save(this, Path.Combine(path, "profile.json"), ProfileJsonContext.DefaultToUse); - - // Save opened gumps - if (saveGumps) - SaveGumps(path); - - Log.Trace("Saving done!"); - } - - private void SaveGumps(string path) - { - string gumpsXmlPath = Path.Combine(path, "gumps.xml"); - - using (XmlTextWriter xml = new XmlTextWriter(gumpsXmlPath, Encoding.UTF8) - { - Formatting = Formatting.Indented, - IndentChar = '\t', - Indentation = 1 - }) - { - xml.WriteStartDocument(true); - xml.WriteStartElement("gumps"); - - UIManager.AnchorManager.Save(xml); - - LinkedList gumps = new LinkedList(); - - foreach (Gump gump in UIManager.Gumps) - { - if (!gump.IsDisposed && gump.CanBeSaved && !(gump is AnchorableGump anchored && UIManager.AnchorManager[anchored] != null)) - { - gumps.AddLast(gump); - } - } - - LinkedListNode first = gumps.First; - - while (first != null) - { - Gump gump = first.Value; - - if (gump.LocalSerial != 0) - { - Item item = World.Items.Get(gump.LocalSerial); - - if (item != null && !item.IsDestroyed && item.Opened) - { - while (SerialHelper.IsItem(item.Container)) - { - item = World.Items.Get(item.Container); - } - - SaveItemsGumpRecursive(item, xml, gumps); - - if (first.List != null) - { - gumps.Remove(first); - } - - first = gumps.First; - - continue; - } - } - - xml.WriteStartElement("gump"); - gump.Save(xml); - xml.WriteEndElement(); - - if (first.List != null) - { - gumps.Remove(first); - } - - first = gumps.First; - } - - xml.WriteEndElement(); - xml.WriteEndDocument(); - } - - - SkillsGroupManager.Save(); - } - - private static void SaveItemsGumpRecursive(Item parent, XmlTextWriter xml, LinkedList list) - { - if (parent != null && !parent.IsDestroyed && parent.Opened) - { - SaveItemsGump(parent, xml, list); - - Item first = (Item)parent.Items; - - while (first != null) - { - Item next = (Item)first.Next; - - SaveItemsGumpRecursive(first, xml, list); - - first = next; - } - } - } - - private static void SaveItemsGump(Item item, XmlTextWriter xml, LinkedList list) - { - if (item != null && !item.IsDestroyed && item.Opened) - { - LinkedListNode first = list.First; - - while (first != null) - { - LinkedListNode next = first.Next; - - if (first.Value.LocalSerial == item.Serial && !first.Value.IsDisposed) - { - xml.WriteStartElement("gump"); - first.Value.Save(xml); - xml.WriteEndElement(); - - list.Remove(first); - - break; - } - - first = next; - } - } - } - - - public List ReadGumps(string path) - { - List gumps = new List(); - - // load skillsgroup - SkillsGroupManager.Load(); - - // load gumps - string gumpsXmlPath = Path.Combine(path, "gumps.xml"); - - if (File.Exists(gumpsXmlPath)) - { - XmlDocument doc = new XmlDocument(); - - try - { - doc.Load(gumpsXmlPath); - } - catch (Exception ex) - { - Log.Error(ex.ToString()); - - return gumps; - } - - XmlElement root = doc["gumps"]; - - if (root != null) - { - int pdolc = 0; - - foreach (XmlElement xml in root.ChildNodes /*.GetElementsByTagName("gump")*/) - { - if (xml.Name != "gump") - { - continue; - } - - try - { - GumpType type = (GumpType)int.Parse(xml.GetAttribute(nameof(type))); - int x = int.Parse(xml.GetAttribute(nameof(x))); - int y = int.Parse(xml.GetAttribute(nameof(y))); - uint serial = uint.Parse(xml.GetAttribute(nameof(serial))); - - if (uint.TryParse(xml.GetAttribute("serverSerial"), out uint serverSerial)) - { - UIManager.SavePosition(serverSerial, new Point(x, y)); - } - - Gump gump = null; - - switch (type) - { - case GumpType.Buff: - if (ProfileManager.CurrentProfile.UseImprovedBuffBar) - gump = new ImprovedBuffGump(); - else - gump = new BuffGump(100, 100); - - break; - - case GumpType.Container: - gump = new ContainerGump(); - - break; - - case GumpType.CounterBar: - gump = new CounterBarGump(); - - break; - - case GumpType.HealthBar: - if (CustomBarsToggled) - { - gump = new HealthBarGumpCustom(); - } - else - { - gump = new HealthBarGump(); - } - - break; - - case GumpType.InfoBar: - gump = new InfoBarGump(); - - break; - - case GumpType.Journal: - //gump = new JournalGump(); - gump = new ResizableJournal(); - x = ProfileManager.CurrentProfile.JournalPosition.X; - y = ProfileManager.CurrentProfile.JournalPosition.Y; - break; - - case GumpType.MacroButton: - gump = new MacroButtonGump(); - - break; - case GumpType.MacroButtonEditor: - gump = new MacroButtonEditorGump(); - - break; - - case GumpType.MiniMap: - gump = new MiniMapGump(); - - break; - - case GumpType.PaperDoll: - if (pdolc > 0) - { - break; - } - - if (ProfileManager.CurrentProfile.UseModernPaperdoll && serial == World.Player.Serial) - { - gump = new ModernPaperdoll(serial); - x = ProfileManager.CurrentProfile.ModernPaperdollPosition.X; - y = ProfileManager.CurrentProfile.ModernPaperdollPosition.Y; - } - else - { - gump = new PaperDollGump(serial, serial == World.Player.Serial); - x = ProfileManager.CurrentProfile.PaperdollPosition.X; - y = ProfileManager.CurrentProfile.PaperdollPosition.Y; - } - pdolc++; - - break; - - case GumpType.SkillMenu: - if (StandardSkillsGump) - { - gump = new StandardSkillsGump(); - } - else - { - gump = new SkillGumpAdvanced(); - } - - break; - - case GumpType.SpellBook: - gump = new SpellbookGump(); - - break; - - case GumpType.StatusGump: - gump = StatusGumpBase.AddStatusGump(0, 0); - x = ProfileManager.CurrentProfile.StatusGumpPosition.X; - y = ProfileManager.CurrentProfile.StatusGumpPosition.Y; - break; - - //case GumpType.TipNotice: - // gump = new TipNoticeGump(); - // break; - case GumpType.AbilityButton: - gump = new UseAbilityButtonGump(); - - break; - - case GumpType.SpellButton: - gump = new UseSpellButtonGump(); - - break; - - case GumpType.SkillButton: - gump = new SkillButtonGump(); - - break; - - case GumpType.RacialButton: - gump = new RacialAbilityButton(); - - break; - - case GumpType.WorldMap: - gump = new WorldMapGump(); - - break; - - case GumpType.Debug: - gump = new DebugGump(100, 100); - - break; - - case GumpType.NetStats: - gump = new NetworkStatsGump(100, 100); - - break; - - case GumpType.NameOverHeadHandler: - NameOverHeadHandlerGump.LastPosition = new Point(x, y); - // Gump gets opened by NameOverHeadManager, we just want to save the last position from profile - break; - case GumpType.GridContainer: - ushort ogContainer = ushort.Parse(xml.GetAttribute("ogContainer")); - gump = new GridContainer(serial, ogContainer); - if (((GridContainer)gump).IsPlayerBackpack) - { - x = ProfileManager.CurrentProfile.BackpackGridPosition.X; - y = ProfileManager.CurrentProfile.BackpackGridPosition.Y; - } - break; - case GumpType.DurabilityGump: - gump = new DurabilitysGump(); - break; - } - - if (gump == null) - { - continue; - } - - gump.LocalSerial = serial; - gump.Restore(xml); - gump.X = x; - gump.Y = y; - - if (gump.LocalSerial != 0) - { - UIManager.SavePosition(gump.LocalSerial, new Point(x, y)); - } - - if (!gump.IsDisposed) - { - gumps.Add(gump); - } - } - catch (Exception ex) - { - Log.Error(ex.ToString()); - } - } - - foreach (XmlElement group in root.GetElementsByTagName("anchored_group_gump")) - { - int matrix_width = int.Parse(group.GetAttribute("matrix_w")); - int matrix_height = int.Parse(group.GetAttribute("matrix_h")); - - AnchorManager.AnchorGroup ancoGroup = new AnchorManager.AnchorGroup(); - ancoGroup.ResizeMatrix(matrix_width, matrix_height, 0, 0); - - foreach (XmlElement xml in group.GetElementsByTagName("gump")) - { - try - { - GumpType type = (GumpType)int.Parse(xml.GetAttribute("type")); - int x = int.Parse(xml.GetAttribute("x")); - int y = int.Parse(xml.GetAttribute("y")); - uint serial = uint.Parse(xml.GetAttribute("serial")); - - int matrix_x = int.Parse(xml.GetAttribute("matrix_x")); - int matrix_y = int.Parse(xml.GetAttribute("matrix_y")); - - AnchorableGump gump = null; - - switch (type) - { - case GumpType.SpellButton: - gump = new UseSpellButtonGump(); - - break; - - case GumpType.SkillButton: - gump = new SkillButtonGump(); - - break; - - case GumpType.HealthBar: - if (CustomBarsToggled) - { - gump = new HealthBarGumpCustom(); - } - else - { - gump = new HealthBarGump(); - } - - break; - - case GumpType.AbilityButton: - gump = new UseAbilityButtonGump(); - - break; - - case GumpType.MacroButton: - gump = new MacroButtonGump(); - - break; - case GumpType.GridContainer: - ushort ogContainer = ushort.Parse(xml.GetAttribute("ogContainer")); - gump = new GridContainer(serial, ogContainer); - break; - case GumpType.Journal: - gump = new ResizableJournal(); - break; - case GumpType.WorldMap: - gump = new WorldMapGump(); - break; - case GumpType.InfoBar: - gump = new InfoBarGump(); - break; - case GumpType.PaperDoll: - gump = new ModernPaperdoll(World.Player.Serial); - break; - } - - if (gump != null) - { - gump.LocalSerial = serial; - gump.Restore(xml); - gump.X = x; - gump.Y = y; - - if (!gump.IsDisposed) - { - if (UIManager.AnchorManager[gump] == null && ancoGroup.IsEmptyDirection(matrix_x, matrix_y)) - { - gumps.Add(gump); - UIManager.AnchorManager[gump] = ancoGroup; - ancoGroup.AddControlToMatrix(matrix_x, matrix_y, gump); - } - else - { - gump.Dispose(); - } - } - } - } - catch (Exception ex) - { - Log.Error(ex.ToString()); - } - } - } - } - } - - return gumps; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Configuration/ProfileManager.cs b/src/ClassicUO.Client/Configuration/ProfileManager.cs deleted file mode 100644 index 632bb7337..000000000 --- a/src/ClassicUO.Client/Configuration/ProfileManager.cs +++ /dev/null @@ -1,109 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.IO; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Configuration -{ - public static class ProfileManager - { - public static Profile CurrentProfile { get; private set; } - public static string ProfilePath { get; private set; } - - public static void Load(string servername, string username, string charactername) - { - string rootpath; - - if (string.IsNullOrWhiteSpace(Settings.GlobalSettings.ProfilesPath)) - { - rootpath = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Profiles"); - } - else - { - rootpath = Settings.GlobalSettings.ProfilesPath; - } - - string path = FileSystemHelper.CreateFolderIfNotExists(rootpath, username, servername, charactername); - string fileToLoad = Path.Combine(path, "profile.json"); - - ProfilePath = path; - CurrentProfile = ConfigurationResolver.Load(fileToLoad, ProfileJsonContext.DefaultToUse) ?? new Profile(); - - CurrentProfile.Username = username; - CurrentProfile.ServerName = servername; - CurrentProfile.CharacterName = charactername; - - ValidateFields(CurrentProfile); - } - - - private static void ValidateFields(Profile profile) - { - if (profile == null) - { - return; - } - - if (string.IsNullOrEmpty(profile.ServerName)) - { - throw new InvalidDataException(); - } - - if (string.IsNullOrEmpty(profile.Username)) - { - throw new InvalidDataException(); - } - - if (string.IsNullOrEmpty(profile.CharacterName)) - { - throw new InvalidDataException(); - } - - if (profile.WindowClientBounds.X < 600) - { - profile.WindowClientBounds = new Point(600, profile.WindowClientBounds.Y); - } - - if (profile.WindowClientBounds.Y < 480) - { - profile.WindowClientBounds = new Point(profile.WindowClientBounds.X, 480); - } - } - - public static void UnLoadProfile() - { - CurrentProfile = null; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Configuration/Settings.cs b/src/ClassicUO.Client/Configuration/Settings.cs deleted file mode 100644 index 151aae0e5..000000000 --- a/src/ClassicUO.Client/Configuration/Settings.cs +++ /dev/null @@ -1,147 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.IO; -using System.Text.Json; -using System.Text.Json.Serialization; -using ClassicUO.Configuration.Json; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Configuration -{ - [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] - [JsonSerializable(typeof(Settings), GenerationMode = JsonSourceGenerationMode.Metadata)] - sealed partial class SettingsJsonContext : JsonSerializerContext { } - - - internal sealed class Settings - { - public const string SETTINGS_FILENAME = "settings.json"; - public static Settings GlobalSettings = new Settings(); - public static string CustomSettingsFilepath = null; - - - [JsonPropertyName("username")] public string Username { get; set; } = string.Empty; - - [JsonPropertyName("password")] public string Password { get; set; } = string.Empty; - - [JsonPropertyName("ip")] public string IP { get; set; } = ""; - - [JsonPropertyName("port"), JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)] public ushort Port { get; set; } = 0; - - [JsonPropertyName("ultimaonlinedirectory")] - public string UltimaOnlineDirectory { get; set; } = ""; - - [JsonPropertyName("profilespath")] public string ProfilesPath { get; set; } = string.Empty; - - [JsonPropertyName("clientversion")] public string ClientVersion { get; set; } = string.Empty; - - [JsonPropertyName("lang")] public string Language { get; set; } = ""; - - [JsonPropertyName("lastservernum")] public ushort LastServerNum { get; set; } = 1; - - [JsonPropertyName("last_server_name")] public string LastServerName { get; set; } = string.Empty; - - [JsonPropertyName("fps")] public int FPS { get; set; } = 60; - - [JsonConverter(typeof(NullablePoint2Converter))] [JsonPropertyName("window_position")] public Point? WindowPosition { get; set; } - [JsonConverter(typeof(NullablePoint2Converter))] [JsonPropertyName("window_size")] public Point? WindowSize { get; set; } - - [JsonPropertyName("is_win_maximized")] public bool IsWindowMaximized { get; set; } = true; - - [JsonPropertyName("saveaccount")] public bool SaveAccount { get; set; } - - [JsonPropertyName("autologin")] public bool AutoLogin { get; set; } - - [JsonPropertyName("reconnect")] public bool Reconnect { get; set; } - - [JsonPropertyName("reconnect_time")] public int ReconnectTime { get; set; } = 1; - - [JsonPropertyName("login_music")] public bool LoginMusic { get; set; } = true; - - [JsonPropertyName("login_music_volume")] public int LoginMusicVolume { get; set; } = 70; - - [JsonPropertyName("shard_type")] public int ShardType { get; set; } // 0 = normal (no customization), 1 = old, 2 = outlands?? - - [JsonPropertyName("fixed_time_step")] public bool FixedTimeStep { get; set; } = true; - - [JsonPropertyName("run_mouse_in_separate_thread")] - public bool RunMouseInASeparateThread { get; set; } = true; - - [JsonPropertyName("force_driver")] public byte ForceDriver { get; set; } - - [JsonPropertyName("use_verdata")] public bool UseVerdata { get; set; } - - [JsonPropertyName("maps_layouts")] public string MapsLayouts { get; set; } - - [JsonPropertyName("encryption")] public byte Encryption { get; set; } - - [JsonPropertyName("plugins")] public string[] Plugins { get; set; } = { @"./Assistant/Razor.dll" }; - - public static string GetSettingsFilepath() - { - if (CustomSettingsFilepath != null) - { - if (Path.IsPathRooted(CustomSettingsFilepath)) - { - return CustomSettingsFilepath; - } - - return Path.Combine(CUOEnviroment.ExecutablePath, CustomSettingsFilepath); - } - - return Path.Combine(CUOEnviroment.ExecutablePath, SETTINGS_FILENAME); - } - - - public void Save() - { - // Make a copy of the settings object that we will use in the saving process - var json = JsonSerializer.Serialize(this, typeof(Settings), SettingsJsonContext.Default); - var settingsToSave = JsonSerializer.Deserialize(json, typeof(Settings), SettingsJsonContext.Default) as Settings; - - // Make sure we don't save username and password if `saveaccount` flag is not set - // NOTE: Even if we pass username and password via command-line arguments they won't be saved - if (!settingsToSave.SaveAccount) - { - settingsToSave.Username = string.Empty; - settingsToSave.Password = string.Empty; - } - - settingsToSave.ProfilesPath = string.Empty; - - // NOTE: We can do any other settings clean-ups here before we save them - - ConfigurationResolver.Save(settingsToSave, GetSettingsFilepath(), SettingsJsonContext.Default); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Configuration/UISettings.cs b/src/ClassicUO.Client/Configuration/UISettings.cs deleted file mode 100644 index cd1c03e90..000000000 --- a/src/ClassicUO.Client/Configuration/UISettings.cs +++ /dev/null @@ -1,133 +0,0 @@ -using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.IO; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace ClassicUO.Configuration -{ - internal abstract class UISettings - { - private static string savePath { get { return Path.Combine(CUOEnviroment.ExecutablePath, "Data", "UI"); } } - private static readonly JsonSerializerOptions serializerOptions = new JsonSerializerOptions() { WriteIndented = true }; - private static Dictionary preload = new Dictionary(); - - public static string ReadJsonFile(string name) - { - string fp = Path.Combine(savePath, name + ".json"); - - if (File.Exists(fp)) - { - try - { - return File.ReadAllText(fp); - } - catch { } - } - - return string.Empty; - } - - public static UISettings Load(string name) - { - string jsonData; - - if (preload.TryGetValue(name, out var value)) - { - jsonData = value; - preload.Remove(name); - } - else - { - jsonData = ReadJsonFile(name); - } - - if (string.IsNullOrEmpty(jsonData)) - { - return null; - } - - var obj = JsonSerializer.Deserialize(jsonData); - - if (obj is UISettings settings) - { - return settings; - } - - return null; - } - - public static void Save(string name, object settings) - { - string fileSaveData = JsonSerializer.Serialize((T)settings, serializerOptions); - - try - { - if (!File.Exists(savePath)) - { - Directory.CreateDirectory(savePath); - } - - File.WriteAllText(Path.Combine(savePath, name + ".json"), fileSaveData); - } - catch { } - } - - public static void Preload() - { - System.Threading.Tasks.Task.Factory.StartNew(() => - { - if (Directory.Exists(savePath)) - { - string[] allFiles = Directory.GetFiles(savePath, "*.json"); - foreach (string file in allFiles) - { - try - { - preload.Add(Path.GetFileNameWithoutExtension(file), File.ReadAllText(file)); - } - catch { } - } - } - else - { - Directory.CreateDirectory(savePath); - } - }); - } - } - - public class ColorJsonConverter : JsonConverter - { - public override Color Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - Color color = new Color(); - string value = reader.GetString(); - if (!string.IsNullOrEmpty(value)) { - string[] parts = value.Split(':'); - - if (int.TryParse(parts[0], out int r)) - { - color.R = (byte)r; - } - if (int.TryParse(parts[1], out int g)) - { - color.G = (byte)g; - } - if (int.TryParse(parts[2], out int b)) - { - color.B = (byte)b; - } - if (int.TryParse(parts[3], out int a)) - { - color.A = (byte)a; - } - } - - return color; - } - - public override void Write(Utf8JsonWriter writer, Color value, JsonSerializerOptions options) => writer.WriteStringValue($"{value.R}:{value.G}:{value.B}:{value.A}"); - } -} diff --git a/src/ClassicUO.Client/DllMap.cs b/src/ClassicUO.Client/DllMap.cs deleted file mode 100644 index 1c300591a..000000000 --- a/src/ClassicUO.Client/DllMap.cs +++ /dev/null @@ -1,278 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Xml.Linq; - -namespace ClassicUO -{ -#if !NETFRAMEWORK - // only works in .NET Core. disable in .NET framework - public static class DllMap - { - [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool SetDefaultDllDirectories(int directoryFlags); - - [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern void AddDllDirectory(string lpPathName); - - [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool SetDllDirectory(string lpPathName); - - private const int LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000; - - public static Dictionary MapDictionary; - public static string OS; - public static string CPU; - public static bool Optimise; - - public static void Initialise(bool optimise = true) - { - Optimise = optimise; - - // Our executable needs to know how to find the native libraries - // For Windows, we can set this to be x86 or x64 directory at runtime (below) - // For Linux we need to move our native libraries to 'netcoredeps' which is set by .net core - // For OSX we need to set an environment variable (DYLD_LIBRARY_PATH) outside of the process by a script - if (Environment.OSVersion.Platform == PlatformID.Win32NT) - { - try - { - SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); - AddDllDirectory( - Path.Combine( - AppDomain.CurrentDomain.BaseDirectory, - Environment.Is64BitProcess ? "x64" : "x86" - ) - ); - } - catch - { - // Pre-Windows 7, KB2533623 - SetDllDirectory( - Path.Combine( - AppDomain.CurrentDomain.BaseDirectory, - Environment.Is64BitProcess ? "x64" : "x86" - ) - ); - } - } - - // .NET Core also doesn't use DllImport but we can replicate this using NativeLibrary as per below - // Uses FNA.dll.config to dictate what the name of the native library is per platform and architecture - var fnaAssembly = Assembly.GetAssembly(typeof(Microsoft.Xna.Framework.Graphics.ColorWriteChannels)); - Register(fnaAssembly); - } - - // Register a call-back for native library resolution. - private static void Register(Assembly assembly) - { - NativeLibrary.SetDllImportResolver(assembly, MapAndLoad); - - // Do setup so that MapLibraryName is faster than reading the XML each time - - // 1) Get platform & cpu - OS = GetCurrentPlatform().ToString().ToLowerInvariant(); - CPU = GetCurrentRuntimeArchitecture().ToString().ToLowerInvariant(); - - // 2) Setup MapDictionary - // For Windows use hardcoded values - // Why? This is our development platform and we wanted the fastest start time possible (eliminates XML Load) - if (OS == "windows" && Optimise) - { - MapDictionary = new Dictionary - { - { "SDL2", "SDL2.dll" }, - { "SDL_image", "SDL_image.dll" }, - { "FAudio", "FAudio.dll" } - }; - } - else - { - // For every other platform use XML file - // Read in config XML and only store details we're interested in within MapDictionary - var xmlPath = Path.Combine( - Path.GetDirectoryName(assembly.Location), - Path.GetFileNameWithoutExtension(assembly.Location) + ".dll.config" - ); - - if (!File.Exists(xmlPath)) - { - Console.WriteLine($"=== Cannot find XML: {xmlPath}"); - return; - } - - var root = XElement.Load(xmlPath); - - MapDictionary = new Dictionary(); - ParseXml(root, true); // Direct match on OS & CPU first - ParseXml(root, false); // Loose match on CPU second (won't allow duplicates) - } - } - - private static void ParseXml(XContainer root, bool matchCPU) - { - foreach (var el in root.Elements("dllmap")) - { - // Ignore entries for other OSs - if (el.Attribute("os")!.ToString().IndexOf(OS) < 0) - { - continue; - } - - // Ignore entries for other CPUs - if (matchCPU) - { - if (el.Attribute("cpu") == null) - { - continue; - } - - if (el.Attribute("cpu")!.ToString().IndexOf(CPU) < 0) - { - continue; - } - } - else - { - if (el.Attribute("cpu") != null && el.Attribute("cpu")!.ToString().IndexOf(CPU) < 0) - { - continue; - } - } - - var oldLib = el.Attribute("dll")!.Value; - var newLib = el.Attribute("target")!.Value; - if (string.IsNullOrWhiteSpace(oldLib) || string.IsNullOrWhiteSpace(newLib)) - { - continue; - } - - // Don't allow duplicates - if (MapDictionary.ContainsKey(oldLib)) - { - continue; - } - - MapDictionary.Add(oldLib, newLib); - } - } - - // The callback: which loads the mapped library in place of the original - private static IntPtr MapAndLoad(string libraryName, Assembly assembly, DllImportSearchPath? dllImportSearchPath) - { - string mappedName; - mappedName = MapLibraryName(libraryName, out mappedName) - ? mappedName - : libraryName; - return NativeLibrary.Load(mappedName, assembly, dllImportSearchPath); - } - - // Parse the assembly.xml file, and map the old name to the new name of a library. - private static bool MapLibraryName(string originalLibName, out string mappedLibName) => MapDictionary.TryGetValue(originalLibName, out mappedLibName); - - // Below pinched from Mono.DllMap project: https://github.com/Firwood-Software/AdvancedDLSupport/tree/1b7394211a655b2f77649ce3b610a3161215cbdc/Mono.DllMap - private static DllMapOS GetCurrentPlatform() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return DllMapOS.Linux; - } - - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return DllMapOS.Windows; - } - - if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return DllMapOS.OSX; - } - - var operatingDesc = RuntimeInformation.OSDescription.ToUpperInvariant(); - foreach (var system in Enum.GetValues(typeof(DllMapOS)) - .Cast() - .Except(new[] { DllMapOS.Linux, DllMapOS.Windows, DllMapOS.OSX })) - { - if (operatingDesc.Contains(system.ToString().ToUpperInvariant())) - { - return system; - } - } - - throw new PlatformNotSupportedException($"Couldn't detect platform: {RuntimeInformation.OSDescription}"); - } - - private static DllMapArchitecture GetCurrentRuntimeArchitecture() - { - switch (RuntimeInformation.ProcessArchitecture) - { - case Architecture.Arm: - return DllMapArchitecture.ARM; - case Architecture.X64: - return DllMapArchitecture.x86_64; - case Architecture.X86: - return DllMapArchitecture.x86; - } - - typeof(object).Module.GetPEKind(out _, out var machine); - switch (machine) - { - case ImageFileMachine.I386: - { - return DllMapArchitecture.x86; - } - case ImageFileMachine.AMD64: - { - return DllMapArchitecture.x86_64; - } - case ImageFileMachine.ARM: - { - return DllMapArchitecture.ARM; - } - case ImageFileMachine.IA64: - { - return DllMapArchitecture.IA64; - } - } - - throw new PlatformNotSupportedException("Couldn't detect the current architecture."); - } - - private enum DllMapOS - { - Linux = 1 << 0, - OSX = 1 << 1, - Solaris = 1 << 2, - FreeBSD = 1 << 3, - OpenBSD = 1 << 4, - NetBSD = 1 << 5, - Windows = 1 << 6, - AIX = 1 << 7, - HPUX = 1 << 8 - } - - private enum DllMapArchitecture - { - x86 = 1 << 0, - x86_64 = 1 << 1, - SPARC = 1 << 2, - PPC = 1 << 3, - S390 = 1 << 4, - S390X = 1 << 5, - ARM = 1 << 6, - ARMV8 = 1 << 7, - MIPS = 1 << 8, - Alpha = 1 << 9, - HPPA = 1 << 10, - IA64 = 1 << 11 - } - } - -#endif -} diff --git a/src/ClassicUO.Client/Game/CircleOfTransparency.cs b/src/ClassicUO.Client/Game/CircleOfTransparency.cs deleted file mode 100644 index e0c4e3409..000000000 --- a/src/ClassicUO.Client/Game/CircleOfTransparency.cs +++ /dev/null @@ -1,171 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game -{ - internal static class CircleOfTransparency - { - private static readonly Lazy _stencil = new Lazy - ( - () => - { - DepthStencilState state = new DepthStencilState - { - StencilEnable = true, - StencilFunction = CompareFunction.Always, - StencilPass = StencilOperation.Replace, - ReferenceStencil = 1 - //DepthBufferEnable = true, - //DepthBufferWriteEnable = true, - }; - - - return state; - } - ); - - - private static Texture2D _texture; - private static short _width, _height; - private static int _radius; - - - public static uint[] CreateCircleTexture(int radius, ref short width, ref short height) - { - int fixRadius = radius + 1; - int mulRadius = fixRadius * 2; - - uint[] pixels = new uint[mulRadius * mulRadius]; - - width = (short) mulRadius; - height = (short) mulRadius; - - for (int x = -fixRadius; x < fixRadius; x++) - { - int mulX = x * x; - int posX = (x + fixRadius) * mulRadius + fixRadius; - - for (int y = -fixRadius; y < fixRadius; y++) - { - int r = (int) Math.Sqrt(mulX + y * y); - - uint pic = (uint) (r <= radius ? (radius - r) & 0xFF : 0); - - int pos = posX + y; - - pixels[pos] = pic; - } - } - - return pixels; - } - - public static void Draw(UltimaBatcher2D batcher, Vector2 pos, ushort hue = 0) - { - if (_texture != null) - { - pos.X -= _width >> 1; - pos.Y -= _height >> 1; - - Vector3 hueVector = new Vector3(); - - if (hue == 0) - { - hueVector.X = 0; - hueVector.Y = 0f; - } - else - { - hueVector.X = hue; - hueVector.Y = 1f; - } - - batcher.SetStencil(_stencil.Value); - batcher.Draw - ( - _texture, - pos, - hueVector - ); - batcher.SetStencil(null); - } - } - - public static void Create(int radius) - { - if (radius < Constants.MIN_CIRCLE_OF_TRANSPARENCY_RADIUS) - { - radius = Constants.MIN_CIRCLE_OF_TRANSPARENCY_RADIUS; - } - else if (radius > Constants.MAX_CIRCLE_OF_TRANSPARENCY_RADIUS) - { - radius = Constants.MAX_CIRCLE_OF_TRANSPARENCY_RADIUS; - } - - if (_radius == radius && _texture != null && !_texture.IsDisposed) - { - return; - } - - _radius = radius; - _texture?.Dispose(); - _texture = null; - - uint[] pixels = CreateCircleTexture(radius, ref _width, ref _height); - - for (int i = 0; i < pixels.Length; i++) - { - ref uint pixel = ref pixels[i]; - - if (pixel != 0) - { - pixel = HuesHelper.RgbaToArgb(pixel); - //ushort value = (ushort)(pixel << 3); - - //if (value > 0xFF) - // value = 0xFF; - - //pixel = (uint)((value << 24) | (value << 16) | (value << 8) | value); - } - } - - _texture = new Texture2D(Client.Game.GraphicsDevice, _width, _height); - _texture.SetData(pixels); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Constants.cs b/src/ClassicUO.Client/Game/Constants.cs deleted file mode 100644 index 2e2738aa9..000000000 --- a/src/ClassicUO.Client/Game/Constants.cs +++ /dev/null @@ -1,144 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game -{ - internal static class Constants - { - public const string WIKI_LINK = "https://github.com/ClassicUO/ClassicUO/wiki"; - - public const int MIN_FPS = 12; - public const int MAX_FPS = 250; - public const int LOGIN_SCREEN_FPS = 60; - - public const int CHARACTER_ANIMATION_DELAY = 80; - public const int ITEM_EFFECT_ANIMATION_DELAY = 50; - - public const int MAX_STEP_COUNT = 5; - public const int TURN_DELAY = 100; // original client 12.5 fps = 80ms delay. Edit --> it causes throttling - public const int TURN_DELAY_FAST = 45; - public const int WALKING_DELAY = 150; // 750 - public const int PLAYER_WALKING_DELAY = 150; - public const int DEFAULT_CHARACTER_HEIGHT = 16; - public const int DEFAULT_BLOCK_HEIGHT = 16; - - public const float TIME_FADEOUT_TEXT = 1000; - public const uint TIME_DISPLAY_SYSTEM_MESSAGE_TEXT = 10000; - - public const int MIN_TERRAIN_SHADOWS_LEVEL = 5; - public const int MAX_TERRAIN_SHADOWS_LEVEL = 25; - - public const int USED_LAYER_COUNT = 23; - - public const int CLEAR_TEXTURES_DELAY = 3000; - public const int MAX_ANIMATIONS_OBJECT_REMOVED_BY_GARBAGE_COLLECTOR = 20; - public const int MAX_ART_OBJECT_REMOVED_BY_GARBAGE_COLLECTOR = 20; - public const int MAX_GUMP_OBJECT_REMOVED_BY_GARBAGE_COLLECTOR = 20; - public const int MAX_SOUND_OBJECT_REMOVED_BY_GARBAGE_COLLECTOR = 20; - public const int MAX_MAP_OBJECT_REMOVED_BY_GARBAGE_COLLECTOR = 50; - - public const int MAX_FAST_WALK_STACK_SIZE = 5; - - public const byte FOLIAGE_ALPHA = 76; - public const byte ALPHA_TIME = 20; - - public const int MAX_OBJECT_HANDLES = 200; - public const int OBJECT_HANDLES_GUMP_WIDTH = 100; - public const int OBJECT_HANDLES_GUMP_HEIGHT = 18; - - public const int SPELLBOOK_1_SPELLS_COUNT = 64; - public const int SPELLBOOK_2_SPELLS_COUNT = 17; - public const int SPELLBOOK_3_SPELLS_COUNT = 10; - public const int SPELLBOOK_4_SPELLS_COUNT = 6; - public const int SPELLBOOK_5_SPELLS_COUNT = 8; - public const int SPELLBOOK_6_SPELLS_COUNT = 16; - public const int SPELLBOOK_7_SPELLS_COUNT = 30; - public const int SPELLBOOK_8_SPELLS_COUNT = 45; - - public const int WAIT_FOR_TARGET_DELAY = 5000; - - public const int CONTAINER_RECT_STEP = 20; - public const int CONTAINER_RECT_DEFAULT_POSITION = 40; - public const int CONTAINER_RECT_LINESTEP = 800; - public const int ITEM_GUMP_TEXTURE_OFFSET = 11369; - - public const int MAX_MUSIC_DATA_INDEX_COUNT = 150; - - - public const ushort FIELD_REPLACE_GRAPHIC = 0x1826; - public const ushort TREE_REPLACE_GRAPHIC = 0x0E59; - - public const int MIN_CIRCLE_OF_TRANSPARENCY_RADIUS = 50; - public const int MAX_CIRCLE_OF_TRANSPARENCY_RADIUS = 1000; - - public const int MAX_ABILITIES_COUNT = 32; - - public const int DRAG_ITEMS_DISTANCE = 3; - public const int MIN_GUMP_DRAG_DISTANCE = 0; - public const int MIN_PICKUP_DRAG_DISTANCE_PIXELS = 5; - - public const int MIN_VIEW_RANGE = 5; - public const int MAX_VIEW_RANGE = 24; - public const int MAX_CONTAINER_OPENED_ON_GROUND_RANGE = 3; - - public const int OUT_RANGE_COLOR = 0x038B; - public const int DEAD_RANGE_COLOR = 0x038E; - public const int DEATH_SCREEN_TIMER = 1500; - - public const ushort HIGHLIGHT_CURRENT_OBJECT_HUE = 0x014; - - public const int MAX_JOURNAL_HISTORY_COUNT = 1000; - - public const byte MIN_CONTAINER_SIZE_PERC = 50; - public const byte MAX_CONTAINER_SIZE_PERC = 200; - - public const int MALE_GUMP_OFFSET = 50000; - public const int FEMALE_GUMP_OFFSET = 60000; - - public const int WEATHER_TIMER = 6 * 60 * 1000; - - public const int PREDICTABLE_CHUNKS = 300; - public const int PREDICTABLE_TILE_COUNT = 64 * PREDICTABLE_CHUNKS; - public const int PREDICTABLE_STATICS = PREDICTABLE_TILE_COUNT * 2; - public const int PREDICTABLE_MULTIS = PREDICTABLE_TILE_COUNT * 4; - - public static readonly bool[] BAD_CONTAINER_LAYERS = - { - false, // invalid [body] - true, true, true, true, true, true, true, true, - true, true, false, true, true, true, false, false, - true, true, true, true, - false, // backpack - true, true, true, false, false, false, false, false - }; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/Ability.cs b/src/ClassicUO.Client/Game/Data/Ability.cs deleted file mode 100644 index 219716bc0..000000000 --- a/src/ClassicUO.Client/Game/Data/Ability.cs +++ /dev/null @@ -1,127 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; - -namespace ClassicUO.Game.Data -{ - [Flags] - public enum Ability : ushort - { - Invalid = 0xFF, - None = 0, - ArmorIgnore = 1, - BleedAttack = 2, - ConcussionBlow = 3, - CrushingBlow = 4, - Disarm = 5, - Dismount = 6, - DoubleStrike = 7, - InfectiousStrike = 8, - MortalStrike = 9, - MovingShot = 10, - ParalyzingBlow = 11, - ShadowStrike = 12, - WhirlwindAttack = 13, - RidingSwipe = 14, - FrenziedWhirlwind = 15, - Block = 16, - DefenseMastery = 17, - NerveStrike = 18, - TalonStrike = 19, - Feint = 20, - DualWield = 21, - DoubleShot = 22, - ArmorPierce = 23, - Bladeweave = 24, - ForceArrow = 25, - LightningArrow = 26, - PsychicAttack = 27, - SerpentArrow = 28, - ForceOfNature = 29, - InfusedThrow = 30, - MysticArc = 31 - } - - internal readonly struct AbilityDefinition - { - public AbilityDefinition(int index, string name, ushort icon) - { - Index = index; - Name = name; - Icon = icon; - } - - public readonly int Index; - public readonly string Name; - public readonly ushort Icon; - } - - internal static class AbilityData - { - public static readonly AbilityDefinition[] Abilities = new AbilityDefinition[Constants.MAX_ABILITIES_COUNT] - { - new AbilityDefinition(1, "Armor Ignore", 0x5200), - new AbilityDefinition(2, "Bleed Attack", 0x5201), - new AbilityDefinition(3, "Concussion Blow", 0x5202), - new AbilityDefinition(4, "Crushing Blow", 0x5203), - new AbilityDefinition(5, "Disarm", 0x5204), - new AbilityDefinition(6, "Dismount", 0x5205), - new AbilityDefinition(7, "Double Strike", 0x5206), - new AbilityDefinition(8, "Infecting", 0x5207), - new AbilityDefinition(9, "Mortal Strike", 0x5208), - new AbilityDefinition(10, "Moving Shot", 0x5209), - new AbilityDefinition(11, "Paralyzing Blow", 0x520A), - new AbilityDefinition(12, "Shadow Strike", 0x520B), - new AbilityDefinition(13, "Whirlwind Attack", 0x520C), - new AbilityDefinition(14, "Riding Swipe", 0x520D), - new AbilityDefinition(15, "Frenzied Whirlwind", 0x520E), - new AbilityDefinition(16, "Block", 0x520F), - new AbilityDefinition(17, "Defense Mastery", 0x5210), - new AbilityDefinition(18, "Nerve Strike", 0x5211), - new AbilityDefinition(19, "Talon Strike", 0x5212), - new AbilityDefinition(20, "Feint", 0x5213), - new AbilityDefinition(21, "Dual Wield", 0x5214), - new AbilityDefinition(22, "Double Shot", 0x5215), - new AbilityDefinition(23, "Armor Pierce", 0x5216), - new AbilityDefinition(24, "Bladeweave", 0x5217), - new AbilityDefinition(25, "Force Arrow", 0x5218), - new AbilityDefinition(26, "Lightning Arrow", 0x5219), - new AbilityDefinition(27, "Psychic Attack", 0x521A), - new AbilityDefinition(28, "Serpent Arrow", 0x521B), - new AbilityDefinition(29, "Force of Nature", 0x521C), - new AbilityDefinition(30, "Infused Throw", 0x521D), - new AbilityDefinition(31, "Mystic Arc", 0x521E), - new AbilityDefinition(32, "Disrobe", 0x521F) - }; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/BuffIcon.cs b/src/ClassicUO.Client/Game/Data/BuffIcon.cs deleted file mode 100644 index 5b54dd194..000000000 --- a/src/ClassicUO.Client/Game/Data/BuffIcon.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; - -namespace ClassicUO.Game.Data -{ - public class BuffIcon : IEquatable - { - public BuffIcon(BuffIconType type, ushort graphic, long timer, string text, string title = "") - { - Type = type; - Graphic = graphic; - Timer = (timer <= 0 ? 0xFFFF_FFFF : Time.Ticks + timer * 1000); - Text = text; - Title = title; - } - - public bool Equals(BuffIcon other) - { - return other != null && Type == other.Type; - } - - public readonly ushort Graphic; - - public readonly string Text; - - public readonly long Timer; - - public readonly BuffIconType Type; - - public readonly string Title; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/BuffTable.cs b/src/ClassicUO.Client/Game/Data/BuffTable.cs deleted file mode 100644 index 311fea59c..000000000 --- a/src/ClassicUO.Client/Game/Data/BuffTable.cs +++ /dev/null @@ -1,472 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Utility; -using System.Collections.Generic; -using System.IO; - -namespace ClassicUO.Game.Data -{ - public enum BuffIconType : short - { - DismountPrevention = 0x3E9, - NoRearm = 0x3EA, - //Currently, no 0x3EB or 0x3EC - NightSight = 0x3ED, //* - DeathStrike, - EvilOmen, - HonoredDebuff, - AchievePerfection, - DivineFury, //* - EnemyOfOne, //* - HidingAndOrStealth, //* - ActiveMeditation, //* - BloodOathCaster, //* - BloodOathCurse, //* - CorpseSkin, //* - Mindrot, //* - PainSpike, //* - Strangle, - GiftOfRenewal, //* - AttuneWeapon, //* - Thunderstorm, //* - EssenceOfWind, //* - EtherealVoyage, //* - GiftOfLife, //* - ArcaneEmpowerment, //* - MortalStrike, - ReactiveArmor, //* - Protection, //* - ArchProtection, - MagicReflection, //* - Incognito, //* - Disguised, - AnimalForm, - Polymorph, - Invisibility, //* - Paralyze, //* - Poison, - Bleed, - Clumsy, //* - FeebleMind, //* - Weaken, //* - Curse, //* - MassCurse, - Agility, //* - Cunning, //* - Strength, //* - Bless, //* - Sleep, - StoneForm, - SpellPlague, - Berserk, - MassSleep, - Fly, - Inspire, - Invigorate, - Resilience, - Perseverance, - TribulationTarget, - DespairTarget, - FishPie = 0x426, - HitLowerAttack, - HitLowerDefense, - DualWield, - Block, - DefenseMastery, - DespairCaster, - Healing, - SpellFocusingBuff, - SpellFocusingDebuff, - RageFocusingDebuff, - RageFocusingBuff, - Warding, - TribulationCaster, - ForceArrow, - Disarm, - Surge, - Feint, - TalonStrike, - PsychicAttack, - ConsecrateWeapon, - GrapesOfWrath, - EnemyOfOneDebuff, - HorrificBeast, - LichForm, - VampiricEmbrace, - CurseWeapon, - ReaperForm, - ImmolatingWeapon, - Enchant, - HonorableExecution, - Confidence, - Evasion, - CounterAttack, - LightningStrike, - MomentumStrike, - OrangePetals, - RoseOfTrinsic, - PoisonImmunity, - Veterinary, - Perfection, - Honored, - ManaPhase, - FanDancerFanFire, - Rage, - Webbing, - MedusaStone, - TrueFear, - AuraOfNausea, - HowlOfCacophony, - GazeDespair, - HiryuPhysicalResistance, - RuneBeetleCorruption, - BloodwormAnemia, - RotwormBloodDisease, - SkillUseDelay, - FactionStatLoss, - HeatOfBattleStatus, - CriminalStatus, - ArmorPierce, - SplinteringEffect, - SwingSpeedDebuff, - WraithForm, - CityTradeDeal = 0x466, - HumilityDebuff = 0x467, - Spirituality, - Humility, - // Skill Masteries - Rampage, - Stagger, // Debuff - Toughness, - Thrust, - Pierce, // Debuff - PlayingTheOdds, - FocusedEye, - Onslaught, // Debuff - ElementalFury, - ElementalFuryDebuff, // Debuff - CalledShot, - Knockout, - SavingThrow, - Conduit, - EtherealBurst, - MysticWeapon, - ManaShield, - AnticipateHit, - Warcry, - Shadow, - WhiteTigerForm, - Bodyguard, - HeightenedSenses, - Tolerance, - DeathRay, - DeathRayDebuff, - Intuition, - EnchantedSummoning, - ShieldBash, - Whispering, - CombatTraining, - InjectedStrikeDebuff, - InjectedStrike, - UnknownTomato, - PlayingTheOddsDebuff, - DragonTurtleDebuff, - Boarding, - Potency, - ThrustDebuff, - FistsOfFury, // 1169 - BarrabHemolymphConcentrate, - JukariBurnPoiltice, - KurakAmbushersEssence, - BarakoDraftOfMight, - UraliTranceTonic, - SakkhraProphylaxis, // 1175 - Sparks, - Swarm, - BoneBreaker, - Unknown2, - SwarmImmune, - BoneBreakerImmune, - UnknownGoblin, - UnknownRedDrop, - UnknownStar, - FeintDebuff, - CaddelliteInfused, - PotionGloriousFortune, - MysticalPolymorphTotem, - UnknownDebuff, - } - - internal static class BuffTable - { - private static ushort[] _table; - - public static ushort[] Table => _table; - - public static void Load() - { - string path = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Client"); - - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - string buff = Path.Combine(path, "buff.txt"); - - if (File.Exists(buff)) - { - var tempList = new List(); - - TextFileParser buffParser = new TextFileParser(File.ReadAllText(buff), new[] { ' ', '\t', ',' }, new[] { '#', ';' }, new[] { '"', '"' }); - - while (!buffParser.IsEOF()) - { - var buffToken = buffParser.ReadTokens(); - - if (buffToken != null && buffToken.Count != 0) - { - if (ushort.TryParse(buffToken[0], out ushort graphic)) - { - tempList.Add(graphic); - } - } - } - - _table = tempList.ToArray(); - } - else - { - _table = _defaultTable; - } - } - - private static ushort[] _defaultTable = - { - 0x754C, - 0x754A, - 0x0000, - 0x0000, - 0x755E, - 0x7549, - 0x7551, - 0x7556, - 0x753A, - 0x754D, - 0x754E, - 0x7565, - 0x753B, - 0x7543, - 0x7544, - 0x7546, - 0x755C, - 0x755F, - 0x7566, - 0x7554, - 0x7540, - 0x7568, - 0x754F, - 0x7550, - 0x7553, - 0x753E, - 0x755D, - 0x7563, - 0x7562, - 0x753F, - 0x7559, - 0x7557, - 0x754B, - 0x753D, - 0x7561, - 0x7558, - 0x755B, - 0x7560, - 0x7541, - 0x7545, - 0x7552, - 0x7569, - 0x7548, - 0x755A, - 0x753C, - 0x7547, - 0x7567, - 0x7542, - 0x758A, - 0x758B, - 0x758C, - 0x758D, - 0x0000, - 0x758E, - 0x094B, - 0x094C, - 0x094D, - 0x094E, - 0x094F, - 0x0950, - 0x753E, - 0x5011, - 0x7590, - 0x7591, - 0x7592, - 0x7593, - 0x7594, - 0x7595, - 0x7596, - 0x7598, - 0x7599, - 0x759B, - 0x759C, - 0x759E, - 0x759F, - 0x75A0, - 0x75A1, - 0x75A3, - 0x75A4, - 0x75A5, - 0x75A6, - 0x75A7, - 0x75C0, - 0x75C1, - 0x75C2, - 0x75C3, - 0x75C4, - 0x75F2, - 0x75F3, - 0x75F4, - 0x75F5, - 0x75F6, - 0x75F7, - 0x75F8, - 0x75F9, - 0x75FA, - 0x75FB, - 0x75FC, - 0x75FD, - 0x75FE, - 0x75FF, - 0x7600, - 0x7601, - 0x7602, - 0x7603, - 0x7604, - 0x7605, - 0x7606, - 0x7607, - 0x7608, - 0x7609, - 0x760A, - 0x760B, - 0x760C, - 0x760D, - 0x760E, - 0x760F, - 0x7610, - 0x7611, - 0x7612, - 0x7613, - 0x7614, - 0x7615, - 0x75C5, - 0x75F6, - 0x761B, - // skill masteries - 0x9bc9, - 0x9bb5, - 0x9bdd, - 0x9bc6, - 0x9bcc, - 0x9bbe, - 0x9bbd, - 0x9bcb, - 0x9bc8, - 0x9bbf, - 0x9bcd, - 0x9bc0, - 0x9bce, - 0x9bc1, - 0x9bc7, - 0x9bc2, - 0x9bb7, - 0x9bca, - 0x9bb6, - 0x9bb8, - 0x9bb9, - 0x9bba, - 0x9bbb, - 0x9bbc, - 0x9bc3, - 0x9bc4, - 0x9bc5, - 0x9bd2, - 0x9bd3, - 0x9bd4, - 0x9bd5, - 0x9bd1, - 0x9bd6, - 0x9bd7, - 0x9bcf, - 0x9bd8, - 0x9bd9, - 0x9bdb, - 0x9bdc, - 0x9bda, - 0x9bd0, - 0x9bde, - 0x9bdf, - - 0xC349, - 0xC34D, - 0xC34E, - 0xC34C, - 0xC34B, - 0xC34A, - 0xC343, - 0xC345, - 0xC346, - 0xC347, - 0xC348, - - 0x9CDE, - - 0x5DE1, - 0x5DDF, - 0x5DE3, - 0x5DE5, - 0x5DE4, - 0x5DE6, - 0x5D51, - - 0x0951 - }; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/ChairTable.cs b/src/ClassicUO.Client/Game/Data/ChairTable.cs deleted file mode 100644 index c6e5ab55b..000000000 --- a/src/ClassicUO.Client/Game/Data/ChairTable.cs +++ /dev/null @@ -1,1942 +0,0 @@ -using ClassicUO.Utility; -using System.Collections.Generic; -using System.IO; -using static ClassicUO.Assets.AnimationsLoader; - -namespace ClassicUO.Game.Data -{ - internal static class ChairTable - { - public static Dictionary Table = new Dictionary(); - - public static void Load() - { - string path = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Client"); - - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - string chair = Path.Combine(path, "chair.txt"); - - if (!File.Exists(chair)) - { - using (StreamWriter writer = new StreamWriter(chair)) - { - foreach (var item in _defaultTable) - { - writer.WriteLine($"{item.Graphic},{item.Direction1},{item.Direction2},{item.Direction3},{item.Direction4},{item.OffsetY},{item.MirrorOffsetY}"); - } - } - } - - TextFileParser chairParse = new TextFileParser(File.ReadAllText(chair), new[] { ' ', '\t', ',' }, new[] { '#', ';' }, new[] { '"', '"' }); - - while (!chairParse.IsEOF()) - { - List ss = chairParse.ReadTokens(); - - if (ss != null && ss.Count >= 7) - { - ushort.TryParse(ss[0], out ushort graphic); - sbyte.TryParse(ss[1], out sbyte d1); - sbyte.TryParse(ss[2], out sbyte d2); - sbyte.TryParse(ss[3], out sbyte d3); - sbyte.TryParse(ss[4], out sbyte d4); - sbyte.TryParse(ss[5], out sbyte offsetY); - sbyte.TryParse(ss[6], out sbyte mirrorOffsetY); - - Table.Add(graphic, new SittingInfoData(graphic, d1, d2, d3, d4, offsetY, mirrorOffsetY, false)); - } - } - } - - private static readonly SittingInfoData[] _defaultTable = - { - new SittingInfoData - ( - 0x0459, - 0, - -1, - 4, - -1, - 2, - 2, - false - ), - new SittingInfoData - ( - 0x045A, - -1, - 2, - -1, - 6, - 2, - 2, - false - ), - new SittingInfoData - ( - 0x045B, - 0, - -1, - 4, - -1, - 2, - 2, - false - ), - new SittingInfoData - ( - 0x045C, - -1, - 2, - -1, - 6, - 2, - 2, - false - ), - new SittingInfoData - ( - 0x0A2A, - 0, - 2, - 4, - 6, - -4, - -4, - false - ), - new SittingInfoData - ( - 0x0A2B, - 0, - 2, - 4, - 6, - -8, - -8, - false - ), - new SittingInfoData - ( - 0x0B2C, - -1, - 2, - -1, - 6, - 2, - 2, - false - ), - new SittingInfoData - ( - 0x0B2D, - 0, - -1, - 4, - -1, - 2, - 2, - false - ), - new SittingInfoData - ( - 0x0B2E, - 4, - 4, - 4, - 4, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x0B2F, - 2, - 2, - 2, - 2, - 6, - 6, - false - ), - new SittingInfoData - ( - 0x0B30, - 6, - 6, - 6, - 6, - -8, - 8, - true - ), - new SittingInfoData - ( - 0x0B31, - 0, - 0, - 0, - 0, - 0, - 4, - true - ), - new SittingInfoData - ( - 0x0B32, - 4, - 4, - 4, - 4, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x0B33, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x0B4E, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x0B4F, - 4, - 4, - 4, - 4, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x0B50, - 0, - 0, - 0, - 0, - 0, - 0, - true - ), - new SittingInfoData - ( - 0x0B51, - 6, - 6, - 6, - 6, - 0, - 0, - true - ), - new SittingInfoData - ( - 0x0B52, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x0B53, - 4, - 4, - 4, - 4, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x0B54, - 0, - 0, - 0, - 0, - 0, - 0, - true - ), - new SittingInfoData - ( - 0x0B55, - 6, - 6, - 6, - 6, - 0, - 0, - true - ), - new SittingInfoData - ( - 0x0B56, - 2, - 2, - 2, - 2, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x0B57, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x0B58, - 6, - 6, - 6, - 6, - 0, - 8, - true - ), - new SittingInfoData - ( - 0x0B59, - 0, - 0, - 0, - 0, - 0, - 8, - true - ), - new SittingInfoData - ( - 0x0B5A, - 2, - 2, - 2, - 2, - 8, - 8, - false - ), - new SittingInfoData - ( - 0x0B5B, - 4, - 4, - 4, - 4, - 8, - 8, - false - ), - new SittingInfoData - ( - 0x0B5C, - 0, - 0, - 0, - 0, - 0, - 8, - true - ), - new SittingInfoData - ( - 0x0B5D, - 6, - 6, - 6, - 6, - 0, - 8, - true - ), - new SittingInfoData - ( - 0x0B5E, - 0, - 2, - 4, - 6, - -8, - -8, - false - ), - new SittingInfoData - ( - 0x0B5F, - -1, - 2, - -1, - 6, - 3, - 14, - false - ), - new SittingInfoData - ( - 0x0B60, - -1, - 2, - -1, - 6, - 3, - 14, - false - ), - new SittingInfoData - ( - 0x0B61, - -1, - 2, - -1, - 6, - 3, - 14, - false - ), - new SittingInfoData - ( - 0x0B62, - -1, - 2, - -1, - 6, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x0B63, - -1, - 2, - -1, - 6, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x0B64, - -1, - 2, - -1, - 6, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x0B65, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x0B66, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x0B67, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x0B68, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x0B69, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x0B6A, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x0B91, - 4, - 4, - 4, - 4, - 6, - 6, - false - ), - new SittingInfoData - ( - 0x0B92, - 4, - 4, - 4, - 4, - 6, - 6, - false - ), - new SittingInfoData - ( - 0x0B93, - 2, - 2, - 2, - 2, - 6, - 6, - false - ), - new SittingInfoData - ( - 0x0B94, - 2, - 2, - 2, - 2, - 6, - 6, - false - ), - new SittingInfoData - ( - 0x0CF3, - -1, - 2, - -1, - 6, - 2, - 8, - false - ), - new SittingInfoData - ( - 0x0CF4, - -1, - 2, - -1, - 6, - 2, - 8, - false - ), - new SittingInfoData - ( - 0x0CF6, - 0, - -1, - 4, - -1, - 2, - 8, - false - ), - new SittingInfoData - ( - 0x0CF7, - 0, - -1, - 4, - -1, - 2, - 8, - false - ), - new SittingInfoData - ( - 0x0E50, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x0E51, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x0E52, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x0E53, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x1049, - -1, - 2, - -1, - 6, - 2, - 2, - false - ), // EAST/WEST - new SittingInfoData - ( - 0x104A, - 0, - -1, - 4, - -1, - 2, - 2, - false - ), // NORTH/SOUTH - new SittingInfoData - ( - 0x11FC, - 0, - 2, - 4, - 6, - 2, - 7, - false - ), // ANY - new SittingInfoData - ( - 0x1207, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), // NORTH/SOUTH - new SittingInfoData - ( - 0x1208, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), // NORTH/SOUTH - new SittingInfoData - ( - 0x1209, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), // NORTH/SOUTH - new SittingInfoData - ( - 0x120A, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), // NORTH/SOUTH - new SittingInfoData - ( - 0x120B, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), // NORTH/SOUTH - new SittingInfoData - ( - 0x120C, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), // NORTH/SOUTH - new SittingInfoData - ( - 0x1218, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x1219, - 2, - 2, - 2, - 2, - 4, - 4, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x121A, - 0, - 0, - 0, - 0, - 0, - 8, - true - ), // NORTH ONLY - new SittingInfoData - ( - 0x121B, - 6, - 6, - 6, - 6, - 0, - 8, - true - ), // WEST ONLY - new SittingInfoData - ( - 0x1527, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x1771, - 0, - 2, - 4, - 6, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x1776, - 0, - 2, - 4, - 6, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x1779, - 0, - 2, - 4, - 6, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x1DC7, - -1, - 2, - -1, - 6, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x1DC8, - -1, - 2, - -1, - 6, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x1DC9, - -1, - 2, - -1, - 6, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x1DCA, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x1DCB, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x1DCC, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x1DCD, - -1, - 2, - -1, - 6, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x1DCE, - -1, - 2, - -1, - 6, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x1DCF, - -1, - 2, - -1, - 6, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x1DD0, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x1DD1, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x1DD2, - -1, - 2, - -1, - 6, - 3, - 10, - false - ), - - new SittingInfoData - ( - 0x2A58, - 4, - 4, - 4, - 4, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x2A59, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x2A5A, - 0, - 2, - 4, - 6, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x2A5B, - 0, - 2, - 4, - 6, - 10, - 10, - false - ), - new SittingInfoData - ( - 0x2A7F, - 0, - 2, - 4, - 6, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x2A80, - 0, - 2, - 4, - 6, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x2DDF, - 0, - 2, - 4, - 6, - 2, - 2, - false - ), - new SittingInfoData - ( - 0x2DE0, - 0, - 2, - 4, - 6, - 2, - 2, - false - ), - new SittingInfoData - ( - 0x2DE3, - 2, - 2, - 2, - 2, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x2DE4, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x2DE5, - 6, - 6, - 6, - 6, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x2DE6, - 0, - 0, - 0, - 0, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x2DEB, - 0, - 0, - 0, - 0, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x2DEC, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x2DED, - 2, - 2, - 2, - 2, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x2DEE, - 6, - 6, - 6, - 6, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x2DF5, - 0, - 2, - 4, - 6, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x2DF6, - 0, - 2, - 4, - 6, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x3088, - 0, - 2, - 4, - 6, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x3089, - 0, - 2, - 4, - 6, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x308A, - 0, - 2, - 4, - 6, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x308B, - 0, - 2, - 4, - 6, - 4, - 4, - false - ), - new SittingInfoData - ( - 0x319A, - -1, - 2, - -1, - 6, - 2, - 2, - false - ), // EAST/WEST - new SittingInfoData - ( - 0x319B, - 0, - -1, - 4, - -1, - 2, - 2, - false - ), // NORTH/SOUTH - new SittingInfoData - ( - 0x35ED, - 0, - 2, - 4, - 6, - 0, - 0, - false - ), - new SittingInfoData - ( - 0x35EE, - 0, - 2, - 4, - 6, - 0, - 0, - false - ), - - new SittingInfoData - ( - 0x3DFF, - 0, - -1, - 4, - -1, - 2, - 2, - false - ), - new SittingInfoData - ( - 0x3E00, - -1, - 2, - -1, - 6, - 2, - 2, - false - ), - new SittingInfoData - ( - 0x4023, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x4024, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x4027, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x4028, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x4029, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x402A, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x4BDC, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x4C1B, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x4C1E, - 2, - 2, - 2, - 2, - 6, - 6, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x4C80, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x4C81, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x4C82, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x4C83, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x4C84, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x4C85, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x4C86, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x4C87, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x4C88, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x4C89, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x4C8A, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x4C8B, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x4C8C, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x4C8D, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x4C8E, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x4C8F, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x4DE0, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x63BC, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x63BD, - 0, - -1, - 4, - -1, - 3, - 10, - false - ), - new SittingInfoData - ( - 0x63C3, - -1, - 2, - -1, - 6, - 3, - 14, - false - ), - new SittingInfoData - ( - 0x63C4, - -1, - 2, - -1, - 6, - 3, - 14, - false - ), - new SittingInfoData - ( - 0x996C, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x9977, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x9C57, - 6, - 6, - 6, - 6, - 6, - 4, - false - ), // WEST ONLY - new SittingInfoData - ( - 0x9C58, - 6, - 6, - 6, - 6, - 6, - 4, - false - ), // WEST ONLY - new SittingInfoData - ( - 0x9C59, - 0, - 0, - 0, - 0, - 4, - 4, - false - ), // NORTH ONLY - new SittingInfoData - ( - 0x9C5A, - 0, - 0, - 0, - 0, - 4, - 4, - false - ), // NORTH ONLY - new SittingInfoData - ( - 0x9C5D, - 6, - 6, - 6, - 6, - 6, - 4, - false - ), // WEST ONLY - new SittingInfoData - ( - 0x9C5E, - 6, - 6, - 6, - 6, - 6, - 4, - false - ), // WEST ONLY - new SittingInfoData - ( - 0x9C5F, - 6, - 6, - 6, - 6, - 6, - 4, - false - ), // WEST ONLY - new SittingInfoData - ( - 0x9C60, - 0, - 0, - 0, - 0, - 4, - 4, - false - ), // NORTH ONLY - new SittingInfoData - ( - 0x9C61, - 0, - 0, - 0, - 0, - 4, - 4, - false - ), // NORTH ONLY - new SittingInfoData - ( - 0x9C62, - 0, - 0, - 0, - 0, - 4, - 4, - false - ), // NORTH ONLY - new SittingInfoData - ( - 0x9E8E, - 0, - 0, - 0, - 0, - 4, - 4, - false - ), // NORTH ONLY - new SittingInfoData - ( - 0x9E8F, - 6, - 6, - 6, - 6, - 6, - 4, - false - ), // WEST ONLY - new SittingInfoData - ( - 0x9E90, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0x9E91, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x9E9F, - 0, - 0, - 0, - 0, - 4, - 4, - false - ), // NORTH ONLY - new SittingInfoData - ( - 0x9EA0, - 6, - 6, - 6, - 6, - 6, - 4, - false - ), // WEST ONLY - new SittingInfoData - ( - 0x9EA1, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0x9EA2, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0xA05C, - 6, - 6, - 6, - 6, - 6, - 4, - false - ), // WEST ONLY - new SittingInfoData - ( - 0xA05D, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0xA05E, - 0, - 0, - 0, - 0, - 4, - 4, - false - ), // NORTH ONLY - new SittingInfoData - ( - 0xA05F, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0xA211, - 0, - 2, - 4, - 6, - -4, - -4, - false - ), // ANY - new SittingInfoData - ( - 0xA4EA, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0xA4EB, - 2, - 2, - 2, - 2, - 0, - 0, - false - ), // EAST ONLY - new SittingInfoData - ( - 0xA586, - 4, - 4, - 4, - 4, - 4, - 4, - false - ), // SOUTH ONLY - new SittingInfoData - ( - 0xA587, - 2, - 2, - 2, - 2, - 0, - 0, - false - ) // EAST ONLY - }; - } -} diff --git a/src/ClassicUO.Client/Game/Data/CharacterCreationValues.cs b/src/ClassicUO.Client/Game/Data/CharacterCreationValues.cs deleted file mode 100644 index 76b79c5c8..000000000 --- a/src/ClassicUO.Client/Game/Data/CharacterCreationValues.cs +++ /dev/null @@ -1,265 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Linq; -using ClassicUO.Assets; - -namespace ClassicUO.Game.Data -{ - internal class CharacterCreationValues - { - private static readonly ushort[] HumanSkinTone = - { - 0x03E9, 0x03F1, 0x03F9, 0x0401, 0x0409, 0x0411, 0x0419, 0x0421, 0x03EA, 0x03F2, 0x03FA, 0x0402, 0x040A, - 0x0412, 0x041A, 0x0421, 0x03EB, 0x03F3, 0x03FB, 0x0403, 0x040B, 0x0413, 0x041B, 0x0421, 0x03EC, 0x03F4, - 0x03FC, 0x0404, 0x040C, 0x0414, 0x041C, 0x0421, 0x03ED, 0x03F5, 0x03FD, 0x0405, 0x040D, 0x0415, 0x041D, - 0x0421, 0x03EE, 0x03F6, 0x03FE, 0x0406, 0x040E, 0x0416, 0x041E, 0x0421, 0x03EF, 0x03F7, 0x03FF, 0x0407, - 0x040F, 0x0417, 0x041F, 0x0421, 0x03F0, 0x03F8, 0x0400, 0x0408, 0x0410, 0x0418, 0x0420, 0x0421 - }; - private static readonly ushort[] ElfSkinTone = - { - 0x04DD, 0x076B, 0x0834, 0x042F, 0x024C, 0x024D, 0x024E, 0x00BE, 0x04A6, 0x0360, 0x0374, 0x0366, 0x03E7, - 0x03DD, 0x0352, 0x0902, 0x076C, 0x0383, 0x0578, 0x03E8, 0x0373, 0x0388, 0x0384, 0x0375, 0x053E, 0x0380, - 0x0381, 0x0382, 0x076A, 0x03E4, 0x051C, 0x03E5 - }; - private static readonly ushort[] GargoyleSkinTone = - { - 0x06DA, 0x06DB, 0x06DC, 0x06DD, 0x06DE, 0x06DF, 0x06E0, 0x06E1, 0x06E2, 0x06E3, 0x06E4, 0x06E5, 0x06E6, - 0x06E7, 0x06E8, 0x06E9, 0x06EA, 0x06EB, 0x06EC, 0x06ED, 0x06EE, 0x06EF, 0x06F0, 0x06F1, 0x06F2, 0x06DA, - 0x06DB, 0x06DC - }; - private static readonly ushort[] HumanHairColor = - { - 0x044D, 0x0455, 0x045D, 0x0465, 0x046D, 0x0475, 0x044E, 0x0456, 0x045E, 0x0466, 0x046E, 0x0476, 0x044F, - 0x0457, 0x045F, 0x0467, 0x046F, 0x0477, 0x0450, 0x0458, 0x0460, 0x0468, 0x0470, 0x0478, 0x0451, 0x0459, - 0x0461, 0x0469, 0x0471, 0x0479, 0x0452, 0x045A, 0x0462, 0x046A, 0x0472, 0x047A, 0x0453, 0x045B, 0x0463, - 0x046B, 0x0473, 0x047B, 0x0454, 0x045C, 0x0464, 0x046C, 0x0474, 0x047C - }; - private static readonly ushort[] ElfHairColor = - { - 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0100, 0x06B7, 0x0206, 0x0210, 0x026B, 0x02C2, 0x02C8, - 0x01E3, 0x0238, 0x0368, 0x059C, 0x0852, 0x008D, 0x008E, 0x008F, 0x0090, 0x0091, 0x0158, 0x0159, 0x015A, - 0x015B, 0x015C, 0x015D, 0x01BC, 0x0724, 0x0057, 0x0127, 0x012E, 0x01F2, 0x0250, 0x031C, 0x031D, 0x031E, - 0x031F, 0x0320, 0x0321, 0x0322, 0x0323, 0x0324, 0x0325, 0x0385, 0x0386, 0x0387, 0x0388, 0x0389, 0x0385, - 0x0386, 0x0387 - }; - private static readonly ushort[] GargoyleHairColor = - { - 0x0708, 0x070A, 0x070C, 0x070E, 0x0710, 0x0762, 0x0764, 0x0767, 0x076A, 0x06F2, 0x06F0, 0x06EE, 0x06E3, - 0x06E1, 0x06DF, 0x0708, 0x070A, 0x070C - }; - private static readonly int[] HumanHairLabels = - { - 3000340, 3000341, 3000342, 3000343, 3000344, 3000345, 3000346, 3000347, 3000348, 3000349 - }; - private static readonly int[] HumanHairGraphics = - { - 0, 8251, 8252, 8253, 8260, 8261, 8266, 8263, 8264, 8265 - }; - private static readonly int[] HumanFacialLabels = - { - 3000340, 3000351, 3000352, 3000353, 3000354, 1011060, 1011061, 3000357 - }; - private static readonly int[] HumanFacialGraphics = - { - 0, 8256, 8254, 8255, 8257, 8267, 8268, 8269 - }; - private static readonly int[] HumanFemaleHairLabels = - { - 3000340, 3000341, 3000342, 3000343, 3000344, 3000345, 3000346, 3000347, 3000349, 3000350 - }; - private static readonly int[] HumanFemaleHairGraphics = - { - 0, 8251, 8252, 8253, 8260, 8261, 8266, 8263, 8265, 8262 - }; - private static readonly int[] ElfHairLabels = - { - 3000340, 1074385, 1074386, 1074387, 1074388, 1074390, 1074391, 1074392, 1074394 - }; - private static readonly int[] ElfHairGraphics = - { - 0, 0x2FBF, 0x2FC0, 0x2FC1, 0x2FC2, 0x2FCD, 0x2FCE, 0x2FCF, 0x2FD1 - }; - private static readonly int[] ElfFemaleHairLabels = - { - 3000340, 1074386, 1074387, 1074388, 1074389, 1074391, 1074392, 1074393, 1074394 - }; - private static readonly int[] ElfFemaleHairGraphics = - { - 0, 0x2FC0, 0x2FC1, 0x2FC2, 0x2FCC, 0x2FCE, 0x2FCF, 0x2FD0, 0x2FD1 - }; - private static readonly int[] GargoyleHairLabels = - { - 3000340, 1112310, 1112311, 1112312, 1112313, 1112314, 1112315, 1112316, 1112317 - }; - private static readonly int[] GargoyleHairGraphics = - { - 0, 0x4258, 0x4259, 0x425A, 0x425B, 0x425C, 0x425D, 0x425E, 0x425F - }; - private static readonly int[] GargoyleFacialLabels = - { - 3000340, 1112310, 1112311, 1112312, 1112313 - }; - private static readonly int[] GargoyleFacialGraphics = - { - 0, 0x42AD, 0x42AE, 0x42AF, 0x42B0 - }; - private static readonly int[] GargoyleFemaleHairLabels = - { - 3000340, 1112310, 1112311, 1112312, 1112313, 1112314, 1112315, 1112316, 1112317 - }; - private static readonly int[] GargoyleFemaleHairGraphics = - { - 0, 0x4261, 0x4262, 0x4273, 0x4274, 0x4275, 0x42AA, 0x42AB, 0x42B1 - }; - - public static ushort[] GetSkinPallet(RaceType race) - { - switch (race) - { - case RaceType.HUMAN: return HumanSkinTone; - - case RaceType.ELF: return ElfSkinTone; - - case RaceType.GARGOYLE: return GargoyleSkinTone; - } - - return new ushort[] - { - }; - } - - public static ushort[] GetHairPallet(RaceType race) - { - switch (race) - { - case RaceType.HUMAN: return HumanHairColor; - - case RaceType.ELF: return ElfHairColor; - - case RaceType.GARGOYLE: return GargoyleHairColor; - } - - return new ushort[] - { - }; - } - - public static ComboContent GetHairComboContent(bool isFemale, RaceType race) - { - switch (race) - { - case RaceType.HUMAN: - - if (isFemale) - { - return new ComboContent(HumanFemaleHairLabels, HumanFemaleHairGraphics); - } - else - { - return new ComboContent(HumanHairLabels, HumanHairGraphics); - } - - case RaceType.ELF: - - if (isFemale) - { - return new ComboContent(ElfFemaleHairLabels, ElfFemaleHairGraphics); - } - else - { - return new ComboContent(ElfHairLabels, ElfHairGraphics); - } - - case RaceType.GARGOYLE: - - if (isFemale) - { - return new ComboContent(GargoyleFemaleHairLabels, GargoyleFemaleHairGraphics); - } - else - { - return new ComboContent(GargoyleHairLabels, GargoyleHairGraphics); - } - } - - return new ComboContent - ( - new int[] - { - }, - new int[] - { - } - ); - } - - public static ComboContent GetFacialHairComboContent(RaceType race) - { - switch (race) - { - case RaceType.HUMAN: return new ComboContent(HumanFacialLabels, HumanFacialGraphics); - - case RaceType.GARGOYLE: return new ComboContent(GargoyleFacialLabels, GargoyleFacialGraphics); - } - - return new ComboContent - ( - new int[] - { - }, - new int[] - { - } - ); - } - - internal class ComboContent - { - private readonly int[] _ids; - - public ComboContent(int[] labels, int[] ids) - { - _ids = ids; - - Labels = labels.Select(o => ClilocLoader.Instance.GetString(o)).ToArray(); - } - - public string[] Labels { get; } - - public int GetGraphic(int index) - { - return _ids[index]; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/CharacterSpeedType.cs b/src/ClassicUO.Client/Game/Data/CharacterSpeedType.cs deleted file mode 100644 index d229e26fc..000000000 --- a/src/ClassicUO.Client/Game/Data/CharacterSpeedType.cs +++ /dev/null @@ -1,42 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Data -{ - public enum CharacterSpeedType - { - Normal, - FastUnmount, - CantRun, - FastUnmountAndCantRun - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/ClientFeatures.cs b/src/ClassicUO.Client/Game/Data/ClientFeatures.cs deleted file mode 100644 index 0bbc178b2..000000000 --- a/src/ClassicUO.Client/Game/Data/ClientFeatures.cs +++ /dev/null @@ -1,92 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Utility; - -namespace ClassicUO.Game.Data -{ - [Flags] - public enum CharacterListFlags - { - CLF_UNKNOWN = 0x01, - CLF_OWERWRITE_CONFIGURATION_BUTTON = 0x02, - CLF_ONE_CHARACTER_SLOT = 0x04, - CLF_CONTEXT_MENU = 0x08, - CLF_LIMIT_CHARACTER_SLOTS = 0x10, - CLF_PALADIN_NECROMANCER_TOOLTIPS = 0x20, - CLF_6_CHARACTER_SLOT = 0x40, - CLF_SAMURAI_NINJA = 0x80, - CLF_ELVEN_RACE = 0x100, - CLF_UNKNOWN_1 = 0x200, - CLF_UO3D = 0x400, - CLF_UNKNOWN_2 = 0x800, - CLF_7_CHARACTER_SLOT = 0x1000, - CLF_UNKNOWN_3 = 0x2000, - CLF_NEW_MOVEMENT_SYSTEM = 0x4000, - CLF_UNLOCK_FELUCCA_AREAS = 0x8000 - } - - public class ClientFeatures - { - public CharacterListFlags Flags { get; private set; } - - public bool TooltipsEnabled { get; private set; } = true; - public bool PopupEnabled { get; private set; } - public bool PaperdollBooks { get; private set; } - public uint MaxChars { get; private set; } = 5; - - public void SetFlags(CharacterListFlags flags) - { - Flags = flags; - - if ((flags & CharacterListFlags.CLF_ONE_CHARACTER_SLOT) != 0) - { - MaxChars = 1; - } - else if ((flags & CharacterListFlags.CLF_7_CHARACTER_SLOT) != 0) - { - MaxChars = 7; - } - else if ((flags & CharacterListFlags.CLF_6_CHARACTER_SLOT) != 0) - { - MaxChars = 6; - } - - PopupEnabled = (flags & CharacterListFlags.CLF_CONTEXT_MENU) != 0; - - TooltipsEnabled = (flags & CharacterListFlags.CLF_PALADIN_NECROMANCER_TOOLTIPS) != 0 && Client.Version >= ClientVersion.CV_308Z; - - PaperdollBooks = (flags & CharacterListFlags.CLF_PALADIN_NECROMANCER_TOOLTIPS) != 0; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/ClientProtocol.cs b/src/ClassicUO.Client/Game/Data/ClientProtocol.cs deleted file mode 100644 index 6c7308d2e..000000000 --- a/src/ClassicUO.Client/Game/Data/ClientProtocol.cs +++ /dev/null @@ -1,52 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; - -namespace ClassicUO.Game.Data -{ - [Flags] - internal enum ClientFlags : uint - { - CF_T2A = 0x00, - CF_RE = 0x01, - CF_TD = 0x02, - CF_LBR = 0x04, - CF_AOS = 0x08, - CF_SE = 0x10, - CF_SA = 0x20, - CF_UO3D = 0x40, - CF_RESERVED = 0x80, - CF_3D = 0x100, - CF_UNDEFINED = 0xFFFF - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/ContainerData.cs b/src/ClassicUO.Client/Game/Data/ContainerData.cs deleted file mode 100644 index 94ad0871f..000000000 --- a/src/ClassicUO.Client/Game/Data/ContainerData.cs +++ /dev/null @@ -1,70 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.Data -{ - internal struct ContainerData - { - public ContainerData - ( - ushort graphic, - ushort sound, - ushort closed, - int x, - int y, - int w, - int h, - ushort iconizedgraphic = 0, - int minimizerX = 0, - int minimizerY = 0 - ) - { - Graphic = graphic; - Bounds = new Rectangle(x, y, w, h); - OpenSound = sound; - ClosedSound = closed; - - MinimizerArea = minimizerX == 0 && minimizerY == 0 ? Rectangle.Empty : new Rectangle(minimizerX, minimizerY, 16, 16); - - IconizedGraphic = iconizedgraphic; - } - - public ushort Graphic; - public Rectangle Bounds; - public ushort OpenSound; - public ushort ClosedSound; - public Rectangle MinimizerArea; - public ushort IconizedGraphic; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/CustomHouse.cs b/src/ClassicUO.Client/Game/Data/CustomHouse.cs deleted file mode 100644 index 6c4bc010a..000000000 --- a/src/ClassicUO.Client/Game/Data/CustomHouse.cs +++ /dev/null @@ -1,500 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; - -namespace ClassicUO.Game.Data -{ - public abstract class CustomHouseObject - { - public int Category; - public int FeatureMask; - - public virtual bool Parse(string text) - { - return false; - } - - public abstract int Contains(ushort graphic); - } - - public abstract class CustomHouseObjectCategory where T : CustomHouseObject - { - public int Index; - public List Items = new List(); - } - - public class CustomHouseWall : CustomHouseObject - { - public const int GRAPHICS_COUNT = 8; - public ushort[] Graphics = new ushort[GRAPHICS_COUNT]; - - - public int Style, TID, South1, South2, South3, Corner, East1, East2, East3, Post, WindowS, AltWindowS, WindowE, AltWindowE, SecondAltWindowS, SecondAltWindowE; - public ushort[] WindowGraphics = new ushort[GRAPHICS_COUNT]; - - public override int Contains(ushort graphic) - { - for (int i = 0; i < GRAPHICS_COUNT; i++) - { - if (Graphics[i] == graphic || WindowGraphics[i] == graphic) - { - return i; - } - } - - return -1; - } - - public override bool Parse(string text) - { - string[] scanf = text.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); - - bool result = false; - - if (scanf.Length >= 17) - { - result = int.TryParse(scanf[0], out Category) && int.TryParse(scanf[1], out Style) && int.TryParse(scanf[2], out TID) && int.TryParse(scanf[3], out South1) && int.TryParse(scanf[4], out South2) && int.TryParse(scanf[5], out South3) && int.TryParse(scanf[6], out Corner) && int.TryParse(scanf[7], out East1) && int.TryParse(scanf[8], out East2) && int.TryParse(scanf[9], out East3) && int.TryParse(scanf[10], out Post) && int.TryParse(scanf[11], out WindowS) && int.TryParse(scanf[12], out AltWindowS) && int.TryParse(scanf[13], out WindowE) && int.TryParse(scanf[14], out AltWindowE) && int.TryParse(scanf[15], out SecondAltWindowS) && int.TryParse(scanf[16], out SecondAltWindowE) && int.TryParse(scanf[17], out FeatureMask); - } - - if (result) - { - WindowGraphics[0] = Graphics[0] = (ushort) South1; - WindowGraphics[1] = Graphics[1] = (ushort) South2; - WindowGraphics[2] = Graphics[2] = (ushort) South3; - WindowGraphics[3] = Graphics[3] = (ushort) Corner; - WindowGraphics[4] = Graphics[4] = (ushort) East1; - WindowGraphics[5] = Graphics[5] = (ushort) East2; - WindowGraphics[6] = Graphics[6] = (ushort) East3; - WindowGraphics[7] = Graphics[7] = (ushort) Post; - } - - if (AltWindowE == 0 && WindowE != 0) - { - AltWindowE = WindowE; - WindowE = 0; - } - - if (WindowS != 0) - { - WindowGraphics[0] = (ushort) WindowS; - } - - if (AltWindowS != 0) - { - WindowGraphics[1] = (ushort) AltWindowS; - } - - if (SecondAltWindowS != 0) - { - WindowGraphics[2] = (ushort) SecondAltWindowS; - } - - if (WindowE != 0) - { - WindowGraphics[4] = (ushort) WindowE; - } - - if (AltWindowE != 0) - { - WindowGraphics[5] = (ushort) AltWindowE; - } - - if (SecondAltWindowE != 0) - { - WindowGraphics[6] = (ushort) SecondAltWindowE; - } - - return result; - } - } - - public class CustomHouseWallCategory : CustomHouseObjectCategory - { - } - - public class CustomHouseFloor : CustomHouseObject - { - public const int GRAPHICS_COUNT = 16; - - public int F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16; - public ushort[] Graphics = new ushort[GRAPHICS_COUNT]; - - public override bool Parse(string text) - { - string[] scanf = text.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); - - bool result = false; - - if (scanf.Length >= 17) - { - result = int.TryParse(scanf[0], out Category) && int.TryParse(scanf[1], out F1) && int.TryParse(scanf[2], out F2) && int.TryParse(scanf[3], out F3) && int.TryParse(scanf[4], out F4) && int.TryParse(scanf[5], out F5) && int.TryParse(scanf[6], out F6) && int.TryParse(scanf[7], out F7) && int.TryParse(scanf[8], out F8) && int.TryParse(scanf[9], out F9) && int.TryParse(scanf[10], out F10) && int.TryParse(scanf[11], out F11) && int.TryParse(scanf[12], out F12) && int.TryParse(scanf[13], out F13) && int.TryParse(scanf[14], out F14) && int.TryParse(scanf[15], out F15) && int.TryParse(scanf[16], out F16) && int.TryParse(scanf[17], out FeatureMask); - } - - if (result) - { - Graphics[0] = (ushort) F1; - Graphics[1] = (ushort) F2; - Graphics[2] = (ushort) F3; - Graphics[3] = (ushort) F4; - Graphics[4] = (ushort) F5; - Graphics[5] = (ushort) F6; - Graphics[6] = (ushort) F7; - Graphics[7] = (ushort) F8; - Graphics[8] = (ushort) F9; - Graphics[9] = (ushort) F10; - Graphics[10] = (ushort) F11; - Graphics[11] = (ushort) F12; - Graphics[12] = (ushort) F13; - Graphics[13] = (ushort) F14; - Graphics[14] = (ushort) F15; - Graphics[15] = (ushort) F16; - } - - return result; - } - - public override int Contains(ushort graphic) - { - for (int i = 0; i < GRAPHICS_COUNT; i++) - { - if (Graphics[i] == graphic) - { - return i; - } - } - - return -1; - } - } - - public class CustomHouseRoof : CustomHouseObject - { - public const int GRAPHICS_COUNT = 16; - public ushort[] Graphics = new ushort[GRAPHICS_COUNT]; - - public int Style, TID, North, East, South, West, NSCrosspiece, EWCrosspiece, NDent, SDent, WDent, NTPiece, ETPiece, STPiece, WTPiece, XPiece, Extra, Piece; - - public override bool Parse(string text) - { - string[] scanf = text.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); - - bool result = false; - - if (scanf.Length >= 19) - { - result = int.TryParse(scanf[0], out Category) && int.TryParse(scanf[1], out Style) && int.TryParse(scanf[2], out TID) && int.TryParse(scanf[3], out North) && int.TryParse(scanf[4], out East) && int.TryParse(scanf[5], out South) && int.TryParse(scanf[6], out West) && int.TryParse(scanf[7], out NSCrosspiece) && int.TryParse(scanf[8], out EWCrosspiece) && int.TryParse(scanf[9], out NDent) && int.TryParse(scanf[10], out SDent) && int.TryParse(scanf[11], out WDent) && int.TryParse(scanf[12], out NTPiece) && int.TryParse(scanf[13], out ETPiece) && int.TryParse(scanf[14], out STPiece) && int.TryParse(scanf[15], out WTPiece) && int.TryParse(scanf[16], out XPiece) && int.TryParse(scanf[17], out Extra) && int.TryParse(scanf[18], out Piece) && int.TryParse(scanf[19], out FeatureMask); - } - - if (result) - { - Graphics[0] = (ushort) North; - Graphics[1] = (ushort) East; - Graphics[2] = (ushort) South; - Graphics[3] = (ushort) West; - Graphics[4] = (ushort) NSCrosspiece; - Graphics[5] = (ushort) EWCrosspiece; - Graphics[6] = (ushort) NDent; - Graphics[7] = (ushort) SDent; - Graphics[8] = (ushort) WDent; - Graphics[9] = (ushort) NTPiece; - Graphics[10] = (ushort) ETPiece; - Graphics[11] = (ushort) STPiece; - Graphics[12] = (ushort) WTPiece; - Graphics[13] = (ushort) XPiece; - Graphics[14] = (ushort) Extra; - Graphics[15] = (ushort) Piece; - } - - return result; - } - - public override int Contains(ushort graphic) - { - for (int i = 0; i < GRAPHICS_COUNT; i++) - { - if (Graphics[i] == graphic) - { - return i; - } - } - - return -1; - } - } - - public class CustomHouseRoofCategory : CustomHouseObjectCategory - { - } - - public class CustomHouseMisc : CustomHouseObject - { - public const int GRAPHICS_COUNT = 8; - public ushort[] Graphics = new ushort[GRAPHICS_COUNT]; - - public int Style, TID, Piece1, Piece2, Piece3, Piece4, Piece5, Piece6, Piece7, Piece8; - - public override bool Parse(string text) - { - string[] scanf = text.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); - - bool result = false; - - if (scanf.Length >= 11) - { - result = int.TryParse(scanf[0], out Category) && int.TryParse(scanf[1], out Style) && int.TryParse(scanf[2], out TID) && int.TryParse(scanf[3], out Piece1) && int.TryParse(scanf[4], out Piece2) && int.TryParse(scanf[5], out Piece3) && int.TryParse(scanf[6], out Piece4) && int.TryParse(scanf[7], out Piece5) && int.TryParse(scanf[8], out Piece6) && int.TryParse(scanf[9], out Piece7) && int.TryParse(scanf[10], out Piece8) && int.TryParse(scanf[11], out FeatureMask); - } - - if (result) - { - Graphics[0] = (ushort) Piece1; - Graphics[1] = (ushort) Piece2; - Graphics[2] = (ushort) Piece3; - Graphics[3] = (ushort) Piece4; - Graphics[4] = (ushort) Piece5; - Graphics[5] = (ushort) Piece6; - Graphics[6] = (ushort) Piece7; - Graphics[7] = (ushort) Piece8; - } - - return result; - } - - public override int Contains(ushort graphic) - { - for (int i = 0; i < GRAPHICS_COUNT; i++) - { - if (Graphics[i] == graphic) - { - return i; - } - } - - return -1; - } - } - - public class CustomHouseMiscCategory : CustomHouseObjectCategory - { - } - - public class CustomHouseDoor : CustomHouseObject - { - public const int GRAPHICS_COUNT = 8; - public ushort[] Graphics = new ushort[GRAPHICS_COUNT]; - - public int Piece1, Piece2, Piece3, Piece4, Piece5, Piece6, Piece7, Piece8; - - public override bool Parse(string text) - { - string[] scanf = text.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); - - bool result = false; - - if (scanf.Length >= 9) - { - result = int.TryParse(scanf[0], out Category) && int.TryParse(scanf[1], out Piece1) && int.TryParse(scanf[2], out Piece2) && int.TryParse(scanf[3], out Piece3) && int.TryParse(scanf[4], out Piece4) && int.TryParse(scanf[5], out Piece5) && int.TryParse(scanf[6], out Piece6) && int.TryParse(scanf[7], out Piece7) && int.TryParse(scanf[8], out Piece8) && int.TryParse(scanf[9], out FeatureMask); - } - - if (result) - { - Graphics[0] = (ushort) Piece1; - Graphics[1] = (ushort) Piece2; - Graphics[2] = (ushort) Piece3; - Graphics[3] = (ushort) Piece4; - Graphics[4] = (ushort) Piece5; - Graphics[5] = (ushort) Piece6; - Graphics[6] = (ushort) Piece7; - Graphics[7] = (ushort) Piece8; - } - - return result; - } - - public override int Contains(ushort graphic) - { - for (int i = 0; i < GRAPHICS_COUNT; i++) - { - if (Graphics[i] == graphic) - { - return i; - } - } - - return -1; - } - } - - public class CustomHouseTeleport : CustomHouseObject - { - public const int GRAPHICS_COUNT = 16; - - public int F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16; - public ushort[] Graphics = new ushort[GRAPHICS_COUNT]; - - public override bool Parse(string text) - { - string[] scanf = text.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); - - bool result = false; - - if (scanf.Length >= 17) - { - result = int.TryParse(scanf[0], out Category) && int.TryParse(scanf[1], out F1) && int.TryParse(scanf[2], out F2) && int.TryParse(scanf[3], out F3) && int.TryParse(scanf[4], out F4) && int.TryParse(scanf[5], out F5) && int.TryParse(scanf[6], out F6) && int.TryParse(scanf[7], out F7) && int.TryParse(scanf[8], out F8) && int.TryParse(scanf[9], out F9) && int.TryParse(scanf[10], out F10) && int.TryParse(scanf[11], out F11) && int.TryParse(scanf[12], out F12) && int.TryParse(scanf[13], out F13) && int.TryParse(scanf[14], out F14) && int.TryParse(scanf[15], out F15) && int.TryParse(scanf[16], out F16) && int.TryParse(scanf[17], out FeatureMask); - } - - if (result) - { - Graphics[0] = (ushort) F1; - Graphics[1] = (ushort) F2; - Graphics[2] = (ushort) F3; - Graphics[3] = (ushort) F4; - Graphics[4] = (ushort) F5; - Graphics[5] = (ushort) F6; - Graphics[6] = (ushort) F7; - Graphics[7] = (ushort) F8; - Graphics[8] = (ushort) F9; - Graphics[9] = (ushort) F10; - Graphics[10] = (ushort) F11; - Graphics[11] = (ushort) F12; - Graphics[12] = (ushort) F13; - Graphics[13] = (ushort) F14; - Graphics[14] = (ushort) F15; - Graphics[15] = (ushort) F16; - } - - return result; - } - - public override int Contains(ushort graphic) - { - for (int i = 0; i < GRAPHICS_COUNT; i++) - { - if (Graphics[i] == graphic) - { - return i; - } - } - - return -1; - } - } - - public class CustomHouseStair : CustomHouseObject - { - public const int GRAPHICS_COUNT = 9; - - public int Block, North, East, South, West, Squared1, Squared2, Rounded1, Rounded2, MultiNorth, MultiEast, MultiSouth, MultiWest; - public ushort[] Graphics = new ushort[GRAPHICS_COUNT]; - - public override bool Parse(string text) - { - string[] scanf = text.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); - - bool result = false; - - if (scanf.Length >= 14) - { - result = int.TryParse(scanf[0], out Category) && int.TryParse(scanf[1], out Block) && int.TryParse(scanf[2], out North) && int.TryParse(scanf[3], out East) && int.TryParse(scanf[4], out South) && int.TryParse(scanf[5], out West) && int.TryParse(scanf[6], out Squared1) && int.TryParse(scanf[7], out Squared2) && int.TryParse(scanf[8], out Rounded1) && int.TryParse(scanf[9], out Rounded2) && int.TryParse(scanf[10], out MultiNorth) && int.TryParse(scanf[11], out MultiEast) && int.TryParse(scanf[12], out MultiSouth) && int.TryParse(scanf[13], out MultiWest) && int.TryParse(scanf[14], out FeatureMask); - } - - if (result) - { - Graphics[0] = (ushort) (MultiNorth != 0 ? Squared1 : 0); - Graphics[1] = (ushort) (MultiEast != 0 ? Squared2 : 0); - Graphics[2] = (ushort) (MultiSouth != 0 ? Rounded1 : 0); - Graphics[3] = (ushort) (MultiWest != 0 ? Rounded2 : 0); - Graphics[4] = (ushort) Block; - Graphics[5] = (ushort) North; - Graphics[6] = (ushort) East; - Graphics[7] = (ushort) South; - Graphics[8] = (ushort) West; - } - - return result; - } - - public override int Contains(ushort graphic) - { - for (int i = 0; i < GRAPHICS_COUNT; i++) - { - if (Graphics[i] == graphic) - { - return i; - } - } - - return -1; - } - } - - public class CustomHousePlaceInfo : CustomHouseObject - { - public const int GRAPHICS_COUNT = 1; - public int Graphic, Top, Bottom, AdjUN, AdjLN, AdjUE, AdjLE, AdjUS, AdjLS, AdjUW, AdjLW, DirectSupports, CanGoW, CanGoN, CanGoNWS; - - public ushort[] Graphics = new ushort[GRAPHICS_COUNT]; - - public override bool Parse(string text) - { - string[] scanf = text.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); - - bool result = false; - - if (scanf.Length >= 16) - { - result = int.TryParse(scanf[1], out Graphic) && int.TryParse(scanf[2], out Top) && int.TryParse(scanf[3], out Bottom) && int.TryParse(scanf[4], out AdjUN) && int.TryParse(scanf[5], out AdjLN) && int.TryParse(scanf[6], out AdjUE) && int.TryParse(scanf[7], out AdjLE) && int.TryParse(scanf[8], out AdjUS) && int.TryParse(scanf[9], out AdjLS) && int.TryParse(scanf[10], out AdjUW) && int.TryParse(scanf[11], out AdjLW) && int.TryParse(scanf[12], out DirectSupports) && int.TryParse(scanf[13], out CanGoW) && int.TryParse(scanf[14], out CanGoN) && int.TryParse(scanf[15], out CanGoNWS); - } - - if (result) - { - Graphics[0] = (ushort) Graphic; - } - - return result; - } - - public override int Contains(ushort graphic) - { - for (int i = 0; i < GRAPHICS_COUNT; i++) - { - if (Graphics[i] == graphic) - { - return i; - } - } - - return -1; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/Direction.cs b/src/ClassicUO.Client/Game/Data/Direction.cs deleted file mode 100644 index 4faf3441b..000000000 --- a/src/ClassicUO.Client/Game/Data/Direction.cs +++ /dev/null @@ -1,226 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.Data -{ - [Flags] - public enum Direction : byte - { - North = 0x00, - Right = 0x01, - East = 0x02, - Down = 0x03, - South = 0x04, - Left = 0x05, - West = 0x06, - Up = 0x07, - Mask = 0x7, - Running = 0x80, - NONE = 0xED - } - - internal static class DirectionHelper - { - public static Direction DirectionFromPoints(Point from, Point to) - { - return DirectionFromVectors(new Vector2(from.X, from.Y), new Vector2(to.X, to.Y)); - } - - public static Direction DirectionFromVectors(Vector2 fromPosition, Vector2 toPosition) - { - double Angle = Math.Atan2(toPosition.Y - fromPosition.Y, toPosition.X - fromPosition.X); - - if (Angle < 0) - { - Angle = Math.PI + (Math.PI + Angle); - } - - double piPerSegment = Math.PI * 2f / 8f; - double segmentValue = Math.PI * 2f / 16f; - int direction = int.MaxValue; - - for (int i = 0; i < 8; i++) - { - if (Angle >= segmentValue && Angle <= segmentValue + piPerSegment) - { - direction = i + 1; - - break; - } - - segmentValue += piPerSegment; - } - - if (direction == int.MaxValue) - { - direction = 0; - } - - direction = direction >= 7 ? direction - 7 : direction + 1; - - return (Direction) direction; - } - - public static Direction GetDirectionAB(int AAx, int AAy, int BBx, int BBy) - { - int dx = AAx - BBx; - int dy = AAy - BBy; - - int rx = (dx - dy) * 44; - int ry = (dx + dy) * 44; - - int ax = Math.Abs(rx); - int ay = Math.Abs(ry); - - Direction ret; - - if ((ay >> 1) - ax >= 0) - { - ret = ry > 0 ? Direction.Up : Direction.Down; - } - else if ((ax >> 1) - ay >= 0) - { - ret = rx > 0 ? Direction.Left : Direction.Right; - } - else if (rx >= 0 && ry >= 0) - { - ret = Direction.West; - } - else if (rx >= 0 && ry < 0) - { - ret = Direction.South; - } - else if (rx < 0 && ry < 0) - { - ret = Direction.East; - } - else - { - ret = Direction.North; - } - - return ret; - } - - public static Direction CalculateDirection(int curX, int curY, int newX, int newY) - { - int deltaX = newX - curX; - int deltaY = newY - curY; - - if (deltaX > 0) - { - if (deltaY > 0) - { - return Direction.Down; - } - - return deltaY == 0 ? Direction.East : Direction.Right; - } - - if (deltaX == 0) - { - if (deltaY > 0) - { - return Direction.South; - } - - return deltaY == 0 ? Direction.NONE : Direction.North; - } - - if (deltaY > 0) - { - return Direction.Left; - } - - return deltaY == 0 ? Direction.West : Direction.Up; - } - - public static Direction DirectionFromKeyboardArrows(bool upPressed, bool downPressed, bool leftPressed, bool rightPressed) - { - int direction = (int) Direction.NONE; - - if (upPressed) - { - if (leftPressed) - { - direction = 6; - } - else if (rightPressed) - { - direction = 0; - } - else - { - direction = 7; - } - } - else if (downPressed) - { - if (leftPressed) - { - direction = 4; - } - else if (rightPressed) - { - direction = 2; - } - else - { - direction = 3; - } - } - else if (leftPressed) - { - direction = 5; - } - else if (rightPressed) - { - direction = 1; - } - - return (Direction) direction; - } - - public static Direction GetCardinal(Direction inDirection) - { - return inDirection & (Direction) 0x6; - } - - public static Direction Reverse(Direction inDirection) - { - return (Direction) ((int) inDirection + 0x04) & Direction.Up; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/EntityFlags.cs b/src/ClassicUO.Client/Game/Data/EntityFlags.cs deleted file mode 100644 index 31bfd3513..000000000 --- a/src/ClassicUO.Client/Game/Data/EntityFlags.cs +++ /dev/null @@ -1,51 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; - -namespace ClassicUO.Game.Data -{ - [Flags] - public enum Flags : byte - { - None, - Frozen = 0x01, - Female = 0x02, - Poisoned = 0x04, - Flying = 0x04, - YellowBar = 0x08, - IgnoreMobiles = 0x10, - Movable = 0x20, - WarMode = 0x40, - Hidden = 0x80 - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/GraphicEffectBlendMode.cs b/src/ClassicUO.Client/Game/Data/GraphicEffectBlendMode.cs deleted file mode 100644 index 078704309..000000000 --- a/src/ClassicUO.Client/Game/Data/GraphicEffectBlendMode.cs +++ /dev/null @@ -1,46 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Data -{ - public enum GraphicEffectBlendMode - { - Normal = 0x00, // normal, black is transparent - Multiply = 0x01, // darken - Screen = 0x02, // lighten - ScreenMore = 0x03, // lighten more (slightly) - ScreenLess = 0x04, // lighten less - NormalHalfTransparent = 0x05, // transparent but with black edges - 50% transparency? - ShadowBlue = 0x06, // complete shadow with blue edges - ScreenRed = 0x07 // transparent more red - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/GraphicEffectType.cs b/src/ClassicUO.Client/Game/Data/GraphicEffectType.cs deleted file mode 100644 index b17af8378..000000000 --- a/src/ClassicUO.Client/Game/Data/GraphicEffectType.cs +++ /dev/null @@ -1,47 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Data -{ - public enum GraphicEffectType - { - Moving = 0x00, - Lightning = 0x01, - FixedXYZ = 0x02, - FixedFrom = 0x03, - ScreenFade = 0x04, - - DragEffect = 0x05, // custom - - Nothing = 0xFF - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/LayerOrder.cs b/src/ClassicUO.Client/Game/Data/LayerOrder.cs deleted file mode 100644 index b00db6455..000000000 --- a/src/ClassicUO.Client/Game/Data/LayerOrder.cs +++ /dev/null @@ -1,96 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Data -{ - internal static class LayerOrder - { - public static Layer[,] UsedLayers { get; } = new Layer[8, Constants.USED_LAYER_COUNT] - { - { - // 0 - Layer.Shirt, Layer.Pants, Layer.Shoes, Layer.Legs, Layer.Torso, Layer.Ring, Layer.Talisman, - Layer.Bracelet, Layer.Face, Layer.Arms, Layer.Gloves, Layer.Skirt, Layer.Tunic, Layer.Robe, - Layer.Necklace, Layer.Hair, Layer.Waist, Layer.Beard, Layer.Earrings, Layer.OneHanded, Layer.Helmet, - Layer.TwoHanded, Layer.Cloak - }, - { - // 1 - Layer.Shirt, Layer.Pants, Layer.Shoes, Layer.Legs, Layer.Torso, Layer.Ring, Layer.Talisman, - Layer.Bracelet, Layer.Face, Layer.Arms, Layer.Gloves, Layer.Skirt, Layer.Tunic, Layer.Robe, - Layer.Necklace, Layer.Hair, Layer.Waist, Layer.Beard, Layer.Earrings, Layer.OneHanded, Layer.Cloak, - Layer.Helmet, Layer.TwoHanded - }, - { - // 2 - Layer.Shirt, Layer.Pants, Layer.Shoes, Layer.Legs, Layer.Torso, Layer.Ring, Layer.Talisman, - Layer.Bracelet, Layer.Face, Layer.Arms, Layer.Gloves, Layer.Skirt, Layer.Tunic, Layer.Robe, - Layer.Necklace, Layer.Hair, Layer.Waist, Layer.Beard, Layer.Earrings, Layer.OneHanded, Layer.Cloak, - Layer.Helmet, Layer.TwoHanded - }, - { - // 3 - Layer.Cloak, Layer.Shirt, Layer.Pants, Layer.Shoes, Layer.Legs, Layer.Torso, Layer.Ring, Layer.Talisman, - Layer.Bracelet, Layer.Face, Layer.Arms, Layer.Gloves, Layer.Skirt, Layer.Tunic, Layer.Robe, Layer.Waist, - Layer.Necklace, Layer.Hair, Layer.Beard, Layer.Earrings, Layer.Helmet, Layer.OneHanded, Layer.TwoHanded - }, - { - // 4 - Layer.Shirt, Layer.Pants, Layer.Shoes, Layer.Legs, Layer.Torso, Layer.Ring, Layer.Talisman, - Layer.Bracelet, Layer.Face, Layer.Arms, Layer.Gloves, Layer.Skirt, Layer.Tunic, Layer.Robe, - Layer.Necklace, Layer.Hair, Layer.Waist, Layer.Beard, Layer.Earrings, Layer.OneHanded, Layer.Cloak, - Layer.Helmet, Layer.TwoHanded - }, - { - // 5 - Layer.Shirt, Layer.Pants, Layer.Shoes, Layer.Legs, Layer.Torso, Layer.Ring, Layer.Talisman, - Layer.Bracelet, Layer.Face, Layer.Arms, Layer.Gloves, Layer.Skirt, Layer.Tunic, Layer.Robe, - Layer.Necklace, Layer.Hair, Layer.Waist, Layer.Beard, Layer.Earrings, Layer.OneHanded, Layer.Cloak, - Layer.Helmet, Layer.TwoHanded - }, - { - // 6 - Layer.Shirt, Layer.Pants, Layer.Shoes, Layer.Legs, Layer.Torso, Layer.Ring, Layer.Talisman, - Layer.Bracelet, Layer.Face, Layer.Arms, Layer.Gloves, Layer.Skirt, Layer.Tunic, Layer.Robe, - Layer.Necklace, Layer.Hair, Layer.Waist, Layer.Beard, Layer.Earrings, Layer.OneHanded, Layer.Cloak, - Layer.Helmet, Layer.TwoHanded - }, - { - // 7 - Layer.Shirt, Layer.Pants, Layer.Shoes, Layer.Legs, Layer.Torso, Layer.Ring, Layer.Talisman, - Layer.Bracelet, Layer.Face, Layer.Arms, Layer.Gloves, Layer.Skirt, Layer.Tunic, Layer.Robe, - Layer.Necklace, Layer.Hair, Layer.Waist, Layer.Beard, Layer.Earrings, Layer.OneHanded, Layer.Cloak, - Layer.Helmet, Layer.TwoHanded - } - }; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/Layers.cs b/src/ClassicUO.Client/Game/Data/Layers.cs deleted file mode 100644 index 22a9c1b80..000000000 --- a/src/ClassicUO.Client/Game/Data/Layers.cs +++ /dev/null @@ -1,96 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Data -{ - public enum Layer : byte - { - Invalid = 0x00, - OneHanded = 0x01, - TwoHanded = 0x02, - Shoes = 0x03, - Pants = 0x04, - Shirt = 0x05, - Helmet = 0x06, - Gloves = 0x07, - Ring = 0x08, - Talisman = 0x09, - Necklace = 0x0A, - Hair = 0x0B, - Waist = 0x0C, - Torso = 0x0D, - Bracelet = 0x0E, - Face = 0x0F, - Beard = 0x10, - Tunic = 0x11, - Earrings = 0x12, - Arms = 0x13, - Cloak = 0x14, - Backpack = 0x15, - Robe = 0x16, - Skirt = 0x17, - Legs = 0x18, - Mount = 0x19, - ShopBuyRestock = 0x1A, - ShopBuy = 0x1B, - ShopSell = 0x1C, - Bank = 0x1D - } - - public enum TooltipLayers : byte - { - Any = 0x00, - OneHanded = 0x01, - TwoHanded = 0x02, - Shoes = 0x03, - Pants = 0x04, - Shirt = 0x05, - Helmet = 0x06, - Gloves = 0x07, - Ring = 0x08, - Talisman = 0x09, - Necklace = 0x0A, - Waist = 0x0C, - Torso = 0x0D, - Bracelet = 0x0E, - Tunic = 0x11, - Earrings = 0x12, - Arms = 0x13, - Cloak = 0x14, - Robe = 0x16, - Skirt = 0x17, - Legs = 0x18, - Body_Group = 0xA1, - Jewelry_Group = 0xA2, - Weapon_Group = 0xA3 - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/LightColors.cs b/src/ClassicUO.Client/Game/Data/LightColors.cs deleted file mode 100644 index f70878692..000000000 --- a/src/ClassicUO.Client/Game/Data/LightColors.cs +++ /dev/null @@ -1,527 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Utility; -using System; -using System.Collections.Generic; -using System.IO; - -namespace ClassicUO.Game.Data -{ - internal static class LightColors - { - - private static readonly Dictionary _shaderdata = new Dictionary(); - private static readonly Dictionary _itemlightdata = new Dictionary(); - - public static bool GetHue(ushort id, out ushort color, out bool ishue) - { - - ishue = false; - color = ushort.MaxValue; - - if (_itemlightdata.TryGetValue(id, out ItemLightData lightdata)) - { - ishue = lightdata.IsHue; - color = lightdata.Color; - return true; - } - - switch (id) - { - case 0x088C: - color = 31; - - break; - - case 0x0FAC: - color = 30; - - break; - - case 0x0FB1: - color = 60; - - break; - - case 0x1647: - color = 61; - - break; - - case 0x19BB: - case 0x1F2B: - color = 40; - - break; - - case 0x9F66: - color = 0; - - break; - } - - - if (id < 0x09FB || id > 0x0A14) - { - if (id < 0x0A15 || id > 0x0A29) - { - if (id < 0x0B1A || id > 0x0B1F) - { - if (id < 0x0B20 || id > 0x0B25) - { - if (id < 0x0B26 || id > 0x0B28) - { - if (id < 0x0DE1 || id > 0x0DEA) - { - if (id < 0x1849 || id > 0x1850) - { - if (id < 0x1853 || id > 0x185A) - { - if (id < 0x197A || id > 0x19A9) - { - if (id < 0x19AB || id > 0x19B6) - { - if (id >= 0x1ECD && id <= 0x1ECF || id >= 0x1ED0 && id <= 0x1ED2) - { - color = 1; - } - } - else - { - color = 60; - } - } - else - { - color = 60; - } - } - else - { - color = 61; - } - } - else - { - color = 61; - } - } - else - { - color = 31; - } - } - else - { - color = 0; - } - } - else - { - color = 0; - } - } - else - { - color = 0; - } - } - else - { - color = 0; - } - } - else - { - color = 30; - } - - if (id == 0x1FD4 || id == 0x0F6C) - { - color = 2; - } - - if (id < 0x0E2D || id > 0x0E30) - { - if (id < 0x0E31 || id > 0x0E33) - { - if (id < 0x0E5C || id > 0x0E6A) - { - if (id < 0x12EE || id > 0x134D) - { - if (id < 0x306A || id > 0x329B) - { - if (id < 0x343B || id > 0x346C) - { - if (id < 0x3547 || id > 0x354C) - { - if (id < 0x3914 || id > 0x3929) - { - if (id < 0x3946 || id > 0x3964) - { - if (id < 0x3967 || id > 0x397A) - { - if (id < 0x398C || id > 0x399F) - { - if (id < 0x3E02 || id > 0x3E0B) - { - if (id < 0x3E27 || id > 0x3E3A) - { - switch (id) - { - case 0x40FE: - color = 40; - - break; - - case 0x40FF: - color = 10; - - break; - - case 0x4100: - color = 20; - - break; - - case 0x4101: - color = 32; - - break; - - default: - - if (id >= 0x983B && id <= 0x983D || id >= 0x983F && id <= 0x9841) - { - color = 30; - } - - break; - } - } - else - { - color = 31; - } - } - else - { - color = 1; - } - } - else - { - color = 31; - } - } - else - { - color = 6; - } - } - else - { - color = 6; - } - } - else - { - color = 1; - } - } - else - { - color = 31; - } - } - else - { - color = 31; - } - } - else - { - color = 31; - } - } - else - { - color = 31; - } - } - else - { - color = 6; - } - } - else - { - color = 40; - } - } - else - { - color = 62; - } - - if (color == ushort.MaxValue) - { - return false; - } - - return true; - } - - private static void MakeDefaultShaders(int count) - { - _shaderdata.Clear(); - - for (ushort i = 1; i <= count; i++) - { - _shaderdata[i] = new LightShaderData((uint)0xFF_FF_FF); - } - - // green small - _shaderdata[1] = new LightShaderData((uint)0x00_FF_00, greencurve: LightShaderCurve.A); - - // light blue - _shaderdata[2] = new LightShaderData((uint)0x7F_7F_FF); - - // dark blue - _shaderdata[6] = new LightShaderData((uint)0xFF_00_FF, bluecurve: LightShaderCurve.A, redcurve: LightShaderCurve.B); - - // blue - _shaderdata[10] = new LightShaderData((uint)0x3F_3F_FF); - - // green - _shaderdata[20] = new LightShaderData((uint)0x00_FF_00); - - // orange - _shaderdata[30] = new LightShaderData((uint)0xFF_7F_00, greencurve: LightShaderCurve.C, redcurve: LightShaderCurve.C); - - // orange small - _shaderdata[31] = new LightShaderData((uint)0xFF_7F_00, greencurve: LightShaderCurve.A, redcurve: LightShaderCurve.A); - - // purple - _shaderdata[32] = new LightShaderData((uint)0xFF_00_FF); - - // red - _shaderdata[40] = new LightShaderData((uint)0xFF_00_00); - - // yellow - _shaderdata[50] = new LightShaderData((uint)0xFF_FF_00); - - // yellow small - _shaderdata[60] = new LightShaderData((uint)0xFF_FF_00, redcurve: LightShaderCurve.A, greencurve: LightShaderCurve.A); - - // yellow medium - _shaderdata[61] = new LightShaderData((uint)0xFF_FF_00, redcurve: LightShaderCurve.D, greencurve: LightShaderCurve.D); - - // white medium - _shaderdata[62] = new LightShaderData((uint)0xFF_FF_FF, LightShaderCurve.D, LightShaderCurve.D, LightShaderCurve.D); - - // white small full - _shaderdata[63] = new LightShaderData((uint)0xFF_FF_FF, LightShaderCurve.E, LightShaderCurve.E, LightShaderCurve.E); - } - - public static void BuildLightShaderFiles(bool force) - { - string path = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Client"); - - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - path = Path.Combine(path, "lightshaders.txt"); - - if (!File.Exists(path) || force) - { - using (StreamWriter writer = new StreamWriter(File.Create(path))) - { - writer.WriteLine("# FORMAT"); - - writer.WriteLine("# ID RGB R_CURVE G_CURVE B_CURVE"); - writer.WriteLine("# HARD LIMIT IS 63"); - writer.WriteLine("#"); - writer.WriteLine("# DEFAULT SHADERS:"); - - foreach (KeyValuePair e in _shaderdata) - { - writer.WriteLine($"# {e.Key} {e.Value.RGB:X6} {e.Value.RedCurve} {e.Value.GreenCurve} {e.Value.BlueCurve}"); - } - } - } - - TextFileParser lightshadersParser = new TextFileParser(File.ReadAllText(path), new[] { ' ', '\t', ',' }, new[] { '#', ';' }, new[] { '"', '"' }); - - while (!lightshadersParser.IsEOF()) - { - List ss = lightshadersParser.ReadTokens(); - - if (ss != null && ss.Count != 0) - { - LightShaderCurve curver = LightShaderCurve.Standard; - LightShaderCurve curveg = LightShaderCurve.Standard; - LightShaderCurve curveb = LightShaderCurve.Standard; - - if (ushort.TryParse(ss[0], out ushort id) && ss.Count > 1) - { - if (ss.Count > 2) - { - Enum.TryParse(ss[2], out curver); - - if (ss.Count > 4) - { - Enum.TryParse(ss[3], out curveg); - Enum.TryParse(ss[4], out curveb); - } - else - { - curveg = curveb = curver; - } - } - - _shaderdata[id] = new LightShaderData(Convert.ToUInt32(ss[1], 16), curver, curveg, curveb); - } - } - } - } - - public static void LoadLights() - { - string path = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Client"); - - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - string lights = Path.Combine(path, "lights.txt"); - - if (!File.Exists(lights)) - { - using (StreamWriter writer = new StreamWriter(lights)) - { - writer.WriteLine("# FORMAT"); - writer.WriteLine("# ITEM_ID LIGHT_SHADER_OR_HUE"); - writer.WriteLine("#"); - writer.WriteLine("# Example for shader"); - writer.WriteLine("# 0xE31 35"); - writer.WriteLine("#"); - writer.WriteLine("# Example for hue"); - writer.WriteLine("# 0xE31 H1234"); - writer.WriteLine(""); - } - } - - TextFileParser itemlightsparser = new TextFileParser(File.ReadAllText(lights), new[] { ' ', '\t', ',' }, new[] { '#', ';' }, new[] { '"', '"' }); - - while (!itemlightsparser.IsEOF()) - { - List ss = itemlightsparser.ReadTokens(); - - if (ss != null && ss.Count != 0) - { - ItemLightData entry = new ItemLightData(); - - ushort id = ss[0].StartsWith("0x") ? Convert.ToUInt16(ss[0], 16) : Convert.ToUInt16(ss[0]); - - string color = ss[1]; - - if (color.StartsWith("H")) - { - color = color.Replace("H", ""); - entry.Color = ushort.Parse(color); - entry.Color--; - entry.IsHue = true; - } - else - { - entry.Color = ushort.Parse(color); - entry.IsHue = false; - } - - _itemlightdata[id] = entry; - } - } - } - - internal static void CreateLightTextures(uint[] buffer, int count) - { - MakeDefaultShaders(count); - BuildLightShaderFiles(false); - - byte[][] lightCurveTables = new byte[6][] - { - new byte[32] { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31}, - new byte[32] { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,6,8,10,12,14,16,18,20,22,24,26,28}, - new byte[32] { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8}, - new byte[32] { 0,1,2,4,6,8,11,14,17,20,23,26,29,30,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31}, - new byte[32] { 0,0,0,0,0,0,0,0,1,1,2,2,3,3,4,4,5,6,7,8,9,10,11,12,13,15,17,19,21,23,25,27}, - new byte[32] { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,5,10,15,20,25,30,30,18,18,18,18,18,18,18}, - }; - - foreach (KeyValuePair entry in _shaderdata) - { - for (uint i = 0; i < 32; i++) - { - uint r = (entry.Value.RGB & 0xFF_00_00) >> 16; - uint g = (entry.Value.RGB & 0x00_FF_00) >> 8; - uint b = (entry.Value.RGB & 0x00_00_FF); - - buffer[32 * (entry.Key - 1) + i] = 0xFF_00_00_00 | - ((lightCurveTables[(uint) entry.Value.BlueCurve][i] * b) / 31) << 16 | - ((lightCurveTables[(uint) entry.Value.GreenCurve][i] * g) / 31) << 8 | - ((lightCurveTables[(uint) entry.Value.RedCurve][i] * r) / 31); - } - } - } - - public enum LightShaderCurve - { - Standard, - A, // small - B, // very small and dim - C, // full, flat - D, // medium dim - E // halo - } - - private struct ItemLightData - { - public ushort Color; - public bool IsHue; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/LightShaderData.cs b/src/ClassicUO.Client/Game/Data/LightShaderData.cs deleted file mode 100644 index 75a325304..000000000 --- a/src/ClassicUO.Client/Game/Data/LightShaderData.cs +++ /dev/null @@ -1,61 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using static ClassicUO.Game.Data.LightColors; - -namespace ClassicUO.Game.Data -{ - internal struct LightShaderData - { - public LightShaderData(uint rgb, LightShaderCurve redcurve = LightShaderCurve.Standard, LightShaderCurve greencurve = LightShaderCurve.Standard, LightShaderCurve bluecurve = LightShaderCurve.Standard) - { - RGB = rgb; - Hue = 0; - RedCurve = redcurve; - GreenCurve = greencurve; - BlueCurve = bluecurve; - } - - public LightShaderData(ushort hue) - { - RGB = 0; - Hue = hue; - RedCurve = GreenCurve = BlueCurve = LightShaderCurve.Standard; - } - - public uint RGB; - public ushort Hue; - public LightShaderCurve RedCurve; - public LightShaderCurve GreenCurve; - public LightShaderCurve BlueCurve; - } -} diff --git a/src/ClassicUO.Client/Game/Data/LockedFeatures.cs b/src/ClassicUO.Client/Game/Data/LockedFeatures.cs deleted file mode 100644 index 165774c08..000000000 --- a/src/ClassicUO.Client/Game/Data/LockedFeatures.cs +++ /dev/null @@ -1,89 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; - -namespace ClassicUO.Game.Data -{ - [Flags] - public enum LockedFeatureFlags : uint - { - None = 0x00000000, - T2A = 0x00000001, - UOR = 0x00000002, // In later clients, the T2A/UOR flags are negative feature flags to disable body replacement of Pre-AOS graphics. - UOTD = 0x00000004, - LBR = 0x00000008, - AOS = 0x00000010, - SixthCharacterSlot = 0x00000020, - SE = 0x00000040, - ML = 0x00000080, - EighthAge = 0x00000100, - NinthAge = 0x00000200, // Crystal/Shadow Custom House Tiles - TenthAge = 0x00000400, - IncreasedStorage = 0x00000800, // Increased Housing/Bank Storage - SeventhCharacterSlot = 0x00001000, - RoleplayFaces = 0x00002000, - TrialAccount = 0x00004000, - LiveAccount = 0x00008000, - SA = 0x00010000, - HS = 0x00020000, - Gothic = 0x00040000, - Rustic = 0x00080000, - Jungle = 0x00100000, - Shadowguard = 0x00200000, - TOL = 0x00400000, - EJ = 0x00800000, - - ExpansionNone = None, - ExpansionT2A = T2A, - ExpansionUOR = ExpansionT2A | UOR, - ExpansionUOTD = ExpansionUOR | UOTD, - ExpansionLBR = ExpansionUOTD | LBR, - ExpansionAOS = LBR | AOS | LiveAccount, - ExpansionSE = ExpansionAOS | SE, - ExpansionML = ExpansionSE | ML | NinthAge, - ExpansionSA = ExpansionML | SA | Gothic | Rustic, - ExpansionHS = ExpansionSA | HS, - ExpansionTOL = ExpansionHS | TOL | Jungle | Shadowguard, - ExpansionEJ = ExpansionTOL | EJ - } - - public class LockedFeatures - { - public LockedFeatureFlags Flags { get; private set; } - - public void SetFlags(LockedFeatureFlags flags) - { - Flags = flags; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/MapMessageType.cs b/src/ClassicUO.Client/Game/Data/MapMessageType.cs deleted file mode 100644 index 0837b3cf6..000000000 --- a/src/ClassicUO.Client/Game/Data/MapMessageType.cs +++ /dev/null @@ -1,45 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Data -{ - internal enum MapMessageType - { - Add = 1, - Insert, - Move, - Remove, - Clear, - Edit, - EditResponse - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/MessageType.cs b/src/ClassicUO.Client/Game/Data/MessageType.cs deleted file mode 100644 index 86365b53f..000000000 --- a/src/ClassicUO.Client/Game/Data/MessageType.cs +++ /dev/null @@ -1,56 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; - -namespace ClassicUO.Game.Data -{ - [Flags] - public enum MessageType : byte - { - Regular = 0, - System = 1, - Emote = 2, - Limit3Spell = 3, // Sphere style shards use this to limit to 3 of these message types showing overhead. - Label = 6, - Focus = 7, - Whisper = 8, - Yell = 9, - Spell = 10, - Guild = 13, - Alliance = 14, - Command = 15, - Encoded = 0xC0, - ChatSystem, //TazUO Addition, value unimportant - Party = 0xFF // This is a CUO assigned type, value is unimportant - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/MovementSpeed.cs b/src/ClassicUO.Client/Game/Data/MovementSpeed.cs deleted file mode 100644 index 38fcdc2d8..000000000 --- a/src/ClassicUO.Client/Game/Data/MovementSpeed.cs +++ /dev/null @@ -1,161 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; - -namespace ClassicUO.Game.Data -{ - internal static class MovementSpeed - { - public const int STEP_DELAY_MOUNT_RUN = 100; - public const int STEP_DELAY_MOUNT_WALK = 200; - public const int STEP_DELAY_RUN = 200; - public const int STEP_DELAY_WALK = 400; - - public static int TimeToCompleteMovement(bool run, bool mounted) - { - if (mounted) - { - return run ? STEP_DELAY_MOUNT_RUN : STEP_DELAY_MOUNT_WALK; - } - - return run ? STEP_DELAY_RUN : STEP_DELAY_WALK; - } - - public static void GetPixelOffset(byte dir, ref float x, ref float y, float framesPerTile) - { - float step_NESW_D = 44.0f / framesPerTile; - float step_NESW = 22.0f / framesPerTile; - int checkX = 22; - int checkY = 22; - - switch (dir & 7) - { - case 0: //W - { - x *= step_NESW; - y *= -step_NESW; - - break; - } - - case 1: //NW - { - x *= step_NESW_D; - checkX = 44; - y = 0.0f; - - break; - } - - case 2: //N - { - x *= step_NESW; - y *= step_NESW; - - break; - } - - case 3: //NE - { - x = 0.0f; - y *= step_NESW_D; - checkY = 44; - - break; - } - - case 4: //E - { - x *= -step_NESW; - y *= step_NESW; - - break; - } - - case 5: //SE - { - x *= -step_NESW_D; - checkX = 44; - y = 0.0f; - - break; - } - - case 6: //S - { - x *= -step_NESW; - y *= -step_NESW; - - break; - } - - case 7: //SW - { - x = 0.0f; - y *= -step_NESW_D; - checkY = 44; - - break; - } - } - - int valueX = (int) x; - - if (Math.Abs(valueX) > checkX) - { - if (valueX < 0) - { - x = -checkX; - } - else - { - x = checkX; - } - } - - int valueY = (int) y; - - if (Math.Abs(valueY) > checkY) - { - if (valueY < 0) - { - y = -checkY; - } - else - { - y = checkY; - } - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/NotorietyFlag.cs b/src/ClassicUO.Client/Game/Data/NotorietyFlag.cs deleted file mode 100644 index ed5990515..000000000 --- a/src/ClassicUO.Client/Game/Data/NotorietyFlag.cs +++ /dev/null @@ -1,94 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; - -namespace ClassicUO.Game.Data -{ - public enum NotorietyFlag : byte - { - Unknown = 0x00, - Innocent = 0x01, - Ally = 0x02, - Gray = 0x03, - Criminal = 0x04, - Enemy = 0x05, - Murderer = 0x06, - Invulnerable = 0x07 - } - - public static class Notoriety - { - public static ushort GetHue(NotorietyFlag flag) - { - switch (flag) - { - case NotorietyFlag.Innocent: return ProfileManager.CurrentProfile.InnocentHue; - - case NotorietyFlag.Ally: return ProfileManager.CurrentProfile.FriendHue; - - case NotorietyFlag.Criminal: return ProfileManager.CurrentProfile.CriminalHue; - - case NotorietyFlag.Gray: return ProfileManager.CurrentProfile.CanAttackHue; - - case NotorietyFlag.Enemy: return ProfileManager.CurrentProfile.EnemyHue; - - case NotorietyFlag.Murderer: return ProfileManager.CurrentProfile.MurdererHue; - - case NotorietyFlag.Invulnerable: return 0x0034; - - default: return 0; - } - } - - public static string GetHTMLHue(NotorietyFlag flag) - { - switch (flag) - { - case NotorietyFlag.Innocent: return ""; - - case NotorietyFlag.Ally: return ""; - - case NotorietyFlag.Criminal: - case NotorietyFlag.Gray: return ""; - - case NotorietyFlag.Enemy: return ""; - - case NotorietyFlag.Murderer: return ""; - - case NotorietyFlag.Invulnerable: return ""; - - default: return string.Empty; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/PopupMenuData.cs b/src/ClassicUO.Client/Game/Data/PopupMenuData.cs deleted file mode 100644 index e0fbdfded..000000000 --- a/src/ClassicUO.Client/Game/Data/PopupMenuData.cs +++ /dev/null @@ -1,112 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Network; - -namespace ClassicUO.Game.Data -{ - public class PopupMenuData - { - public PopupMenuData(uint serial, PopupMenuItem[] items) - { - Serial = serial; - Items = items; - } - - public PopupMenuItem[] Items { get; } - - public uint Serial { get; } - - public PopupMenuItem this[int i] => Items[i]; - - public static PopupMenuData Parse(ref StackDataReader p) - { - ushort mode = p.ReadUInt16BE(); - bool isNewCliloc = mode >= 2; - uint serial = p.ReadUInt32BE(); - byte count = p.ReadUInt8(); - PopupMenuItem[] items = new PopupMenuItem[count]; - - for (int i = 0; i < count; i++) - { - ushort hue = 0xFFFF, replaced = 0; - int cliloc; - ushort index, flags; - - if (isNewCliloc) - { - cliloc = (int) p.ReadUInt32BE(); - index = p.ReadUInt16BE(); - flags = p.ReadUInt16BE(); - } - else - { - index = p.ReadUInt16BE(); - cliloc = p.ReadUInt16BE() + 3000000; - flags = p.ReadUInt16BE(); - - if ((flags & 0x84) != 0) - { - p.Skip(2); - } - - if ((flags & 0x40) != 0) - { - p.Skip(2); - } - - if ((flags & 0x20) != 0) - { - replaced = (ushort) (p.ReadUInt16BE() ); - } - } - - if ((flags & 0x01) != 0) - { - hue = 0x0386; - } - - items[i] = new PopupMenuItem - ( - cliloc, - index, - hue, - replaced, - flags - ); - } - - return new PopupMenuData(serial, items); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/PopupMenuItem.cs b/src/ClassicUO.Client/Game/Data/PopupMenuItem.cs deleted file mode 100644 index 192d606c8..000000000 --- a/src/ClassicUO.Client/Game/Data/PopupMenuItem.cs +++ /dev/null @@ -1,51 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Data -{ - public readonly struct PopupMenuItem - { - public PopupMenuItem(int cliloc, ushort index, ushort hue, ushort replaced, ushort flags) - { - Cliloc = cliloc; - Index = index; - Hue = hue; - ReplacedHue = replaced; - Flags = flags; - } - - public readonly int Cliloc; - public readonly ushort Index; - public readonly ushort Hue, ReplacedHue; - public readonly ushort Flags; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/PromptData.cs b/src/ClassicUO.Client/Game/Data/PromptData.cs deleted file mode 100644 index 07e55635c..000000000 --- a/src/ClassicUO.Client/Game/Data/PromptData.cs +++ /dev/null @@ -1,47 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Data -{ - internal enum ConsolePrompt - { - None, - ASCII, - Unicode - } - - internal struct PromptData - { - public ConsolePrompt Prompt; - public ulong Data; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/RaceType.cs b/src/ClassicUO.Client/Game/Data/RaceType.cs deleted file mode 100644 index e0a2224cc..000000000 --- a/src/ClassicUO.Client/Game/Data/RaceType.cs +++ /dev/null @@ -1,41 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Data -{ - public enum RaceType : byte - { - HUMAN = 1, - ELF, - GARGOYLE - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/Reagents.cs b/src/ClassicUO.Client/Game/Data/Reagents.cs deleted file mode 100644 index bd53f6017..000000000 --- a/src/ClassicUO.Client/Game/Data/Reagents.cs +++ /dev/null @@ -1,69 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Data -{ - public enum Reagents - { - // britannia reagents - BlackPearl, - Bloodmoss, - Garlic, - Ginseng, - MandrakeRoot, - Nightshade, - SulfurousAsh, - SpidersSilk, - - // pagan reagents - BatWing, - GraveDust, - DaemonBlood, - NoxCrystal, - PigIron, - - // Other - Bone, - FertileDirt, - DragonsBlood, - DemonBone, - - // More extras usable as reagents - Blackmoor, - Bloodspawn, - DeadWood, - WyrmHeart, - - // None - None - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/ServerErrorMessages.cs b/src/ClassicUO.Client/Game/Data/ServerErrorMessages.cs deleted file mode 100644 index 6ca17ef97..000000000 --- a/src/ClassicUO.Client/Game/Data/ServerErrorMessages.cs +++ /dev/null @@ -1,137 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Assets; -using ClassicUO.Resources; - -namespace ClassicUO.Game.Data -{ - internal static class ServerErrorMessages - { - private static readonly Tuple[] _loginErrors = - { - Tuple.Create(3000007, ResErrorMessages.IncorrectPassword), - Tuple.Create(3000009, ResErrorMessages.CharacterDoesNotExist), - Tuple.Create(3000006, ResErrorMessages.CharacterAlreadyExists), - Tuple.Create(3000016, ResErrorMessages.ClientCouldNotAttachToServer), - Tuple.Create(3000017, ResErrorMessages.ClientCouldNotAttachToServer), - Tuple.Create(3000012, ResErrorMessages.AnotherCharacterOnline), - Tuple.Create(3000013, ResErrorMessages.ErrorInSynchronization), - Tuple.Create(3000005, ResErrorMessages.IdleTooLong), - Tuple.Create(-1, ResErrorMessages.CouldNotAttachServer), - Tuple.Create(-1, ResErrorMessages.CharacterTransferInProgress) - }; - - private static readonly Tuple[] _errorCode = - { - Tuple.Create(3000018, ResErrorMessages.CharacterPasswordInvalid), - Tuple.Create(3000019, ResErrorMessages.ThatCharacterDoesNotExist), - Tuple.Create(3000020, ResErrorMessages.ThatCharacterIsBeingPlayed), - Tuple.Create(3000021, ResErrorMessages.CharacterIsNotOldEnough), - Tuple.Create(3000022, ResErrorMessages.CharacterIsQueuedForBackup), - Tuple.Create(3000023, ResErrorMessages.CouldntCarryOutYourRequest) - }; - - private static readonly Tuple[] _pickUpErrors = - { - Tuple.Create(3000267, ResErrorMessages.YouCanNotPickThatUp), - Tuple.Create(3000268, ResErrorMessages.ThatIsTooFarAway), - Tuple.Create(3000269, ResErrorMessages.ThatIsOutOfSight), - Tuple.Create(3000270, ResErrorMessages.ThatItemDoesNotBelongToYou), - Tuple.Create(3000271, ResErrorMessages.YouAreAlreadyHoldingAnItem) - }; - - private static readonly Tuple[] _generalErrors = - { - Tuple.Create(3000007, ResErrorMessages.IncorrectNamePassword), - Tuple.Create(3000034, ResErrorMessages.SomeoneIsAlreadyUsingThisAccount), - Tuple.Create(3000035, ResErrorMessages.YourAccountHasBeenBlocked), - Tuple.Create(3000036, ResErrorMessages.YourAccountCredentialsAreInvalid), - Tuple.Create(-1, ResErrorMessages.CommunicationProblem), - Tuple.Create(-1, ResErrorMessages.TheIGRConcurrencyLimitHasBeenMet), - Tuple.Create(-1, ResErrorMessages.TheIGRTimeLimitHasBeenMet), - Tuple.Create(-1, ResErrorMessages.GeneralIGRAuthenticationFailure), - Tuple.Create(3000037, ResErrorMessages.CouldntConnectToUO) - }; - - public static string GetError(byte packetID, byte code) - { - ClilocLoader cliloc = ClilocLoader.Instance; - - switch (packetID) - { - case 0x53: - if (code >= 10) - { - code = 9; - } - - Tuple t = _loginErrors[code]; - - return cliloc.GetString(t.Item1, t.Item2); - - case 0x85: - if (code >= 6) - { - code = 5; - } - - t = _errorCode[code]; - - return cliloc.GetString(t.Item1, t.Item2); - - case 0x27: - if (code >= 5) - { - code = 4; - } - - t = _pickUpErrors[code]; - - return cliloc.GetString(t.Item1, t.Item2); - - case 0x82: - if (code >= 9) - { - code = 8; - } - - t = _generalErrors[code]; - - return cliloc.GetString(t.Item1, t.Item2); - } - - return string.Empty; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/Skill.cs b/src/ClassicUO.Client/Game/Data/Skill.cs deleted file mode 100644 index cbc7fbb29..000000000 --- a/src/ClassicUO.Client/Game/Data/Skill.cs +++ /dev/null @@ -1,105 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Resources; -using System; - -namespace ClassicUO.Game.Data -{ - public enum Lock : byte - { - Up = 0, - Down = 1, - Locked = 2 - } - - public sealed class Skill - { - public static event EventHandler SkillValueChangedEvent; - public static event EventHandler SkillBaseChangedEvent; - public static event EventHandler SkillCapChangedEvent; - - public Skill(string name, int index, bool click) - { - Name = name; - Index = index; - IsClickable = click; - } - - public Lock Lock { get; internal set; } - - public ushort ValueFixed { get; internal set; } - - public ushort BaseFixed { get; internal set; } - - public ushort CapFixed { get; internal set; } - - public float Value => ValueFixed / 10.0f; - - public float Base => BaseFixed / 10.0f; - - public float Cap => CapFixed / 10.0f; - - public bool IsClickable { get; } - - public string Name { get; } - - public int Index { get; } - - public static void InvokeSkillValueChanged(int index) - { - SkillValueChangedEvent?.Invoke(null, new SkillChangeArgs(index)); - } - public static void InvokeSkillBaseChanged(int index) - { - SkillBaseChangedEvent?.Invoke(null, new SkillChangeArgs(index)); - } - public static void InvokeSkillCapChanged(int index) - { - SkillCapChangedEvent?.Invoke(null, new SkillChangeArgs(index)); - } - - public override string ToString() - { - return string.Format(ResGeneral.Name0Val1, Name, Value); - } - - public class SkillChangeArgs : EventArgs - { - public int Index; - public SkillChangeArgs(int index) - { - Index = index; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/SpellDefinition.cs b/src/ClassicUO.Client/Game/Data/SpellDefinition.cs deleted file mode 100644 index 463c7cc80..000000000 --- a/src/ClassicUO.Client/Game/Data/SpellDefinition.cs +++ /dev/null @@ -1,554 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Text; -using ClassicUO.Game.Managers; -using ClassicUO.Resources; -using ClassicUO.Utility; - -namespace ClassicUO.Game.Data -{ - public class SpellDefinition : IEquatable - { - public static SpellDefinition EmptySpell = new SpellDefinition - ( - "", - 0, - 0, - "", - 0, - 0, - 0 - ); - - internal static Dictionary WordToTargettype = new Dictionary(); - - - public SpellDefinition - ( - string name, - int index, - int gumpIconID, - int gumpSmallIconID, - string powerwords, - int manacost, - int minskill, - int tithingcost, - TargetType target, - params Reagents[] regs - ) - { - Name = name; - ID = index; - GumpIconID = gumpIconID; - GumpIconSmallID = gumpSmallIconID; - Regs = regs; - ManaCost = manacost; - MinSkill = minskill; - PowerWords = powerwords; - TithingCost = tithingcost; - TargetType = target; - AddToWatchedSpell(); - } - - public SpellDefinition - ( - string name, - int index, - int gumpIconID, - string powerwords, - int manacost, - int minskill, - TargetType target, - params Reagents[] regs - ) - { - Name = name; - ID = index; - GumpIconID = gumpIconID; - GumpIconSmallID = gumpIconID; - Regs = regs; - ManaCost = manacost; - MinSkill = minskill; - PowerWords = powerwords; - TithingCost = 0; - TargetType = target; - AddToWatchedSpell(); - } - - public SpellDefinition - ( - string name, - int index, - int gumpIconID, - string powerwords, - TargetType target, - params Reagents[] regs - ) - { - Name = name; - ID = index; - GumpIconID = gumpIconID; - GumpIconSmallID = gumpIconID - 0x1298; - Regs = regs; - ManaCost = 0; - MinSkill = 0; - TithingCost = 0; - PowerWords = powerwords; - TargetType = target; - AddToWatchedSpell(); - } - - public bool Equals(SpellDefinition other) - { - return ID.Equals(other.ID); - } - - public readonly int GumpIconID; - public readonly int GumpIconSmallID; - public readonly int ID; - public readonly int ManaCost; - public readonly int MinSkill; - - public readonly string Name; - public readonly string PowerWords; - public readonly Reagents[] Regs; - public readonly TargetType TargetType; - public readonly int TithingCost; - - private void AddToWatchedSpell() - { - if (!string.IsNullOrEmpty(PowerWords)) - { - WordToTargettype[PowerWords] = this; - } - else if (!string.IsNullOrEmpty(Name)) - { - WordToTargettype[Name] = this; - } - } - - public static bool TryGetSpellFromName(string spellName, out SpellDefinition spell, bool partialMatch = true) - { - foreach (var entry in SpellsMagery.GetAllSpells) - { - if (partialMatch) - { - if (entry.Value.Name.ToLower().Contains(spellName.ToLower())) - { - spell = entry.Value; - return true; - } - } - else if (entry.Value.Name.Equals(spellName, StringComparison.InvariantCultureIgnoreCase)) - { - spell = entry.Value; - return true; - } - } - - foreach (var entry in SpellsNecromancy.GetAllSpells) - { - if (partialMatch) - { - if (entry.Value.Name.ToLower().Contains(spellName.ToLower())) - { - spell = entry.Value; - return true; - } - } - else if (entry.Value.Name.Equals(spellName, StringComparison.InvariantCultureIgnoreCase)) - { - spell = entry.Value; - return true; - } - } - - foreach (var entry in SpellsChivalry.GetAllSpells) - { - if (partialMatch) - { - if (entry.Value.Name.ToLower().Contains(spellName.ToLower())) - { - spell = entry.Value; - return true; - } - } - else if (entry.Value.Name.Equals(spellName, StringComparison.InvariantCultureIgnoreCase)) - { - spell = entry.Value; - return true; - } - } - - foreach (var entry in SpellsBushido.GetAllSpells) - { - if (partialMatch) - { - if (entry.Value.Name.ToLower().Contains(spellName.ToLower())) - { - spell = entry.Value; - return true; - } - } - else if (entry.Value.Name.Equals(spellName, StringComparison.InvariantCultureIgnoreCase)) - { - spell = entry.Value; - return true; - } - } - - foreach (var entry in SpellsNinjitsu.GetAllSpells) - { - if (partialMatch) - { - if (entry.Value.Name.ToLower().Contains(spellName.ToLower())) - { - spell = entry.Value; - return true; - } - } - else if (entry.Value.Name.Equals(spellName, StringComparison.InvariantCultureIgnoreCase)) - { - spell = entry.Value; - return true; - } - } - - foreach (var entry in SpellsSpellweaving.GetAllSpells) - { - if (partialMatch) - { - if (entry.Value.Name.ToLower().Contains(spellName.ToLower())) - { - spell = entry.Value; - return true; - } - } - else if (entry.Value.Name.Equals(spellName, StringComparison.InvariantCultureIgnoreCase)) - { - spell = entry.Value; - return true; - } - } - - foreach (var entry in SpellsMysticism.GetAllSpells) - { - if (partialMatch) - { - if (entry.Value.Name.ToLower().Contains(spellName.ToLower())) - { - spell = entry.Value; - return true; - } - } - else if (entry.Value.Name.Equals(spellName, StringComparison.InvariantCultureIgnoreCase)) - { - spell = entry.Value; - return true; - } - } - - foreach (var entry in SpellsMastery.GetAllSpells) - { - if (partialMatch) - { - if (entry.Value.Name.ToLower().Contains(spellName.ToLower())) - { - spell = entry.Value; - return true; - } - } - else if (entry.Value.Name.Equals(spellName, StringComparison.InvariantCultureIgnoreCase)) - { - spell = entry.Value; - return true; - } - } - - spell = null; - return false; - } - - public string CreateReagentListString(string separator) - { - ValueStringBuilder sb = new ValueStringBuilder(); - { - for (int i = 0; i < Regs.Length; i++) - { - switch (Regs[i]) - { - // britanian reagents - case Reagents.BlackPearl: - sb.Append(ResGeneral.BlackPearl); - - break; - - case Reagents.Bloodmoss: - sb.Append(ResGeneral.Bloodmoss); - - break; - - case Reagents.Garlic: - sb.Append(ResGeneral.Garlic); - - break; - - case Reagents.Ginseng: - sb.Append(ResGeneral.Ginseng); - - break; - - case Reagents.MandrakeRoot: - sb.Append(ResGeneral.MandrakeRoot); - - break; - - case Reagents.Nightshade: - sb.Append(ResGeneral.Nightshade); - - break; - - case Reagents.SulfurousAsh: - sb.Append(ResGeneral.SulfurousAsh); - - break; - - case Reagents.SpidersSilk: - sb.Append(ResGeneral.SpidersSilk); - - break; - - // pagan reagents - case Reagents.BatWing: - sb.Append(ResGeneral.BatWing); - - break; - - case Reagents.GraveDust: - sb.Append(ResGeneral.GraveDust); - - break; - - case Reagents.DaemonBlood: - sb.Append(ResGeneral.DaemonBlood); - - break; - - case Reagents.NoxCrystal: - sb.Append(ResGeneral.NoxCrystal); - - break; - - case Reagents.PigIron: - sb.Append(ResGeneral.PigIron); - - break; - - default: - - if (Regs[i] < Reagents.None) - { - sb.Append(StringHelper.AddSpaceBeforeCapital(Regs[i].ToString())); - } - - break; - } - - if (i < Regs.Length - 1) - { - sb.Append(separator); - } - } - - string ss = sb.ToString(); - sb.Dispose(); - return ss; - } - } - - public static SpellDefinition FullIndexGetSpell(int fullidx) - { - if (fullidx < 1 || fullidx > 799) - { - return EmptySpell; - } - - if (fullidx < 100) - { - return SpellsMagery.GetSpell(fullidx); - } - - if (fullidx < 200) - { - return SpellsNecromancy.GetSpell(fullidx % 100); - } - - if (fullidx < 300) - { - return SpellsChivalry.GetSpell(fullidx % 100); - } - - if (fullidx < 500) - { - return SpellsBushido.GetSpell(fullidx % 100); - } - - if (fullidx < 600) - { - return SpellsNinjitsu.GetSpell(fullidx % 100); - } - - if (fullidx < 678) - { - return SpellsSpellweaving.GetSpell(fullidx % 100); - } - - if (fullidx < 700) - { - return SpellsMysticism.GetSpell((fullidx - 77) % 100); - } - - return SpellsMastery.GetSpell(fullidx % 100); - } - - public static void FullIndexSetModifySpell - ( - int fullidx, - int id, - int iconid, - int smalliconid, - int minskill, - int manacost, - int tithing, - string name, - string words, - TargetType target, - params Reagents[] regs - ) - { - if (fullidx < 1 || fullidx > 799) - { - return; - } - - SpellDefinition sd = FullIndexGetSpell(fullidx); - - if (sd.ID == fullidx) //we are not using an emptyspell spelldefinition - { - if (iconid == 0) - { - iconid = sd.GumpIconID; - } - - if (smalliconid == 0) - { - smalliconid = sd.GumpIconSmallID; - } - - if (tithing == 0) - { - tithing = sd.TithingCost; - } - - if (manacost == 0) - { - manacost = sd.ManaCost; - } - - if (minskill == 0) - { - minskill = sd.MinSkill; - } - - if (!string.IsNullOrEmpty(sd.PowerWords) && sd.PowerWords != words) - { - WordToTargettype.Remove(sd.PowerWords); - } - - if (!string.IsNullOrEmpty(sd.Name) && sd.Name != name) - { - WordToTargettype.Remove(sd.Name); - } - } - - sd = new SpellDefinition - ( - name, - fullidx, - iconid, - smalliconid, - words, - manacost, - minskill, - tithing, - target, - regs - ); - - if (fullidx < 100) - { - SpellsMagery.SetSpell(id, in sd); - } - else if (fullidx < 200) - { - SpellsNecromancy.SetSpell(id, in sd); - } - else if (fullidx < 300) - { - SpellsChivalry.SetSpell(id, in sd); - } - else if (fullidx < 500) - { - SpellsBushido.SetSpell(id, in sd); - } - else if (fullidx < 600) - { - SpellsNinjitsu.SetSpell(id, in sd); - } - else if (fullidx < 678) - { - SpellsSpellweaving.SetSpell(id, in sd); - } - else if (fullidx < 700) - { - SpellsMysticism.SetSpell(id - 77, in sd); - } - else - { - SpellsMastery.SetSpell(id, in sd); - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/SpellbookTypes.cs b/src/ClassicUO.Client/Game/Data/SpellbookTypes.cs deleted file mode 100644 index 2cb4e752f..000000000 --- a/src/ClassicUO.Client/Game/Data/SpellbookTypes.cs +++ /dev/null @@ -1,92 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Data -{ - internal enum SpellBookType - { - Magery, - Necromancy, - Chivalry, - Bushido = 4, - Ninjitsu, - Spellweaving, - Mysticism, - Mastery, - Unknown = 0xFF - } - - internal static class SpellBookDefinition - { - #region MacroSubType Offsets - // Offset for MacroSubType - private const int MAGERY_SPELLS_OFFSET = 61; - private const int NECRO_SPELLS_OFFSET = 125; - private const int CHIVAL_SPELLS_OFFSETS = 142; - private const int BUSHIDO_SPELLS_OFFSETS = 152; - private const int NINJITSU_SPELLS_OFFSETS = 158; - private const int SPELLWEAVING_SPELLS_OFFSETS = 166; - private const int MYSTICISM_SPELLS_OFFSETS = 182; - private const int MASTERY_SPELLS_OFFSETS = 198; - - #endregion - - public static int GetSpellsGroup(int spellID) - { - var spellsGroup = spellID / 100; - - switch (spellsGroup) - { - case (int)SpellBookType.Magery: - return MAGERY_SPELLS_OFFSET; - case (int)SpellBookType.Necromancy: - return NECRO_SPELLS_OFFSET; - case (int)SpellBookType.Chivalry: - return CHIVAL_SPELLS_OFFSETS; - case (int)SpellBookType.Bushido: - return BUSHIDO_SPELLS_OFFSETS; - case (int)SpellBookType.Ninjitsu: - return NINJITSU_SPELLS_OFFSETS; - case (int)SpellBookType.Spellweaving: - // Mysticicsm Spells Id starts from 678 and Spellweaving ends at 618 - if (spellID > 620) - { - return MYSTICISM_SPELLS_OFFSETS; - } - return SPELLWEAVING_SPELLS_OFFSETS; - case (int)SpellBookType.Mastery - 1: - return MASTERY_SPELLS_OFFSETS; - } - return -1; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/SpellsBushido.cs b/src/ClassicUO.Client/Game/Data/SpellsBushido.cs deleted file mode 100644 index 0c414f170..000000000 --- a/src/ClassicUO.Client/Game/Data/SpellsBushido.cs +++ /dev/null @@ -1,159 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Game.Managers; - -namespace ClassicUO.Game.Data -{ - internal static class SpellsBushido - { - private static readonly Dictionary _spellsDict; - - static SpellsBushido() - { - _spellsDict = new Dictionary - { - // Spell List - { - 1, - new SpellDefinition - ( - "Honorable Execution", - 401, - 0x5420, - string.Empty, - 0, - 25, - TargetType.Harmful, - Reagents.None - ) - }, - { - 2, - new SpellDefinition - ( - "Confidence", - 402, - 0x5421, - string.Empty, - 10, - 25, - TargetType.Beneficial, - Reagents.None - ) - }, - { - 3, - new SpellDefinition - ( - "Evasion", - 403, - 0x5422, - string.Empty, - 10, - 60, - TargetType.Beneficial, - Reagents.None - ) - }, - { - 4, - new SpellDefinition - ( - "Counter Attack", - 404, - 0x5423, - string.Empty, - 5, - 40, - TargetType.Harmful, - Reagents.None - ) - }, - { - 5, - new SpellDefinition - ( - "Lightning Strike", - 405, - 0x5424, - string.Empty, - 10, - 50, - TargetType.Harmful, - Reagents.None - ) - }, - { - 6, - new SpellDefinition - ( - "Momentum Strike", - 406, - 0x5425, - string.Empty, - 10, - 70, - TargetType.Harmful, - Reagents.None - ) - } - }; - } - - public static string SpellBookName { get; set; } = SpellBookType.Bushido.ToString(); - - public static IReadOnlyDictionary GetAllSpells => _spellsDict; - internal static int MaxSpellCount => _spellsDict.Count; - - public static SpellDefinition GetSpell(int spellIndex) - { - if (_spellsDict.TryGetValue(spellIndex, out SpellDefinition spell)) - { - return spell; - } - - return SpellDefinition.EmptySpell; - } - - public static void SetSpell(int id, in SpellDefinition newspell) - { - _spellsDict[id] = newspell; - } - - internal static void Clear() - { - _spellsDict.Clear(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/SpellsChivalry.cs b/src/ClassicUO.Client/Game/Data/SpellsChivalry.cs deleted file mode 100644 index 04a38c591..000000000 --- a/src/ClassicUO.Client/Game/Data/SpellsChivalry.cs +++ /dev/null @@ -1,235 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Game.Managers; - -namespace ClassicUO.Game.Data -{ - internal static class SpellsChivalry - { - private static readonly Dictionary _spellsDict; - - static SpellsChivalry() - { - _spellsDict = new Dictionary - { - // Spell List - { - 1, - new SpellDefinition - ( - "Cleanse by Fire", - 201, - 0x5100, - 0x5100, - "Expor Flamus", - 10, - 5, - 10, - TargetType.Beneficial, - Reagents.None - ) - }, - { - 2, - new SpellDefinition - ( - "Close Wounds", - 202, - 0x5101, - 0x5101, - "Obsu Vulni", - 10, - 0, - 10, - TargetType.Beneficial, - Reagents.None - ) - }, - { - 3, - new SpellDefinition - ( - "Consecrate Weapon", - 203, - 0x5102, - 0x5102, - "Consecrus Arma", - 10, - 15, - 10, - TargetType.Neutral, - Reagents.None - ) - }, - { - 4, - new SpellDefinition - ( - "Dispel Evil", - 204, - 0x5103, - 0x5103, - "Dispiro Malas", - 10, - 35, - 10, - TargetType.Neutral, - Reagents.None - ) - }, - { - 5, - new SpellDefinition - ( - "Divine Fury", - 205, - 0x5104, - 0x5104, - "Divinum Furis", - 10, - 25, - 10, - TargetType.Neutral, - Reagents.None - ) - }, - { - 6, - new SpellDefinition - ( - "Enemy of One", - 206, - 0x5105, - 0x5105, - "Forul Solum", - 20, - 45, - 10, - TargetType.Neutral, - Reagents.None - ) - }, - { - 7, - new SpellDefinition - ( - "Holy Light", - 207, - 0x5106, - 0x5106, - "Augus Luminos", - 20, - 55, - 10, - TargetType.Harmful, - Reagents.None - ) - }, - { - 8, - new SpellDefinition - ( - "Noble Sacrifice", - 208, - 0x5107, - 0x5107, - "Dium Prostra", - 20, - 65, - 30, - TargetType.Beneficial, - Reagents.None - ) - }, - { - 9, - new SpellDefinition - ( - "Remove Curse", - 209, - 0x5108, - 0x5108, - "Extermo Vomica", - 20, - 5, - 10, - TargetType.Beneficial, - Reagents.None - ) - }, - { - 10, - new SpellDefinition - ( - "Sacred Journey", - 210, - 0x5109, - 0x5109, - "Sanctum Viatas", - 20, - 5, - 10, - TargetType.Neutral, - Reagents.None - ) - } - }; - } - - public static string SpellBookName { get; set; } = SpellBookType.Chivalry.ToString(); - - public static IReadOnlyDictionary GetAllSpells => _spellsDict; - internal static int MaxSpellCount => _spellsDict.Count; - - public static SpellDefinition GetSpell(int spellIndex) - { - if (_spellsDict.TryGetValue(spellIndex, out SpellDefinition spell)) - { - return spell; - } - - return SpellDefinition.EmptySpell; - } - - public static void SetSpell(int id, in SpellDefinition newspell) - { - _spellsDict[id] = newspell; - } - - internal static void Clear() - { - _spellsDict.Clear(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/SpellsMagery.cs b/src/ClassicUO.Client/Game/Data/SpellsMagery.cs deleted file mode 100644 index c386cdbd1..000000000 --- a/src/ClassicUO.Client/Game/Data/SpellsMagery.cs +++ /dev/null @@ -1,994 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using System.Linq; -using ClassicUO.Game.Managers; -using ClassicUO.Utility; - -namespace ClassicUO.Game.Data -{ - internal static class SpellsMagery - { - private static readonly Dictionary _spellsDict; - - private static string[] _spRegsChars; - - static SpellsMagery() - { - _spellsDict = new Dictionary - { - // first circle - { - 1, - new SpellDefinition - ( - "Clumsy", - 1, - 0x1B58, - "Uus Jux", - TargetType.Harmful, - Reagents.Bloodmoss, - Reagents.Nightshade - ) - }, - { - 2, - new SpellDefinition - ( - "Create Food", - 2, - 0x1B59, - "In Mani Ylem", - TargetType.Neutral, - Reagents.Garlic, - Reagents.Ginseng, - Reagents.MandrakeRoot - ) - }, - { - 3, - new SpellDefinition - ( - "Feeblemind", - 3, - 0x1B5A, - "Rel Wis", - TargetType.Harmful, - Reagents.Nightshade, - Reagents.Ginseng - ) - }, - { - 4, - new SpellDefinition - ( - "Heal", - 4, - 0x1B5B, - "In Mani", - TargetType.Beneficial, - Reagents.Garlic, - Reagents.Ginseng, - Reagents.SpidersSilk - ) - }, - { - 5, - new SpellDefinition - ( - "Magic Arrow", - 5, - 0x1B5C, - "In Por Ylem", - TargetType.Harmful, - Reagents.SulfurousAsh - ) - }, - { - 6, - new SpellDefinition - ( - "Night Sight", - 6, - 0x1B5D, - "In Lor", - TargetType.Beneficial, - Reagents.SpidersSilk, - Reagents.SulfurousAsh - ) - }, - { - 7, - new SpellDefinition - ( - "Reactive Armor", - 7, - 0x1B5E, - "Flam Sanct", - TargetType.Beneficial, - Reagents.Garlic, - Reagents.SpidersSilk, - Reagents.SulfurousAsh - ) - }, - { - 8, - new SpellDefinition - ( - "Weaken", - 8, - 0x1B5F, - "Des Mani", - TargetType.Harmful, - Reagents.Garlic, - Reagents.Nightshade - ) - }, - // second circle - { - 9, - new SpellDefinition - ( - "Agility", - 9, - 0x1B60, - "Ex Uus", - TargetType.Beneficial, - Reagents.Bloodmoss, - Reagents.MandrakeRoot - ) - }, - { - 10, - new SpellDefinition - ( - "Cunning", - 10, - 0x1B61, - "Uus Wis", - TargetType.Beneficial, - Reagents.Nightshade, - Reagents.MandrakeRoot - ) - }, - { - 11, - new SpellDefinition - ( - "Cure", - 11, - 0x1B62, - "An Nox", - TargetType.Beneficial, - Reagents.Garlic, - Reagents.Ginseng - ) - }, - { - 12, - new SpellDefinition - ( - "Harm", - 12, - 0x1B63, - "An Mani", - TargetType.Harmful, - Reagents.Nightshade, - Reagents.SpidersSilk - ) - }, - { - 13, - new SpellDefinition - ( - "Magic Trap", - 13, - 0x1B64, - "In Jux", - TargetType.Neutral, - Reagents.Garlic, - Reagents.SpidersSilk, - Reagents.SulfurousAsh - ) - }, - { - 14, - new SpellDefinition - ( - "Magic Untrap", - 14, - 0x1B65, - "An Jux", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.SulfurousAsh - ) - }, - { - 15, - new SpellDefinition - ( - "Protection", - 15, - 0x1B66, - "Uus Sanct", - TargetType.Beneficial, - Reagents.Garlic, - Reagents.Ginseng, - Reagents.SulfurousAsh - ) - }, - { - 16, - new SpellDefinition - ( - "Strength", - 16, - 0x1B67, - "Uus Mani", - TargetType.Beneficial, - Reagents.MandrakeRoot, - Reagents.Nightshade - ) - }, - // third circle - { - 17, - new SpellDefinition - ( - "Bless", - 17, - 0x1B68, - "Rel Sanct", - TargetType.Beneficial, - Reagents.Garlic, - Reagents.MandrakeRoot - ) - }, - { - 18, new SpellDefinition - ( - "Fireball", - 18, - 0x1B69, - "Vas Flam", - TargetType.Harmful, - Reagents.BlackPearl - ) - }, - { - 19, - new SpellDefinition - ( - "Magic Lock", - 19, - 0x1B6a, - "An Por", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.Garlic, - Reagents.SulfurousAsh - ) - }, - { - 20, new SpellDefinition - ( - "Poison", - 20, - 0x1B6b, - "In Nox", - TargetType.Harmful, - Reagents.Nightshade - ) - }, - { - 21, - new SpellDefinition - ( - "Telekinesis", - 21, - 0x1B6c, - "Ort Por Ylem", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.MandrakeRoot - ) - }, - { - 22, - new SpellDefinition - ( - "Teleport", - 22, - 0x1B6d, - "Rel Por", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.MandrakeRoot - ) - }, - { - 23, - new SpellDefinition - ( - "Unlock", - 23, - 0x1B6e, - "Ex Por", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.SulfurousAsh - ) - }, - { - 24, - new SpellDefinition - ( - "Wall of Stone", - 24, - 0x1B6f, - "In Sanct Ylem", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.Garlic - ) - }, - // fourth circle - { - 25, - new SpellDefinition - ( - "Arch Cure", - 25, - 0x1B70, - "Vas An Nox", - TargetType.Beneficial, - Reagents.Garlic, - Reagents.Ginseng, - Reagents.MandrakeRoot - ) - }, - { - 26, - new SpellDefinition - ( - "Arch Protection", - 26, - 0x1B71, - "Vas Uus Sanct", - TargetType.Beneficial, - Reagents.Garlic, - Reagents.Ginseng, - Reagents.MandrakeRoot, - Reagents.SulfurousAsh - ) - }, - { - 27, - new SpellDefinition - ( - "Curse", - 27, - 0x1B72, - "Des Sanct", - TargetType.Harmful, - Reagents.Garlic, - Reagents.Nightshade, - Reagents.SulfurousAsh - ) - }, - { - 28, - new SpellDefinition - ( - "Fire Field", - 28, - 0x1B73, - "In Flam Grav", - TargetType.Neutral, - Reagents.BlackPearl, - Reagents.SpidersSilk, - Reagents.SulfurousAsh - ) - }, - { - 29, - new SpellDefinition - ( - "Greater Heal", - 29, - 0x1B74, - "In Vas Mani", - TargetType.Beneficial, - Reagents.Garlic, - Reagents.Ginseng, - Reagents.MandrakeRoot, - Reagents.SpidersSilk - ) - }, - { - 30, - new SpellDefinition - ( - "Lightning", - 30, - 0x1B75, - "Por Ort Grav", - TargetType.Harmful, - Reagents.MandrakeRoot, - Reagents.SulfurousAsh - ) - }, - { - 31, - new SpellDefinition - ( - "Mana Drain", - 31, - 0x1B76, - "Ort Rel", - TargetType.Harmful, - Reagents.BlackPearl, - Reagents.MandrakeRoot, - Reagents.SpidersSilk - ) - }, - { - 32, - new SpellDefinition - ( - "Recall", - 32, - 0x1B77, - "Kal Ort Por", - TargetType.Neutral, - Reagents.BlackPearl, - Reagents.Bloodmoss, - Reagents.MandrakeRoot - ) - }, - // fifth circle - { - 33, - new SpellDefinition - ( - "Blade Spirits", - 33, - 0x1B78, - "In Jux Hur Ylem", - TargetType.Neutral, - Reagents.BlackPearl, - Reagents.MandrakeRoot, - Reagents.Nightshade - ) - }, - { - 34, - new SpellDefinition - ( - "Dispel Field", - 34, - 0x1B79, - "An Grav", - TargetType.Neutral, - Reagents.BlackPearl, - Reagents.Garlic, - Reagents.SpidersSilk, - Reagents.SulfurousAsh - ) - }, - { - 35, - new SpellDefinition - ( - "Incognito", - 35, - 0x1B7a, - "Kal In Ex", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.Garlic, - Reagents.Nightshade - ) - }, - { - 36, - new SpellDefinition - ( - "Magic Reflection", - 36, - 0x1B7b, - "In Jux Sanct", - TargetType.Beneficial, - Reagents.Garlic, - Reagents.MandrakeRoot, - Reagents.SpidersSilk - ) - }, - { - 37, - new SpellDefinition - ( - "Mind Blast", - 37, - 0x1B7c, - "Por Corp Wis", - TargetType.Harmful, - Reagents.BlackPearl, - Reagents.MandrakeRoot, - Reagents.Nightshade, - Reagents.SulfurousAsh - ) - }, - { - 38, - new SpellDefinition - ( - "Paralyze", - 38, - 0x1B7d, - "An Ex Por", - TargetType.Harmful, - Reagents.Garlic, - Reagents.MandrakeRoot, - Reagents.SpidersSilk - ) - }, - { - 39, - new SpellDefinition - ( - "Poison Field", - 39, - 0x1B7e, - "In Nox Grav", - TargetType.Neutral, - Reagents.BlackPearl, - Reagents.Nightshade, - Reagents.SpidersSilk - ) - }, - { - 40, - new SpellDefinition - ( - "Summon Creature", - 40, - 0x1B7f, - "Kal Xen", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.MandrakeRoot, - Reagents.SpidersSilk - ) - }, - // sixth circle - { - 41, - new SpellDefinition - ( - "Dispel", - 41, - 0x1B80, - "An Ort", - TargetType.Neutral, - Reagents.Garlic, - Reagents.MandrakeRoot, - Reagents.SulfurousAsh - ) - }, - { - 42, - new SpellDefinition - ( - "Energy Bolt", - 42, - 0x1B81, - "Corp Por", - TargetType.Harmful, - Reagents.BlackPearl, - Reagents.Nightshade - ) - }, - { - 43, - new SpellDefinition - ( - "Explosion", - 43, - 0x1B82, - "Vas Ort Flam", - TargetType.Harmful, - Reagents.Bloodmoss, - Reagents.MandrakeRoot - ) - }, - { - 44, - new SpellDefinition - ( - "Invisibility", - 44, - 0x1B83, - "An Lor Xen", - TargetType.Beneficial, - Reagents.Bloodmoss, - Reagents.Nightshade - ) - }, - { - 45, - new SpellDefinition - ( - "Mark", - 45, - 0x1B84, - "Kal Por Ylem", - TargetType.Neutral, - Reagents.BlackPearl, - Reagents.Bloodmoss, - Reagents.MandrakeRoot - ) - }, - { - 46, - new SpellDefinition - ( - "Mass Curse", - 46, - 0x1B85, - "Vas Des Sanct", - TargetType.Harmful, - Reagents.Garlic, - Reagents.MandrakeRoot, - Reagents.Nightshade, - Reagents.SulfurousAsh - ) - }, - { - 47, - new SpellDefinition - ( - "Paralyze Field", - 47, - 0x1B86, - "In Ex Grav", - TargetType.Neutral, - Reagents.BlackPearl, - Reagents.Ginseng, - Reagents.SpidersSilk - ) - }, - { - 48, - new SpellDefinition - ( - "Reveal", - 48, - 0x1B87, - "Wis Quas", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.SulfurousAsh - ) - }, - // seventh circle - { - 49, - new SpellDefinition - ( - "Chain Lightning", - 49, - 0x1B88, - "Vas Ort Grav", - TargetType.Harmful, - Reagents.BlackPearl, - Reagents.Bloodmoss, - Reagents.MandrakeRoot, - Reagents.SulfurousAsh - ) - }, - { - 50, - new SpellDefinition - ( - "Energy Field", - 50, - 0x1B89, - "In Sanct Grav", - TargetType.Neutral, - Reagents.BlackPearl, - Reagents.MandrakeRoot, - Reagents.SpidersSilk, - Reagents.SulfurousAsh - ) - }, - { - 51, - new SpellDefinition - ( - "Flamestrike", - 51, - 0x1B8a, - "Kal Vas Flam", - TargetType.Harmful, - Reagents.SpidersSilk, - Reagents.SulfurousAsh - ) - }, - { - 52, - new SpellDefinition - ( - "Gate Travel", - 52, - 0x1B8b, - "Vas Rel Por", - TargetType.Neutral, - Reagents.BlackPearl, - Reagents.MandrakeRoot, - Reagents.SulfurousAsh - ) - }, - { - 53, - new SpellDefinition - ( - "Mana Vampire", - 53, - 0x1B8c, - "Ort Sanct", - TargetType.Harmful, - Reagents.BlackPearl, - Reagents.Bloodmoss, - Reagents.MandrakeRoot, - Reagents.SpidersSilk - ) - }, - { - 54, - new SpellDefinition - ( - "Mass Dispel", - 54, - 0x1B8d, - "Vas An Ort", - TargetType.Neutral, - Reagents.BlackPearl, - Reagents.Garlic, - Reagents.MandrakeRoot, - Reagents.SulfurousAsh - ) - }, - { - 55, - new SpellDefinition - ( - "Meteor Swarm", - 55, - 0x1B8e, - "Flam Kal Des Ylem", - TargetType.Harmful, - Reagents.Bloodmoss, - Reagents.MandrakeRoot, - Reagents.SpidersSilk, - Reagents.SulfurousAsh - ) - }, - { - 56, - new SpellDefinition - ( - "Polymorph", - 56, - 0x1B8f, - "Vas Ylem Rel", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.MandrakeRoot, - Reagents.SpidersSilk - ) - }, - // eighth circle - { - 57, - new SpellDefinition - ( - "Earthquake", - 57, - 0x1B90, - "In Vas Por", - TargetType.Harmful, - Reagents.Bloodmoss, - Reagents.Ginseng, - Reagents.MandrakeRoot, - Reagents.SulfurousAsh - ) - }, - { - 58, - new SpellDefinition - ( - "Energy Vortex", - 58, - 0x1B91, - "Vas Corp Por", - TargetType.Neutral, - Reagents.BlackPearl, - Reagents.Bloodmoss, - Reagents.MandrakeRoot, - Reagents.Nightshade - ) - }, - { - 59, - new SpellDefinition - ( - "Resurrection", - 59, - 0x1B92, - "An Corp", - TargetType.Beneficial, - Reagents.Bloodmoss, - Reagents.Ginseng, - Reagents.Garlic - ) - }, - { - 60, - new SpellDefinition - ( - "Air Elemental", - 60, - 0x1B93, - "Kal Vas Xen Hur", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.MandrakeRoot, - Reagents.SpidersSilk - ) - }, - { - 61, - new SpellDefinition - ( - "Summon Daemon", - 61, - 0x1B94, - "Kal Vas Xen Corp", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.MandrakeRoot, - Reagents.SpidersSilk, - Reagents.SulfurousAsh - ) - }, - { - 62, - new SpellDefinition - ( - "Earth Elemental", - 62, - 0x1B95, - "Kal Vas Xen Ylem", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.MandrakeRoot, - Reagents.SpidersSilk - ) - }, - { - 63, - new SpellDefinition - ( - "Fire Elemental", - 63, - 0x1B96, - "Kal Vas Xen Flam", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.MandrakeRoot, - Reagents.SpidersSilk, - Reagents.SulfurousAsh - ) - }, - { - 64, - new SpellDefinition - ( - "Water Elemental", - 64, - 0x1B97, - "Kal Vas Xen An Flam", - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.MandrakeRoot, - Reagents.SpidersSilk - ) - } - }; - } - - public static string SpellBookName { get; set; } = SpellBookType.Magery.ToString(); - - public static IReadOnlyDictionary GetAllSpells => _spellsDict; - internal static int MaxSpellCount => _spellsDict.Count; - - public static string[] CircleNames { get; } = - { - "First Circle", "Second Circle", "Third Circle", "Fourth Circle", "Fifth Circle", "Sixth Circle", - "Seventh Circle", "Eighth Circle" - }; - - public static string[] SpecialReagentsChars - { - get - { - if (_spRegsChars == null) - { - _spRegsChars = new string[_spellsDict.Max(o => o.Key)]; - - for (int i = _spRegsChars.Length; i > 0; --i) - { - if (_spellsDict.TryGetValue(i, out SpellDefinition sd)) - { - _spRegsChars[i - 1] = StringHelper.RemoveUpperLowerChars(sd.PowerWords); - } - else - { - _spRegsChars[i - 1] = string.Empty; - } - } - } - - return _spRegsChars; - } - } - - public static SpellDefinition GetSpell(int index) - { - return _spellsDict.TryGetValue(index, out SpellDefinition spell) ? spell : SpellDefinition.EmptySpell; - } - - public static void SetSpell(int id, in SpellDefinition newspell) - { - _spRegsChars = null; - _spellsDict[id] = newspell; - } - - internal static void Clear() - { - _spellsDict.Clear(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/SpellsMastery.cs b/src/ClassicUO.Client/Game/Data/SpellsMastery.cs deleted file mode 100644 index 619a61b8e..000000000 --- a/src/ClassicUO.Client/Game/Data/SpellsMastery.cs +++ /dev/null @@ -1,1013 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Game.Managers; - -namespace ClassicUO.Game.Data -{ - internal static class SpellsMastery - { - private static readonly Dictionary _spellsDict; - - - public static readonly int[][] SpellbookIndices = - { - new[] { 1, 2, 3, 4, 5, 6, 7, 8 }, - new[] { 9, 10, 11, 12, 13, 14, 19, 20 }, - new[] { 17, 21, 22, 25, 26, 34, 35, 36 }, - new[] { 27, 28, 29, 32, 37, 38, 40, 41 }, - new[] { 23, 24, 30, 31, 43, 44 }, - new[] { 15, 16, 18, 33, 39, 42, 45 } - }; - - public static readonly string SpellBookName = SpellBookType.Mastery.ToString(); - - - static SpellsMastery() - { - _spellsDict = new Dictionary - { - // Spell List - { - 1, - new SpellDefinition - ( - "Inspire", - 701, - 0x945, - 0x945, - "Uus Por", - 16, - 90, - 4, - TargetType.Beneficial, - Reagents.None - ) - }, - { - 2, - new SpellDefinition - ( - "Invigorate", - 702, - 0x946, - 0x946, - "An Zu", - 22, - 90, - 5, - TargetType.Beneficial, - Reagents.None - ) - }, - { - 3, - new SpellDefinition - ( - "Resilience", - 703, - 0x947, - 0x947, - "Kal Mani Tym", - 16, - 90, - 4, - TargetType.Beneficial, - Reagents.None - ) - }, - { - 4, - new SpellDefinition - ( - "Perseverance", - 704, - 0x948, - 0x948, - "Uus Jux Sanct", - 18, - 90, - 5, - TargetType.Beneficial, - Reagents.None - ) - }, - { - 5, - new SpellDefinition - ( - "Tribulation", - 705, - 0x949, - 0x949, - "In Jux Hur Rel", - 24, - 90, - 10, - TargetType.Harmful, - Reagents.None - ) - }, - { - 6, - new SpellDefinition - ( - "Despair", - 706, - 0x94A, - 0x94A, - "Kal Des Mani Tym", - 26, - 90, - 12, - TargetType.Harmful, - Reagents.None - ) - }, - { - 7, - new SpellDefinition - ( - "Death Ray", - 707, - 0x9B8B, - 0x9B8B, - "In Grav Corp", - 50, - 90, - 35, - TargetType.Harmful, - Reagents.BlackPearl, - Reagents.Bloodmoss, - Reagents.SpidersSilk - ) - }, - { - 8, - new SpellDefinition - ( - "Ethereal Burst", - 708, - 0x9B8C, - 0x9B8C, - "Uus Ort Grav", - 0, - 90, - 0, - TargetType.Beneficial, - Reagents.Bloodmoss, - Reagents.Ginseng, - Reagents.MandrakeRoot - ) - }, - { - 9, - new SpellDefinition - ( - "Nether Blast", - 709, - 0x9B8D, - 0x9B8D, - "In Vas Xen Por", - 40, - 90, - 0, - TargetType.Harmful, - Reagents.DragonsBlood, - Reagents.DemonBone - ) - }, - { - 10, - new SpellDefinition - ( - "Mystic Weapon", - 710, - 0x9B8E, - 0x9B8E, - "Vas Ylem Wis", - 40, - 90, - 0, - TargetType.Neutral, - Reagents.FertileDirt, - Reagents.Bone - ) - }, - { - 11, - new SpellDefinition - ( - "Command Undead", - 711, - 0x9B8F, - 0x9B8F, - "In Corp Xen Por", - 40, - 90, - 0, - TargetType.Neutral, - Reagents.DaemonBlood, - Reagents.PigIron, - Reagents.BatWing - ) - }, - { - 12, - new SpellDefinition - ( - "Conduit", - 712, - 0x9B90, - 0x9B90, - "Uus Corp Grav", - 40, - 90, - 0, - TargetType.Harmful, - Reagents.NoxCrystal, - Reagents.BatWing, - Reagents.GraveDust - ) - }, - { - 13, - new SpellDefinition - ( - "Mana Shield", - 713, - 0x9B91, - 0x9B91, - "Faerkulggen", - 40, - 90, - 0, - TargetType.Beneficial - ) - }, - { - 14, - new SpellDefinition - ( - "Summon Reaper", - 714, - 0x9B92, - 0x9B92, - "Lartarisstree", - 50, - 90, - 0, - TargetType.Neutral - ) - }, - { - 15, - new SpellDefinition - ( - "Enchanted Summoning", - 715, - 0x9B93, - 0x9B93, - "", - 0, - 90, - 0, - TargetType.Neutral - ) - }, - { - 16, new SpellDefinition - ( - "Anticipate Hit", - 716, - 0x9B94, - 0x9B94, - "", - 10, - 90, - 0, - TargetType.Neutral - ) - }, - { - 17, new SpellDefinition - ( - "Warcry", - 717, - 0x9B95, - 0x9B95, - "", - 40, - 90, - 0, - TargetType.Neutral - ) - }, - { - 18, new SpellDefinition - ( - "Intuition", - 718, - 0x9B96, - 0x9B96, - "", - 0, - 90, - 0, - TargetType.Neutral - ) - }, - { - 19, new SpellDefinition - ( - "Rejuvenate", - 719, - 0x9B97, - 0x9B97, - "", - 10, - 90, - 35, - TargetType.Neutral - ) - }, - { - 20, new SpellDefinition - ( - "Holy Fist", - 720, - 0x9B98, - 0x9B98, - "", - 50, - 90, - 35, - TargetType.Neutral - ) - }, - { - 21, new SpellDefinition - ( - "Shadow", - 721, - 0x9B99, - 0x9B99, - "", - 10, - 90, - 4, - TargetType.Neutral - ) - }, - { - 22, new SpellDefinition - ( - "White Tiger Form", - 722, - 0x9B9A, - 0x9B9A, - "", - 10, - 90, - 0, - TargetType.Neutral - ) - }, - { - 23, new SpellDefinition - ( - "Flaming Shot", - 723, - 0x9B9B, - 0x9B9B, - "", - 30, - 90, - 0, - TargetType.Neutral - ) - }, - { - 24, new SpellDefinition - ( - "Playing The Odds", - 724, - 0x9B9C, - 0x9B9C, - "", - 25, - 90, - 0, - TargetType.Neutral - ) - }, - { - 25, new SpellDefinition - ( - "Thrust", - 725, - 0x9B9D, - 0x9B9D, - "", - 30, - 90, - 20, - TargetType.Neutral - ) - }, - { - 26, new SpellDefinition - ( - "Pierce", - 726, - 0x9B9E, - 0x9B9E, - "", - 20, - 90, - 0, - TargetType.Neutral - ) - }, - { - 27, new SpellDefinition - ( - "Stagger", - 727, - 0x9B9F, - 0x9B9F, - "", - 20, - 90, - 0, - TargetType.Neutral - ) - }, - { - 28, new SpellDefinition - ( - "Toughness", - 728, - 0x9BA0, - 0x9BA0, - "", - 20, - 90, - 20, - TargetType.Neutral - ) - }, - { - 29, new SpellDefinition - ( - "Onslaught", - 729, - 0x9BA1, - 0x9BA1, - "", - 20, - 90, - 0, - TargetType.Neutral - ) - }, - { - 30, new SpellDefinition - ( - "Focused Eye", - 730, - 0x9BA2, - 0x9BA2, - "", - 20, - 90, - 20, - TargetType.Neutral - ) - }, - { - 31, new SpellDefinition - ( - "Elemental Fury", - 731, - 0x9BA3, - 0x9BA3, - "", - 20, - 90, - 0, - TargetType.Neutral - ) - }, - { - 32, new SpellDefinition - ( - "Called Shot", - 732, - 0x9BA4, - 0x9BA4, - "", - 40, - 90, - 0, - TargetType.Neutral - ) - }, - { - 33, new SpellDefinition - ( - "Warrior's Gifts", - 733, - 0x9BA5, - 0x9BA5, - "", - 50, - 90, - 0, - TargetType.Neutral - ) - }, - { - 34, new SpellDefinition - ( - "Shield Bash", - 734, - 0x9BA6, - 0x9BA6, - "", - 50, - 90, - 0, - TargetType.Neutral - ) - }, - { - 35, new SpellDefinition - ( - "Bodyguard", - 735, - 0x9BA7, - 0x9BA7, - "", - 40, - 90, - 0, - TargetType.Neutral - ) - }, - { - 36, new SpellDefinition - ( - "Heighten Senses", - 736, - 0x9BA8, - 0x9BA8, - "", - 10, - 90, - 10, - TargetType.Neutral - ) - }, - { - 37, new SpellDefinition - ( - "Tolerance", - 737, - 0x9BA9, - 0x9BA9, - "", - 20, - 90, - 0, - TargetType.Neutral - ) - }, - { - 38, new SpellDefinition - ( - "Injected Strike", - 738, - 0x9BAA, - 0x9BAA, - "", - 30, - 90, - 0, - TargetType.Neutral - ) - }, - { - 39, new SpellDefinition - ( - "Potency", - 739, - 0x9BAB, - 0x9BAB, - "", - 0, - 90, - 0, - TargetType.Neutral - ) - }, - { - 40, new SpellDefinition - ( - "Rampage", - 740, - 0x9BAC, - 0x9BAC, - "", - 20, - 90, - 0, - TargetType.Neutral - ) - }, - { - 41, new SpellDefinition - ( - "Fists of Fury", - 741, - 0x9BAD, - 0x9BAD, - "", - 20, - 90, - 0, - TargetType.Neutral - ) - }, - { - 42, new SpellDefinition - ( - "Knockout", - 742, - 0x9BAE, - 0x9BAE, - "", - 0, - 90, - 0, - TargetType.Neutral - ) - }, - { - 43, new SpellDefinition - ( - "Whispering", - 743, - 0x9BAF, - 0x9BAF, - "", - 40, - 90, - 0, - TargetType.Neutral - ) - }, - { - 44, new SpellDefinition - ( - "Combat Training", - 744, - 0x9BB0, - 0x9BB0, - "", - 40, - 90, - 0, - TargetType.Neutral - ) - }, - { - 45, new SpellDefinition - ( - "Boarding", - 745, - 0x9BB1, - 0x9BB1, - "", - 0, - 90, - 0, - TargetType.Neutral - ) - } - }; - } - - public static IReadOnlyDictionary GetAllSpells => _spellsDict; - internal static int MaxSpellCount => _spellsDict.Count; - - internal static string GetUsedSkillName(int spellid) - { - int div = (MaxSpellCount * 3) >> 3; - - if (div <= 0) - { - div = 1; - } - - int group = spellid / div; - - - switch (group) - { - case 0: return "Provocation"; - - case 1: return "Peacemaking"; - - case 3: return "Discordance"; - - case 4: return "Magery"; - - case 5: return "Mysticism"; - - case 6: return "Necromancy"; - - case 7: return "Spellweaving"; - - case 8: return "Passive"; - - case 9: return "Bushido"; - } - - if (group == 0) - { - return "Provocation"; - } - - if (group == 1) - { - return "Peacemaking"; - } - - return "Discordance"; - } - - public static SpellDefinition GetSpell(int spellIndex) - { - if (_spellsDict.TryGetValue(spellIndex, out SpellDefinition spell)) - { - return spell; - } - - return SpellDefinition.EmptySpell; - } - - public static List GetSpellListByGroupName(string group) - { - List list = new List(); - - switch (group.ToLower()) - { - default: - case "provocation": - list.Add(1); - list.Add(2); - - break; - - case "peacemaking": - list.Add(3); - list.Add(4); - - break; - - case "discordance": - list.Add(5); - list.Add(6); - - break; - - case "magery": - list.Add(15); - list.Add(7); - list.Add(8); - - break; - - case "mysticism": - list.Add(15); - list.Add(9); - list.Add(10); - - break; - - case "necromancy": - list.Add(15); - list.Add(11); - list.Add(12); - - break; - - case "spellweaving": - list.Add(15); - list.Add(13); - list.Add(14); - - break; - - case "bushido": - list.Add(18); - list.Add(16); - list.Add(17); - - break; - - case "chivalry": - list.Add(18); - list.Add(19); - list.Add(20); - - break; - - case "ninjitsu": - list.Add(18); - list.Add(21); - list.Add(22); - - break; - - case "archery": - list.Add(33); - list.Add(23); - list.Add(24); - - break; - - case "fencing": - list.Add(33); - list.Add(25); - list.Add(26); - - break; - - case "mace fighting": - list.Add(33); - list.Add(27); - list.Add(28); - - break; - - case "swordsmanship": - list.Add(33); - list.Add(29); - list.Add(30); - - break; - - case "throwing": - list.Add(33); - list.Add(31); - list.Add(32); - - break; - - case "parrying": - list.Add(34); - list.Add(35); - list.Add(36); - - break; - - case "poisoning": - list.Add(39); - list.Add(37); - list.Add(38); - - break; - - case "wrestling": - list.Add(40); - list.Add(42); - list.Add(41); - - break; - - case "animal taming": - list.Add(45); - list.Add(43); - list.Add(44); - - break; - } - - return list; - } - - public static string GetMasteryGroupByID(int id) - { - switch (id) - { - default: - case 1: - case 2: return "Provocation"; - - case 3: - case 4: return "Peacemaking"; - - case 5: - case 6: return "Discordance"; - - case 7: - case 8: return "Magery"; - - case 9: - case 10: return "Mysticism"; - - case 11: - case 12: return "Necromancy"; - - case 13: - case 14: return "Spellweaving"; - - case 16: - case 17: return "Bushido"; - - case 19: - case 20: return "Chivalry"; - - case 21: - case 22: return "Ninjitsu"; - - case 23: - case 24: return "Archery"; - - case 25: - case 26: return "Fencing"; - - case 27: - case 28: return "Mace Fighting"; - - case 29: - case 30: return "Swordmanship"; - - case 31: - case 32: return "Throwing"; - - case 34: - case 35: - case 36: return "Parrying"; - - case 37: - case 38: - case 39: return "Poisoning"; - - case 40: - case 41: - case 42: return "Wrestling"; - - case 43: - case 44: - case 45: return "Animal Taming"; - - case 15: - case 18: - case 33: return "Passive"; - } - } - - public static void SetSpell(int id, in SpellDefinition newspell) - { - _spellsDict[id] = newspell; - } - - internal static void Clear() - { - _spellsDict.Clear(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/SpellsMysticism.cs b/src/ClassicUO.Client/Game/Data/SpellsMysticism.cs deleted file mode 100644 index fe20c37bb..000000000 --- a/src/ClassicUO.Client/Game/Data/SpellsMysticism.cs +++ /dev/null @@ -1,341 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Game.Managers; - -namespace ClassicUO.Game.Data -{ - internal static class SpellsMysticism - { - private static readonly Dictionary _spellsDict; - - static SpellsMysticism() - { - _spellsDict = new Dictionary - { - // Spell List - { - 1, - new SpellDefinition - ( - "Nether Bolt", - 678, - 0x5DC0, - "In Corp Ylem", - 4, - 0, - TargetType.Harmful, - Reagents.BlackPearl, - Reagents.SulfurousAsh - ) - }, - { - 2, - new SpellDefinition - ( - "Healing Stone", - 679, - 0x5DC1, - "Kal In Mani", - 4, - 0, - TargetType.Neutral, - Reagents.Bone, - Reagents.Garlic, - Reagents.Ginseng, - Reagents.SpidersSilk - ) - }, - { - 3, - new SpellDefinition - ( - "Purge Magic", - 680, - 0x5DC2, - "An Ort Sanct", - 6, - 8, - TargetType.Beneficial, - Reagents.FertileDirt, - Reagents.Garlic, - Reagents.MandrakeRoot, - Reagents.SulfurousAsh - ) - }, - { - 4, - new SpellDefinition - ( - "Enchant", - 681, - 0x5DC3, - "In Ort Ylem", - 6, - 8, - TargetType.Neutral, - Reagents.SpidersSilk, - Reagents.MandrakeRoot, - Reagents.SulfurousAsh - ) - }, - { - 5, - new SpellDefinition - ( - "Sleep", - 682, - 0x5DC4, - "In Zu", - 8, - 20, - TargetType.Harmful, - Reagents.Nightshade, - Reagents.SpidersSilk, - Reagents.BlackPearl - ) - }, - { - 6, - new SpellDefinition - ( - "Eagle Strike", - 683, - 0x5DC5, - "Kal Por Xen", - 9, - 20, - TargetType.Harmful, - Reagents.Bloodmoss, - Reagents.Bone, - Reagents.MandrakeRoot, - Reagents.SpidersSilk - ) - }, - { - 7, - new SpellDefinition - ( - "Animated Weapon", - 684, - 0x5DC6, - "In Jux Por Ylem", - 11, - 33, - TargetType.Neutral, - Reagents.Bone, - Reagents.BlackPearl, - Reagents.MandrakeRoot, - Reagents.Nightshade - ) - }, - { - 8, - new SpellDefinition - ( - "Stone Form", - 685, - 0x5DC7, - "In Rel Ylem", - 11, - 33, - TargetType.Neutral, - Reagents.Bloodmoss, - Reagents.FertileDirt, - Reagents.Garlic - ) - }, - { - 9, - new SpellDefinition - ( - "Spell Trigger", - 686, - 0x5DC8, - "In Vas Ort Ex", - 14, - 45, - TargetType.Neutral, - Reagents.DragonsBlood, - Reagents.Garlic, - Reagents.MandrakeRoot, - Reagents.SpidersSilk - ) - }, - { - 10, - new SpellDefinition - ( - "Mass Sleep", - 687, - 0x5DC9, - "Vas Zu", - 14, - 45, - TargetType.Harmful, - Reagents.Ginseng, - Reagents.Nightshade, - Reagents.SpidersSilk - ) - }, - { - 11, - new SpellDefinition - ( - "Cleansing Winds", - 688, - 0x5DCA, - "In Vas Mani Hur", - 20, - 58, - TargetType.Beneficial, - Reagents.DragonsBlood, - Reagents.Garlic, - Reagents.Ginseng, - Reagents.MandrakeRoot - ) - }, - { - 12, - new SpellDefinition - ( - "Bombard", - 689, - 0x5DCB, - "Corp Por Ylem", - 20, - 58, - TargetType.Harmful, - Reagents.Bloodmoss, - Reagents.DragonsBlood, - Reagents.Garlic, - Reagents.SulfurousAsh - ) - }, - { - 13, - new SpellDefinition - ( - "Spell Plague", - 690, - 0x5DCC, - "Vas Rel Jux Ort", - 40, - 70, - TargetType.Harmful, - Reagents.DemonBone, - Reagents.DragonsBlood, - Reagents.Nightshade, - Reagents.SulfurousAsh - ) - }, - { - 14, - new SpellDefinition - ( - "Hail Storm", - 691, - 0x5DCD, - "Kal Des Ylem", - 50, - 70, - TargetType.Harmful, - Reagents.DragonsBlood, - Reagents.BlackPearl, - Reagents.Bloodmoss, - Reagents.MandrakeRoot - ) - }, - { - 15, - new SpellDefinition - ( - "Nether Cyclone", - 692, - 0x5DCE, - "Grav Hur", - 50, - 83, - TargetType.Harmful, - Reagents.MandrakeRoot, - Reagents.Nightshade, - Reagents.SulfurousAsh, - Reagents.Bloodmoss - ) - }, - { - 16, - new SpellDefinition - ( - "Rising Colossus", - 693, - 0x5DCF, - "Kal Vas Xen Corp Ylem", - 50, - 83, - TargetType.Neutral, - Reagents.DemonBone, - Reagents.DragonsBlood, - Reagents.FertileDirt, - Reagents.Nightshade - ) - } - }; - } - - public static string SpellBookName { get; set; } = SpellBookType.Mysticism.ToString(); - - public static IReadOnlyDictionary GetAllSpells => _spellsDict; - internal static int MaxSpellCount => _spellsDict.Count; - - public static SpellDefinition GetSpell(int spellIndex) - { - if (_spellsDict.TryGetValue(spellIndex, out SpellDefinition spell)) - { - return spell; - } - - return SpellDefinition.EmptySpell; - } - - public static void SetSpell(int id, in SpellDefinition newspell) - { - _spellsDict[id] = newspell; - } - - internal static void Clear() - { - _spellsDict.Clear(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/SpellsNecromancy.cs b/src/ClassicUO.Client/Game/Data/SpellsNecromancy.cs deleted file mode 100644 index f49474f57..000000000 --- a/src/ClassicUO.Client/Game/Data/SpellsNecromancy.cs +++ /dev/null @@ -1,328 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Game.Managers; - -namespace ClassicUO.Game.Data -{ - internal static class SpellsNecromancy - { - private static readonly Dictionary _spellsDict; - - static SpellsNecromancy() - { - _spellsDict = new Dictionary - { - // Spell List - { - 1, - new SpellDefinition - ( - "Animate Dead", - 101, - 0x5000, - "Uus Corp", - 23, - 40, - TargetType.Neutral, - Reagents.DaemonBlood, - Reagents.GraveDust - ) - }, - { - 2, - new SpellDefinition - ( - "Blood Oath", - 102, - 0x5001, - "In Jux Mani Xen", - 13, - 20, - TargetType.Harmful, - Reagents.DaemonBlood - ) - }, - { - 3, - new SpellDefinition - ( - "Corpse Skin", - 103, - 0x5002, - "In Agle Corp Ylem", - 11, - 20, - TargetType.Harmful, - Reagents.BatWing, - Reagents.GraveDust - ) - }, - { - 4, - new SpellDefinition - ( - "Curse Weapon", - 104, - 0x5003, - "An Sanct Gra Char", - 7, - 0, - TargetType.Neutral, - Reagents.PigIron - ) - }, - { - 5, - new SpellDefinition - ( - "Evil Omen", - 105, - 0x5004, - "Pas Tym An Sanct", - 11, - 20, - TargetType.Harmful, - Reagents.BatWing, - Reagents.NoxCrystal - ) - }, - { - 6, - new SpellDefinition - ( - "Horrific Beast", - 106, - 0x5005, - "Rel Xen Vas Bal", - 11, - 40, - TargetType.Neutral, - Reagents.BatWing, - Reagents.DaemonBlood - ) - }, - { - 7, - new SpellDefinition - ( - "Lich Form", - 107, - 0x5006, - "Rel Xen Corp Ort", - 25, - 70, - TargetType.Neutral, - Reagents.DaemonBlood, - Reagents.GraveDust, - Reagents.NoxCrystal - ) - }, - { - 8, - new SpellDefinition - ( - "Mind Rot", - 108, - 0x5007, - "Wis An Ben", - 17, - 30, - TargetType.Harmful, - Reagents.BatWing, - Reagents.DaemonBlood, - Reagents.PigIron - ) - }, - { - 9, - new SpellDefinition - ( - "Pain Spike", - 109, - 0x5008, - "In Sar", - 5, - 20, - TargetType.Harmful, - Reagents.GraveDust, - Reagents.PigIron - ) - }, - { - 10, - new SpellDefinition - ( - "Poison Strike", - 110, - 0x5009, - "In Vas Nox", - 17, - 50, - TargetType.Harmful, - Reagents.NoxCrystal - ) - }, - { - 11, - new SpellDefinition - ( - "Strangle", - 111, - 0x500A, - "In Bal Nox", - 29, - 65, - TargetType.Harmful, - Reagents.DaemonBlood, - Reagents.NoxCrystal - ) - }, - { - 12, - new SpellDefinition - ( - "Summon Familiar", - 112, - 0x500B, - "Kal Xen Bal", - 17, - 30, - TargetType.Neutral, - Reagents.BatWing, - Reagents.DaemonBlood, - Reagents.GraveDust - ) - }, - { - 13, - new SpellDefinition - ( - "Vampiric Embrace", - 113, - 0x500C, - "Rel Xen An Sanct", - 25, - 99, - TargetType.Neutral, - Reagents.BatWing, - Reagents.NoxCrystal, - Reagents.PigIron - ) - }, - { - 14, - new SpellDefinition - ( - "Vengeful Spirit", - 114, - 0x500D, - "Kal Xen Bal Beh", - 41, - 80, - TargetType.Harmful, - Reagents.BatWing, - Reagents.GraveDust, - Reagents.PigIron - ) - }, - { - 15, - new SpellDefinition - ( - "Wither", - 115, - 0x500E, - "Kal Vas An Flam", - 23, - 60, - TargetType.Harmful, - Reagents.GraveDust, - Reagents.NoxCrystal, - Reagents.PigIron - ) - }, - { - 16, - new SpellDefinition - ( - "Wraith Form", - 116, - 0x500F, - "Rel Xen Um", - 17, - 20, - TargetType.Neutral, - Reagents.NoxCrystal, - Reagents.PigIron - ) - }, - { - 17, - new SpellDefinition - ( - "Exorcism", - 117, - 0x5010, - "Ort Corp Grav", - 40, - 80, - TargetType.Neutral, - Reagents.NoxCrystal, - Reagents.GraveDust - ) - } - }; - } - - public static string SpellBookName { get; set; } = SpellBookType.Necromancy.ToString(); - - public static IReadOnlyDictionary GetAllSpells => _spellsDict; - internal static int MaxSpellCount => _spellsDict.Count; - - public static SpellDefinition GetSpell(int spellIndex) - { - return _spellsDict.TryGetValue(spellIndex, out SpellDefinition spell) ? spell : SpellDefinition.EmptySpell; - } - - public static void SetSpell(int id, in SpellDefinition newspell) - { - _spellsDict[id] = newspell; - } - - internal static void Clear() - { - _spellsDict.Clear(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/SpellsNinjitsu.cs b/src/ClassicUO.Client/Game/Data/SpellsNinjitsu.cs deleted file mode 100644 index dbc2e92fc..000000000 --- a/src/ClassicUO.Client/Game/Data/SpellsNinjitsu.cs +++ /dev/null @@ -1,187 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Game.Managers; - -namespace ClassicUO.Game.Data -{ - internal static class SpellsNinjitsu - { - private static readonly Dictionary _spellsDict; - - static SpellsNinjitsu() - { - _spellsDict = new Dictionary - { - // Spell List - { - 1, - new SpellDefinition - ( - "Focus Attack", - 501, - 0x5320, - string.Empty, - 20, - 60, - TargetType.Harmful, - Reagents.None - ) - }, - { - 2, - new SpellDefinition - ( - "Death Strike", - 502, - 0x5321, - string.Empty, - 30, - 85, - TargetType.Harmful, - Reagents.None - ) - }, - { - 3, - new SpellDefinition - ( - "Animal Form", - 503, - 0x5322, - string.Empty, - 0, - 10, - TargetType.Beneficial, - Reagents.None - ) - }, - { - 4, - new SpellDefinition - ( - "Ki Attack", - 504, - 0x5323, - string.Empty, - 25, - 80, - TargetType.Harmful, - Reagents.None - ) - }, - { - 5, - new SpellDefinition - ( - "Surprise Attack", - 505, - 0x5324, - string.Empty, - 20, - 30, - TargetType.Harmful, - Reagents.None - ) - }, - { - 6, - new SpellDefinition - ( - "Backstab", - 506, - 0x5325, - string.Empty, - 30, - 20, - TargetType.Harmful, - Reagents.None - ) - }, - { - 7, - new SpellDefinition - ( - "Shadowjump", - 507, - 0x5326, - string.Empty, - 15, - 50, - TargetType.Neutral, - Reagents.None - ) - }, - { - 8, - new SpellDefinition - ( - "Mirror Image", - 508, - 0x5327, - string.Empty, - 10, - 40, - TargetType.Neutral, - Reagents.None - ) - } - }; - } - - public static string SpellBookName { get; set; } = SpellBookType.Ninjitsu.ToString(); - - public static IReadOnlyDictionary GetAllSpells => _spellsDict; - internal static int MaxSpellCount => _spellsDict.Count; - - public static SpellDefinition GetSpell(int spellIndex) - { - if (_spellsDict.TryGetValue(spellIndex, out SpellDefinition spell)) - { - return spell; - } - - return SpellDefinition.EmptySpell; - } - - public static void SetSpell(int id, in SpellDefinition newspell) - { - _spellsDict[id] = newspell; - } - - internal static void Clear() - { - _spellsDict.Clear(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/SpellsSpellweaving.cs b/src/ClassicUO.Client/Game/Data/SpellsSpellweaving.cs deleted file mode 100644 index 2cce9ed3c..000000000 --- a/src/ClassicUO.Client/Game/Data/SpellsSpellweaving.cs +++ /dev/null @@ -1,299 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Game.Managers; - -namespace ClassicUO.Game.Data -{ - internal static class SpellsSpellweaving - { - private static readonly Dictionary _spellsDict; - - static SpellsSpellweaving() - { - _spellsDict = new Dictionary - { - // Spell List - { - 1, - new SpellDefinition - ( - "Arcane Circle", - 601, - 0x59D8, - "Myrshalee", - 20, - 0, - TargetType.Neutral, - Reagents.None - ) - }, - { - 2, - new SpellDefinition - ( - "Gift of Renewal", - 602, - 0x59D9, - "Olorisstra", - 24, - 0, - TargetType.Beneficial, - Reagents.None - ) - }, - { - 3, - new SpellDefinition - ( - "Immolating Weapon", - 603, - 0x59DA, - "Thalshara", - 32, - 10, - TargetType.Neutral, - Reagents.None - ) - }, - { - 4, - new SpellDefinition - ( - "Attune Weapon", - 604, - 0x59DB, - "Haeldril", - 24, - 0, - TargetType.Harmful, - Reagents.None - ) - }, - { - 5, - new SpellDefinition - ( - "Thunderstorm", - 605, - 0x59DC, - "Erelonia", - 32, - 10, - TargetType.Harmful, - Reagents.None - ) - }, - { - 6, - new SpellDefinition - ( - "Nature's Fury", - 606, - 0x59DD, - "Rauvvrae", - 24, - 0, - TargetType.Neutral, - Reagents.None - ) - }, - { - 7, - new SpellDefinition - ( - "Summon Fey", - 607, - 0x59DE, - "Alalithra", - 10, - 38, - TargetType.Neutral, - Reagents.None - ) - }, - { - 8, - new SpellDefinition - ( - "Summon Fiend", - 608, - 0x59DF, - "Nylisstra", - 10, - 38, - TargetType.Neutral, - Reagents.None - ) - }, - { - 9, - new SpellDefinition - ( - "Reaper Form", - 609, - 0x59E0, - "Tarisstree", - 34, - 24, - TargetType.Neutral, - Reagents.None - ) - }, - { - 10, - new SpellDefinition - ( - "Wildfire", - 610, - 0x59E1, - "Haelyn", - 50, - 66, - TargetType.Harmful, - Reagents.None - ) - }, - { - 11, - new SpellDefinition - ( - "Essence of Wind", - 611, - 0x59E2, - "Anathrae", - 40, - 52, - TargetType.Harmful, - Reagents.None - ) - }, - { - 12, - new SpellDefinition - ( - "Dryad Allure", - 612, - 0x59E3, - "Rathril", - 40, - 52, - TargetType.Neutral, - Reagents.None - ) - }, - { - 13, - new SpellDefinition - ( - "Ethereal Voyage", - 613, - 0x59E4, - "Orlavdra", - 32, - 24, - TargetType.Neutral, - Reagents.None - ) - }, - { - 14, - new SpellDefinition - ( - "Word of Death", - 614, - 0x59E5, - "Nyraxle", - 50, - 23, - TargetType.Harmful, - Reagents.None - ) - }, - { - 15, - new SpellDefinition - ( - "Gift of Life", - 615, - 0x59E6, - "Illorae", - 70, - 38, - TargetType.Beneficial, - Reagents.None - ) - }, - { - 16, - new SpellDefinition - ( - "Arcane Empowerment", - 616, - 0x59E7, - "Aslavdra", - 50, - 24, - TargetType.Beneficial, - Reagents.None - ) - } - }; - } - - public static string SpellBookName { get; set; } = SpellBookType.Spellweaving.ToString(); - - public static IReadOnlyDictionary GetAllSpells => _spellsDict; - internal static int MaxSpellCount => _spellsDict.Count; - - public static SpellDefinition GetSpell(int spellIndex) - { - if (_spellsDict.TryGetValue(spellIndex, out SpellDefinition spell)) - { - return spell; - } - - return SpellDefinition.EmptySpell; - } - - public static void SetSpell(int id, in SpellDefinition newspell) - { - _spellsDict[id] = newspell; - } - - internal static void Clear() - { - _spellsDict.Clear(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/StaticFilters.cs b/src/ClassicUO.Client/Game/Data/StaticFilters.cs deleted file mode 100644 index 49c034d1b..000000000 --- a/src/ClassicUO.Client/Game/Data/StaticFilters.cs +++ /dev/null @@ -1,361 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.IO; -using System.Runtime.CompilerServices; -using ClassicUO.Configuration; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; - -namespace ClassicUO.Game.Data -{ - [Flags] - internal enum STATIC_TILES_FILTER_FLAGS : byte - { - STFF_CAVE = 0x01, - STFF_STUMP = 0x02, - STFF_STUMP_HATCHED = 0x04, - STFF_VEGETATION = 0x08, - STFF_WATER = 0x10 - } - - internal static class StaticFilters - { - private static readonly STATIC_TILES_FILTER_FLAGS[] _filteredTiles = new STATIC_TILES_FILTER_FLAGS[ArtLoader.MAX_STATIC_DATA_INDEX_COUNT]; - - public static readonly List CaveTiles = new List(); - public static readonly List TreeTiles = new List(); - - public static void Load() - { - string path = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Client"); - - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - string cave = Path.Combine(path, "cave.txt"); - string vegetation = Path.Combine(path, "vegetation.txt"); - string trees = Path.Combine(path, "tree.txt"); - - - if (!File.Exists(cave)) - { - using (StreamWriter writer = new StreamWriter(cave)) - { - for (int i = 0x053B; i < 0x0553 + 1; i++) - { - if (i != 0x0550) - { - writer.WriteLine(i); - } - } - } - } - - if (!File.Exists(vegetation)) - { - using (StreamWriter writer = new StreamWriter(vegetation)) - { - ushort[] vegetationTiles = - { - 0x0D45, 0x0D46, 0x0D47, 0x0D48, 0x0D49, 0x0D4A, 0x0D4B, 0x0D4C, 0x0D4D, 0x0D4E, 0x0D4F, - 0x0D50, 0x0D51, 0x0D52, 0x0D53, 0x0D54, 0x0D5C, 0x0D5D, 0x0D5E, 0x0D5F, 0x0D60, 0x0D61, - 0x0D62, 0x0D63, 0x0D64, 0x0D65, 0x0D66, 0x0D67, 0x0D68, 0x0D69, 0x0D6D, 0x0D73, 0x0D74, - 0x0D75, 0x0D76, 0x0D77, 0x0D78, 0x0D79, 0x0D7A, 0x0D7B, 0x0D7C, 0x0D7D, 0x0D7E, 0x0D7F, - 0x0D80, 0x0D83, 0x0D87, 0x0D88, 0x0D89, 0x0D8A, 0x0D8B, 0x0D8C, 0x0D8D, 0x0D8E, 0x0D8F, - 0x0D90, 0x0D91, 0x0D93, 0x12B6, 0x12B7, 0x12BC, 0x12BD, 0x12BE, 0x12BF, 0x12C0, 0x12C1, - 0x12C2, 0x12C3, 0x12C4, 0x12C5, 0x12C6, 0x12C7, 0x0CB9, 0x0CBC, 0x0CBD, 0x0CBE, 0x0CBF, - 0x0CC0, 0x0CC1, 0x0CC3, 0x0CC5, 0x0CC6, 0x0CC7, 0x0CF3, 0x0CF4, 0x0CF5, 0x0CF6, 0x0CF7, - 0x0D04, 0x0D06, 0x0D07, 0x0D08, 0x0D09, 0x0D0A, 0x0D0B, 0x0D0C, 0x0D0D, 0x0D0E, 0x0D0F, - 0x0D10, 0x0D11, 0x0D12, 0x0D13, 0x0D14, 0x0D15, 0x0D16, 0x0D17, 0x0D18, 0x0D19, 0x0D28, - 0x0D29, 0x0D2A, 0x0D2B, 0x0D2D, 0x0D34, 0x0D36, 0x0DAE, 0x0DAF, 0x0DBA, 0x0DBB, 0x0DBC, - 0x0DBD, 0x0DBE, 0x0DC1, 0x0DC2, 0x0DC3, 0x0C83, 0x0C84, 0x0C85, 0x0C86, 0x0C87, 0x0C88, - 0x0C89, 0x0C8A, 0x0C8B, 0x0C8C, 0x0C8D, 0x0C8E, 0x0C93, 0x0C94, 0x0C98, 0x0C9F, 0x0CA0, - 0x0CA1, 0x0CA2, 0x0CA3, 0x0CA4, 0x0CA7, 0x0CAC, 0x0CAD, 0x0CAE, 0x0CAF, 0x0CB0, 0x0CB1, - 0x0CB2, 0x0CB3, 0x0CB4, 0x0CB5, 0x0CB6, 0x0C45, 0x0C46, 0x0C49, 0x0C47, 0x0C48, 0x0C4A, - 0x0C4B, 0x0C4C, 0x0C4D, 0x0C4E, 0x0C37, 0x0C38, 0x0CBA, 0x0D2F, 0x0D32, 0x0D33, 0x0D3F, - 0x0D40, 0x0CE9 - }; - - for (int i = 0; i < vegetationTiles.Length; i++) - { - ushort g = vegetationTiles[i]; - - if (TileDataLoader.Instance.StaticData[g].IsImpassable) - { - continue; - } - - writer.WriteLine(g); - } - } - } - - if (!File.Exists(trees)) - { - using (StreamWriter writer = new StreamWriter(trees)) - using (StreamWriter writerveg = new StreamWriter(vegetation, true)) - { - ushort[] treeTiles = - { - 0x0C95, 0x0C96, 0x0C99, 0x0C9B, 0x0C9C, 0x0C9D, 0x0C9E, 0x0CA6, 0x0CA8, 0x0CAA, 0x0CAB, - 0x0CC9, 0x0CCA, 0x0CCB, 0x0CCC, 0x0CCD, 0x0CD0, 0x0CD3, 0x0CD6, 0x0CD8, 0x0CDA, 0x0CDD, - 0x0CE0, 0x0CE3, 0x0CE6, 0x0CF8, 0x0CFB, 0x0CFE, 0x0D01, 0x0D37, 0x0D38, 0x0D41, 0x0D42, - 0x0D43, 0x0D44, 0x0D57, 0x0D58, 0x0D59, 0x0D5A, 0x0D5B, 0x0D6E, 0x0D6F, 0x0D70, 0x0D71, - 0x0D72, 0x0D84, 0x0D85, 0x0D86, 0x0D94, 0x0D98, 0x0D9C, 0x0DA0, 0x0DA4, 0x0DA8, 0x12B6, - 0x12B7, 0x12B8, 0x12B9, 0x12BA, 0x12BB, 0x12BC, 0x12BD - }; - - for (int i = 0; i < treeTiles.Length; i++) - { - ushort graphic = treeTiles[i]; - byte flag = 1; - - switch (graphic) - { - case 0x0C9E: - case 0x0CA8: - case 0x0CAA: - case 0x0CAB: - case 0x0CC9: - case 0x0CF8: - case 0x0CFB: - case 0x0CFE: - case 0x0D01: - case 0x12B6: - case 0x12B7: - case 0x12B8: - case 0x12B9: - case 0x12BA: - case 0x12BB: - flag = 0; - - break; - } - - if (!TileDataLoader.Instance.StaticData[graphic].IsImpassable) - { - writerveg.WriteLine(graphic); - } - else - { - writer.WriteLine($"{graphic}={flag}"); - } - } - } - } - - - TextFileParser caveParser = new TextFileParser(File.ReadAllText(cave), new[] { ' ', '\t', ',' }, new[] { '#', ';' }, new[] { '"', '"' }); - - while (!caveParser.IsEOF()) - { - List ss = caveParser.ReadTokens(); - - if (ss != null && ss.Count != 0) - { - if (ushort.TryParse(ss[0], out ushort graphic)) - { - _filteredTiles[graphic] |= STATIC_TILES_FILTER_FLAGS.STFF_CAVE; - CaveTiles.Add(graphic); - } - } - } - - - TextFileParser stumpsParser = new TextFileParser(File.ReadAllText(trees), new[] { ' ', '\t', ',', '=' }, new[] { '#', ';' }, new[] { '"', '"' }); - - while (!stumpsParser.IsEOF()) - { - List ss = stumpsParser.ReadTokens(); - - if (ss != null && ss.Count >= 2) - { - STATIC_TILES_FILTER_FLAGS flag = STATIC_TILES_FILTER_FLAGS.STFF_STUMP; - - if (byte.TryParse(ss[1], out byte f) && f != 0) - { - flag |= STATIC_TILES_FILTER_FLAGS.STFF_STUMP_HATCHED; - } - - if (ushort.TryParse(ss[0], out ushort graphic)) - { - _filteredTiles[graphic] |= flag; - TreeTiles.Add(graphic); - } - } - } - - - TextFileParser vegetationParser = new TextFileParser(File.ReadAllText(vegetation), new[] { ' ', '\t', ',' }, new[] { '#', ';' }, new[] { '"', '"' }); - - while (!vegetationParser.IsEOF()) - { - List ss = vegetationParser.ReadTokens(); - - if (ss != null && ss.Count != 0) - { - if (ushort.TryParse(ss[0], out ushort graphic)) - { - _filteredTiles[graphic] |= STATIC_TILES_FILTER_FLAGS.STFF_VEGETATION; - } - } - } - } - - public static void CleanCaveTextures() - { - //foreach (ushort graphic in CaveTiles) - //{ - // ArtTexture texture = ArtLoader.Instance.GetTexture(graphic); - - // if (texture != null) - // { - // texture.Ticks = 0; - // } - //} - - //ArtLoader.Instance.CleaUnusedResources(short.MaxValue); - } - - public static void CleanTreeTextures() - { - //foreach (ushort graphic in TreeTiles) - //{ - // ArtTexture texture = ArtLoader.Instance.GetTexture(graphic); - - // if (texture != null) - // { - // texture.Ticks = 0; - // } - //} - - //ArtLoader.Instance.CleaUnusedResources(short.MaxValue); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsTree(ushort g, out int index) - { - STATIC_TILES_FILTER_FLAGS flag = _filteredTiles[g]; - - if ((flag & STATIC_TILES_FILTER_FLAGS.STFF_STUMP) != 0) - { - if ((flag & STATIC_TILES_FILTER_FLAGS.STFF_STUMP_HATCHED) != 0) - { - index = 0; - } - else - { - index = 1; - } - - return true; - } - - index = 0; - - return false; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsVegetation(ushort g) - { - return (_filteredTiles[g] & STATIC_TILES_FILTER_FLAGS.STFF_VEGETATION) != 0; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsCave(ushort g) - { - return (_filteredTiles[g] & STATIC_TILES_FILTER_FLAGS.STFF_CAVE) != 0; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsRock(ushort g) - { - switch (g) - { - case 4945: - case 4948: - case 4950: - case 4953: - case 4955: - case 4958: - case 4959: - case 4960: - case 4962: return true; - - default: return g >= 6001 && g <= 6012; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsField(ushort g) - { - return g >= 0x398C && g <= 0x399F || g >= 0x3967 && g <= 0x397A || g >= 0x3946 && g <= 0x3964 || g >= 0x3914 && g <= 0x3929; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsFireField(ushort g) - { - return g >= 0x398C && g <= 0x399F; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsParalyzeField(ushort g) - { - return g >= 0x3967 && g <= 0x397A; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsEnergyField(ushort g) - { - return g >= 0x3946 && g <= 0x3964; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsPoisonField(ushort g) - { - return g >= 0x3914 && g <= 0x3929; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsWallOfStone(ushort g) - { - return g == 0x038A; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/TextType.cs b/src/ClassicUO.Client/Game/Data/TextType.cs deleted file mode 100644 index a9d5ffa28..000000000 --- a/src/ClassicUO.Client/Game/Data/TextType.cs +++ /dev/null @@ -1,42 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Data -{ - public enum TextType - { - CLIENT, - SYSTEM, - OBJECT, - GUILD_ALLY - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Data/Waypoints.cs b/src/ClassicUO.Client/Game/Data/Waypoints.cs deleted file mode 100644 index d40cab610..000000000 --- a/src/ClassicUO.Client/Game/Data/Waypoints.cs +++ /dev/null @@ -1,51 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Data -{ - internal enum WaypointsType : ushort - { - Corpse = 0x01, - PartyMember = 0x02, - RallyPoint = 0x03, - QuestGiver = 0x04, - QuestDestination = 0x05, - Resurrection = 0x06, - PointOfInterest = 0x07, - Landmark = 0x08, - Town = 0x09, - Dungeon = 0x0A, - Moongate = 0x0B, - Shop = 0x0C, - Player = 0x0D - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/GameActions.cs b/src/ClassicUO.Client/Game/GameActions.cs deleted file mode 100644 index 8d011395a..000000000 --- a/src/ClassicUO.Client/Game/GameActions.cs +++ /dev/null @@ -1,907 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Network; -using ClassicUO.Resources; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using static ClassicUO.Network.NetClient; - -namespace ClassicUO.Game -{ - public static class GameActions - { - public static int LastSpellIndex { get; set; } = 1; - public static int LastSkillIndex { get; set; } = 1; - - - public static void ToggleWarMode() - { - RequestWarMode(!World.Player.InWarMode); - } - - public static void RequestWarMode(bool war) - { - if (!World.Player.IsDead) - { - if (war && ProfileManager.CurrentProfile != null && ProfileManager.CurrentProfile.EnableMusic) - { - Client.Game.Audio.PlayMusic((RandomHelper.GetValue(0, 3) % 3) + 38, true); - } - else if (!war) - { - Client.Game.Audio.StopWarMusic(); - } - } - - Socket.Send_ChangeWarMode(war); - } - - public static void OpenMacroGump(string name) - { - MacroGump macroGump = UIManager.GetGump(); - - macroGump?.Dispose(); - UIManager.Add(new MacroGump(name)); - } - - public static void OpenPaperdoll(uint serial) - { - if (ProfileManager.CurrentProfile.UseModernPaperdoll && serial == World.Player.Serial) - { - ModernPaperdoll modernPaperdoll = UIManager.GetGump(serial); - if (modernPaperdoll == null) - UIManager.Add(new ModernPaperdoll(serial)); - else - { - modernPaperdoll.SetInScreen(); - modernPaperdoll.BringOnTop(); - } - } - else - { - PaperDollGump paperDollGump = UIManager.GetGump(serial); - - if (paperDollGump == null) - { - DoubleClick(serial | 0x80000000); - } - else - { - if (paperDollGump.IsMinimized) - { - paperDollGump.IsMinimized = false; - } - - paperDollGump.SetInScreen(); - paperDollGump.BringOnTop(); - } - } - } - - public static void OpenSettings(int page = 0) - { - ModernOptionsGump opt = UIManager.GetGump(); - - if (opt == null) - { - ModernOptionsGump optionsGump = new ModernOptionsGump(); - - UIManager.Add(optionsGump); - optionsGump.ChangePage(page); - optionsGump.SetInScreen(); - } - else - { - opt.SetInScreen(); - opt.BringOnTop(); - } - } - - public static void OpenStatusBar() - { - Client.Game.Audio.StopWarMusic(); - - if (StatusGumpBase.GetStatusGump() == null) - { - UIManager.Add(StatusGumpBase.AddStatusGump(ProfileManager.CurrentProfile.StatusGumpPosition.X, ProfileManager.CurrentProfile.StatusGumpPosition.Y)); - } - } - - public static void OpenJournal() - { - ResizableJournal resizableJournal = UIManager.GetGump(); - if (resizableJournal == null) - UIManager.Add(new ResizableJournal()); - else - { - resizableJournal.SetInScreen(); - resizableJournal.BringOnTop(); - } - //JournalGump journalGump = UIManager.GetGump(); - - //if (journalGump == null) - //{ - // UIManager.Add(new JournalGump { X = 64, Y = 64 }); - //} - //else - //{ - // journalGump.SetInScreen(); - // journalGump.BringOnTop(); - - // if (journalGump.IsMinimized) - // { - // journalGump.IsMinimized = false; - // } - //} - } - - public static void OpenSkills() - { - StandardSkillsGump skillsGump = UIManager.GetGump(); - - if (skillsGump != null && skillsGump.IsMinimized) - { - skillsGump.IsMinimized = false; - } - else - { - World.SkillsRequested = true; - Socket.Send_SkillsRequest(World.Player.Serial); - } - } - - public static void OpenMiniMap() - { - MiniMapGump miniMapGump = UIManager.GetGump(); - - if (miniMapGump == null) - { - UIManager.Add(new MiniMapGump()); - } - else - { - miniMapGump.ToggleSize(); - miniMapGump.SetInScreen(); - miniMapGump.BringOnTop(); - } - } - - public static void BandageSelf() - { - Item bandage = World.Player.FindBandage(); - if(bandage != null) - { - NetClient.Socket.Send_TargetSelectedObject(bandage.Serial, World.Player.Serial); - } - } - - public static void OpenWorldMap() - { - WorldMapGump worldMap = UIManager.GetGump(); - - if (worldMap == null || worldMap.IsDisposed) - { - worldMap = new WorldMapGump(); - UIManager.Add(worldMap); - } - else - { - worldMap.BringOnTop(); - worldMap.SetInScreen(); - } - } - - public static void OpenChat() - { - if (ChatManager.ChatIsEnabled == ChatStatus.Enabled) - { - ChatGump chatGump = UIManager.GetGump(); - - if (chatGump == null) - { - UIManager.Add(new ChatGump()); - } - else - { - chatGump.SetInScreen(); - chatGump.BringOnTop(); - } - } - else if (ChatManager.ChatIsEnabled == ChatStatus.EnabledUserRequest) - { - ChatGumpChooseName chatGump = UIManager.GetGump(); - - if (chatGump == null) - { - UIManager.Add(new ChatGumpChooseName()); - } - else - { - chatGump.SetInScreen(); - chatGump.BringOnTop(); - } - } - } - - public static bool OpenCorpse(uint serial) - { - if (!SerialHelper.IsItem(serial)) - { - return false; - } - - Item item = World.Items.Get(serial); - - if (item == null || !item.IsCorpse || item.IsDestroyed) - { - return false; - } - - World.Player.ManualOpenedCorpses.Add(serial); - DoubleClick(serial); - - return true; - } - - public static bool OpenBackpack() - { - Item backpack = World.Player.FindItemByLayer(Layer.Backpack); - - if (backpack == null) - { - return false; - } - - Gump backpackGump = UIManager.GetGump(backpack); - if (backpackGump == null) - { - backpackGump = UIManager.GetGump(backpack); - if (backpackGump == null) - { - GameActions.DoubleClick(backpack); - return true; - } - else - { - backpackGump.RequestUpdateContents(); - backpackGump.SetInScreen(); - backpackGump.BringOnTop(); - } - } - else - { - ((ContainerGump)backpackGump).IsMinimized = false; - backpackGump.SetInScreen(); - backpackGump.BringOnTop(); - } - return true; - } - - public static void Attack(uint serial) - { - if (ProfileManager.CurrentProfile.EnabledCriminalActionQuery) - { - Mobile m = World.Mobiles.Get(serial); - - if (m != null && (World.Player.NotorietyFlag == NotorietyFlag.Innocent || World.Player.NotorietyFlag == NotorietyFlag.Ally) && m.NotorietyFlag == NotorietyFlag.Innocent && m != World.Player) - { - QuestionGump messageBox = new QuestionGump - ( - ResGeneral.ThisMayFlagYouCriminal, - s => - { - if (s) - { - Socket.Send_AttackRequest(serial); - } - } - ); - - UIManager.Add(messageBox); - return; - } - } - - TargetManager.LastAttack = serial; - Socket.Send_AttackRequest(serial); - } - - public static void DoubleClickQueued(uint serial) - { - Client.Game.GetScene()?.DoubleClickDelayed(serial); - } - - public static void DoubleClick(uint serial) - { - if (serial != World.Player && SerialHelper.IsMobile(serial) && World.Player.InWarMode) - { - RequestMobileStatus(serial); - Attack(serial); - } - else - { - if (SerialHelper.IsItem(serial)) - { - Gump g = UIManager.GetGump(serial); - if (g != null) - { - g.SetInScreen(); - g.BringOnTop(); - } - Socket.Send_DoubleClick(serial); - } - else - Socket.Send_DoubleClick(serial); - } - - if (SerialHelper.IsItem(serial) || (SerialHelper.IsMobile(serial) && (World.Mobiles.Get(serial)?.IsHuman ?? false))) - { - World.LastObject = serial; - } - else - { - World.LastObject = 0; - } - } - - public static void SingleClick(uint serial) - { - // add request context menu - Socket.Send_ClickRequest(serial); - - Entity entity = World.Get(serial); - - if (entity != null) - { - entity.IsClicked = true; - } - } - - public static void Say(string message, ushort hue = 0xFFFF, MessageType type = MessageType.Regular, byte font = 3) - { - if (hue == 0xFFFF) - { - hue = ProfileManager.CurrentProfile.SpeechHue; - } - - // TODO: identify what means 'older client' that uses ASCIISpeechRquest [0x03] - // - // Fix -> #1267 - if (Client.Version >= ClientVersion.CV_200) - { - Socket.Send_UnicodeSpeechRequest(message, - type, - font, - hue, - Settings.GlobalSettings.Language); - } - else - { - Socket.Send_ASCIISpeechRequest(message, type, font, hue); - } - } - - - public static void Print(string message, ushort hue = 946, MessageType type = MessageType.Regular, byte font = 3, bool unicode = true) - { - if (type == MessageType.ChatSystem) - { - MessageManager.HandleMessage - ( - null, - message, - "Chat", - hue, - type, - font, - TextType.OBJECT, - unicode, - Settings.GlobalSettings.Language - ); - return; - } - - Print - ( - null, - message, - hue, - type, - font, - unicode - ); - } - - public static void Print - ( - Entity entity, - string message, - ushort hue = 946, - MessageType type = MessageType.Regular, - byte font = 3, - bool unicode = true - ) - { - MessageManager.HandleMessage - ( - entity, - message, - entity != null ? entity.Name : "System", - hue, - type, - font, - entity == null ? TextType.SYSTEM : TextType.OBJECT, - unicode, - Settings.GlobalSettings.Language - ); - } - - public static void SayParty(string message, uint serial = 0) - { - Socket.Send_PartyMessage(message, serial); - } - - public static void RequestPartyAccept(uint serial) - { - Socket.Send_PartyAccept(serial); - - UIManager.GetGump()?.Dispose(); - } - - public static void RequestPartyRemoveMemberByTarget() - { - Socket.Send_PartyRemoveRequest(0x00); - } - - public static void RequestPartyRemoveMember(uint serial) - { - Socket.Send_PartyRemoveRequest(serial); - } - - public static void RequestPartyQuit() - { - Socket.Send_PartyRemoveRequest(World.Player.Serial); - } - - public static void RequestPartyInviteByTarget() - { - Socket.Send_PartyInviteRequest(); - } - - public static void RequestPartyLootState(bool isLootable) - { - Socket.Send_PartyChangeLootTypeRequest(isLootable); - } - - public static bool PickUp - ( - uint serial, - int x, - int y, - int amount = -1, - Point? offset = null, - bool is_gump = false - ) - { - if (World.Player.IsDead || Client.Game.GameCursor.ItemHold.Enabled) - { - return false; - } - - Item item = World.Items.Get(serial); - - if (item == null || item.IsDestroyed || item.IsMulti || item.OnGround && (item.IsLocked || item.Distance > Constants.DRAG_ITEMS_DISTANCE)) - { - return false; - } - - if (amount <= -1 && item.Amount > 1 && item.ItemData.IsStackable) - { - if (ProfileManager.CurrentProfile.HoldShiftToSplitStack == Keyboard.Shift) - { - SplitMenuGump gump = UIManager.GetGump(item); - - if (gump != null) - { - return false; - } - - gump = new SplitMenuGump(item, new Point(x, y)) - { - X = Mouse.Position.X - 80, - Y = Mouse.Position.Y - 40 - }; - - UIManager.Add(gump); - UIManager.AttemptDragControl(gump, true); - - return true; - } - } - - if (amount <= 0) - { - amount = item.Amount; - } - - Client.Game.GameCursor.ItemHold.Clear(); - Client.Game.GameCursor.ItemHold.Set(item, (ushort)amount, offset); - Client.Game.GameCursor.ItemHold.IsGumpTexture = is_gump; - Socket.Send_PickUpRequest(item, (ushort)amount); - - if (item.OnGround) - { - item.RemoveFromTile(); - } - - item.TextContainer?.Clear(); - - World.ObjectToRemove = item.Serial; - - return true; - } - - public static void DropItem(uint serial, int x, int y, int z, uint container) - { - if (Client.Game.GameCursor.ItemHold.Enabled && !Client.Game.GameCursor.ItemHold.IsFixedPosition && (Client.Game.GameCursor.ItemHold.Serial != container || Client.Game.GameCursor.ItemHold.ItemData.IsStackable)) - { - if (Client.Version >= ClientVersion.CV_6017) - { - Socket.Send_DropRequest(serial, - (ushort)x, - (ushort)y, - (sbyte)z, - 0, - container); - } - else - { - Socket.Send_DropRequest_Old(serial, - (ushort)x, - (ushort)y, - (sbyte)z, - container); - } - - Client.Game.GameCursor.ItemHold.Enabled = false; - Client.Game.GameCursor.ItemHold.Dropped = true; - } - } - - public static void Equip(uint container = 0) - { - if (Client.Game.GameCursor.ItemHold.Enabled && !Client.Game.GameCursor.ItemHold.IsFixedPosition && Client.Game.GameCursor.ItemHold.ItemData.IsWearable) - { - if (!SerialHelper.IsValid(container)) - { - container = World.Player.Serial; - } - - Socket.Send_EquipRequest(Client.Game.GameCursor.ItemHold.Serial, (Layer)Client.Game.GameCursor.ItemHold.ItemData.Layer, container); - - Client.Game.GameCursor.ItemHold.Enabled = false; - Client.Game.GameCursor.ItemHold.Dropped = true; - } - } - - public static void ReplyGump(uint local, uint server, int button, uint[] switches = null, Tuple[] entries = null) - { - Socket.Send_GumpResponse(local, - server, - button, - switches, - entries); - } - - public static void RequestHelp() - { - Socket.Send_HelpRequest(); - } - - public static void RequestQuestMenu() - { - Socket.Send_QuestMenuRequest(); - } - - public static void RequestProfile(uint serial) - { - Socket.Send_ProfileRequest(serial); - } - - public static void ChangeSkillLockStatus(ushort skillindex, byte lockstate) - { - Socket.Send_SkillStatusChangeRequest(skillindex, lockstate); - } - - public static void RequestMobileStatus(uint serial, bool force = false) - { - if (World.InGame) - { - Entity ent = World.Get(serial); - - if (ent != null) - { - if (force) - { - if (ent.HitsRequest >= HitsRequestStatus.Pending) - { - SendCloseStatus(serial); - } - } - - if (ent.HitsRequest < HitsRequestStatus.Received) - { - ent.HitsRequest = HitsRequestStatus.Pending; - force = true; - } - } - - if (force && SerialHelper.IsValid(serial)) - { - //ent = ent ?? World.Player; - //ent.AddMessage(MessageType.Regular, $"PACKET SENT: 0x{serial:X8}", 3, 0x34, true, TextType.OBJECT); - Socket.Send_StatusRequest(serial); - } - } - } - - public static void SendCloseStatus(uint serial, bool force = false) - { - if (Client.Version >= ClientVersion.CV_200 && World.InGame) - { - Entity ent = World.Get(serial); - - if (ent != null && ent.HitsRequest >= HitsRequestStatus.Pending) - { - ent.HitsRequest = HitsRequestStatus.None; - force = true; - } - - if (force && SerialHelper.IsValid(serial)) - { - //ent = ent ?? World.Player; - //ent.AddMessage(MessageType.Regular, $"PACKET REMOVED SENT: 0x{serial:X8}", 3, 0x34 + 10, true, TextType.OBJECT); - Socket.Send_CloseStatusBarGump(serial); - } - } - } - - public static void CastSpellFromBook(int index, uint bookSerial) - { - if (index >= 0) - { - LastSpellIndex = index; - SpellVisualRangeManager.Instance.ClearCasting(); - Socket.Send_CastSpellFromBook(index, bookSerial); - } - } - - public static void CastSpell(int index) - { - if (index >= 0) - { - LastSpellIndex = index; - SpellVisualRangeManager.Instance.ClearCasting(); - Socket.Send_CastSpell(index); - } - } - - public static void OpenGuildGump() - { - Socket.Send_GuildMenuRequest(); - } - - public static void ChangeStatLock(byte stat, Lock state) - { - Socket.Send_StatLockStateRequest(stat, state); - } - - public static void Rename(uint serial, string name) - { - Socket.Send_RenameRequest(serial, name); - } - - public static void UseSkill(int index) - { - if (index >= 0) - { - LastSkillIndex = index; - Socket.Send_UseSkill(index); - } - } - - public static void OpenPopupMenu(uint serial, bool shift = false) - { - shift = shift || Keyboard.Shift; - - if (ProfileManager.CurrentProfile.HoldShiftForContext && !shift) - { - return; - } - - Socket.Send_RequestPopupMenu(serial); - } - - public static void ResponsePopupMenu(uint serial, ushort index) - { - Socket.Send_PopupMenuSelection(serial, index); - } - - public static void MessageOverhead(string message, uint entity) - { - Print(World.Get(entity), message); - } - - public static void MessageOverhead(string message, ushort hue, uint entity) - { - Print(World.Get(entity), message, hue); - } - - public static void AcceptTrade(uint serial, bool accepted) - { - Socket.Send_TradeResponse(serial, 2, accepted); - } - - public static void CancelTrade(uint serial) - { - Socket.Send_TradeResponse(serial, 1, false); - } - - public static void AllNames() - { - foreach (Mobile mobile in World.Mobiles.Values) - { - if (mobile != World.Player) - { - Socket.Send_ClickRequest(mobile.Serial); - } - } - - foreach (Item item in World.Items.Values) - { - if (item.IsCorpse) - { - Socket.Send_ClickRequest(item.Serial); - } - } - } - - public static void OpenDoor() - { - Socket.Send_OpenDoor(); - } - - public static void EmoteAction(string action) - { - Socket.Send_EmoteAction(action); - } - - public static void OpenAbilitiesBook() - { - if (UIManager.GetGump() == null) - { - UIManager.Add(new CombatBookGump(100, 100)); - } - } - - public static void UsePrimaryAbility() - { - ref Ability ability = ref World.Player.Abilities[0]; - - if (((byte)ability & 0x80) == 0) - { - for (int i = 0; i < 2; i++) - { - World.Player.Abilities[i] &= (Ability)0x7F; - } - - Socket.Send_UseCombatAbility((byte)ability); - } - else - { - Socket.Send_UseCombatAbility(0); - } - - ability ^= (Ability)0x80; - } - - public static void UseSecondaryAbility() - { - ref Ability ability = ref World.Player.Abilities[1]; - - if (((byte)ability & 0x80) == 0) - { - for (int i = 0; i < 2; i++) - { - World.Player.Abilities[i] &= (Ability)0x7F; - } - - Socket.Send_UseCombatAbility((byte)ability); - } - else - { - Socket.Send_UseCombatAbility(0); - } - - ability ^= (Ability)0x80; - } - - public static void QuestArrow(bool rightClick) - { - Socket.Send_ClickQuestArrow(rightClick); - } - - public static void GrabItem(uint serial, ushort amount, uint bag = 0) - { - //Socket.Send(new PPickUpRequest(serial, amount)); - - Item backpack = World.Player.FindItemByLayer(Layer.Backpack); - - if (backpack == null) - { - return; - } - - if (bag == 0) - { - bag = ProfileManager.CurrentProfile.GrabBagSerial == 0 ? backpack.Serial : ProfileManager.CurrentProfile.GrabBagSerial; - } - - if (!World.Items.Contains(bag)) - { - Print(ResGeneral.GrabBagNotFound); - ProfileManager.CurrentProfile.GrabBagSerial = 0; - bag = backpack.Serial; - } - - PickUp(serial, 0, 0, amount); - - DropItem - ( - serial, - 0xFFFF, - 0xFFFF, - 0, - bag - ); - } - } -} diff --git a/src/ClassicUO.Client/Game/GameCursor.cs b/src/ClassicUO.Client/Game/GameCursor.cs deleted file mode 100644 index e86166a3e..000000000 --- a/src/ClassicUO.Client/Game/GameCursor.cs +++ /dev/null @@ -1,809 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using SDL2; - -namespace ClassicUO.Game -{ - internal sealed class GameCursor - { - private static readonly ushort[,] _cursorData = new ushort[3, 16] - { - { - 0x206A, - 0x206B, - 0x206C, - 0x206D, - 0x206E, - 0x206F, - 0x2070, - 0x2071, - 0x2072, - 0x2073, - 0x2074, - 0x2075, - 0x2076, - 0x2077, - 0x2078, - 0x2079 - }, - { - 0x2053, - 0x2054, - 0x2055, - 0x2056, - 0x2057, - 0x2058, - 0x2059, - 0x205A, - 0x205B, - 0x205C, - 0x205D, - 0x205E, - 0x205F, - 0x2060, - 0x2061, - 0x2062 - }, - { - 0x206A, - 0x206B, - 0x206C, - 0x206D, - 0x206E, - 0x206F, - 0x2070, - 0x2071, - 0x2072, - 0x2073, - 0x2074, - 0x2075, - 0x2076, - 0x2077, - 0x2078, - 0x2079 - } - }; - - private readonly Aura _aura = new Aura(30); - private readonly CustomBuildObject[] _componentsList = new CustomBuildObject[10]; - private readonly int[,] _cursorOffset = new int[2, 16]; - private readonly IntPtr[,] _cursors_ptr = new IntPtr[3, 16]; - private ushort _graphic = 0x2073; - private bool _needGraphicUpdate = true; - private readonly List _temp = new List(); - private readonly Tooltip _tooltip; - - public GameCursor() - { - _tooltip = new Tooltip(); - - for (int i = 0; i < 3; i++) - { - for (int j = 0; j < 16; j++) - { - ushort id = _cursorData[i, j]; - - var surface = Client.Game.Arts.CreateCursorSurfacePtr( - id, - (ushort)(i == 2 ? 0x0033 : 0), - out int hotX, - out int hotY - ); - - if (surface != IntPtr.Zero) - { - if (hotX != 0 || hotY != 0) - { - _cursorOffset[0, j] = hotX; - _cursorOffset[1, j] = hotY; - } - - _cursors_ptr[i, j] = SDL.SDL_CreateColorCursor(surface, hotX, hotY); - } - } - } - } - - public ushort Graphic - { - get => _graphic; - set - { - if (_graphic != value) - { - _graphic = value; - _needGraphicUpdate = true; - } - } - } - - public bool IsLoading { get; set; } - public bool IsDraggingCursorForced { get; set; } - public bool AllowDrawSDLCursor { get; set; } = true; - - public ItemHold ItemHold { get; } = new ItemHold(); - - private ushort GetDraggingItemGraphic() - { - if (ItemHold.Enabled) - { - if (ItemHold.IsGumpTexture) - { - return (ushort)(ItemHold.DisplayedGraphic - Constants.ITEM_GUMP_TEXTURE_OFFSET); - } - - return ItemHold.DisplayedGraphic; - } - - return 0xFFFF; - } - - private Point GetDraggingItemOffset() - { - ushort graphic = GetDraggingItemGraphic(); - - if (graphic != 0xFFFF) - { - ref readonly var artInfo = ref Client.Game.Arts.GetArt(graphic); - - float scale = 1; - - if ( - ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.ScaleItemsInsideContainers - ) - { - scale = UIManager.ContainerScale; - } - - return new Point( - (int)((artInfo.UV.Width >> 1) * scale) - ItemHold.MouseOffset.X, - (int)((artInfo.UV.Height >> 1) * scale) - ItemHold.MouseOffset.Y - ); - } - - return Point.Zero; - } - - public void Update() - { - Graphic = AssignGraphicByState(); - - if (_needGraphicUpdate) - { - _needGraphicUpdate = false; - - if (AllowDrawSDLCursor && Settings.GlobalSettings.RunMouseInASeparateThread) - { - ushort id = Graphic; - - if (id < 0x206A) - { - id -= 0x2053; - } - else - { - id -= 0x206A; - } - - int war = - World.InGame && World.Player.InWarMode - ? 1 - : World.InGame && World.MapIndex != 0 - ? 2 - : 0; - - ref IntPtr ptrCursor = ref _cursors_ptr[war, id]; - - if (ptrCursor != IntPtr.Zero) - { - SDL.SDL_SetCursor(ptrCursor); - } - } - } - - if (ItemHold.Enabled) - { - ushort draggingGraphic = GetDraggingItemGraphic(); - - if (draggingGraphic != 0xFFFF && ItemHold.IsFixedPosition && !UIManager.IsDragging) - { - ref readonly var artInfo = ref Client.Game.Arts.GetArt(draggingGraphic); - - Point offset = GetDraggingItemOffset(); - - int x = ItemHold.FixedX - offset.X; - int y = ItemHold.FixedY - offset.Y; - - if ( - Mouse.Position.X >= x - && Mouse.Position.X < x + artInfo.UV.Width - && Mouse.Position.Y >= y - && Mouse.Position.Y < y + artInfo.UV.Height - ) - { - if (!ItemHold.IgnoreFixedPosition) - { - ItemHold.IsFixedPosition = false; - ItemHold.FixedX = 0; - ItemHold.FixedY = 0; - } - } - else if (ItemHold.IgnoreFixedPosition) - { - ItemHold.IgnoreFixedPosition = false; - } - } - } - } - - public void Draw(UltimaBatcher2D sb) - { - if (World.InGame && TargetManager.IsTargeting && ProfileManager.CurrentProfile != null) - { - if (TargetManager.TargetingState == CursorTarget.MultiPlacement) - { - if ( - World.CustomHouseManager != null - && World.CustomHouseManager.SelectedGraphic != 0 - ) - { - ushort hue = 0; - - Array.Clear(_componentsList, 0, 10); - - if ( - !World.CustomHouseManager.CanBuildHere( - _componentsList, - out CUSTOM_HOUSE_BUILD_TYPE type - ) - ) - { - hue = 0x0021; - } - - //if (_temp.Count != list.Count) - { - _temp.ForEach(s => s.Destroy()); - _temp.Clear(); - - for (int i = 0; i < _componentsList.Length; i++) - { - if (_componentsList[i].Graphic == 0) - { - break; - } - - Multi m = Multi.Create(_componentsList[i].Graphic); - - m.AlphaHue = 0xFF; - m.Hue = hue; - m.State = CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_PREVIEW; - _temp.Add(m); - } - } - - if (_componentsList.Length != 0) - { - if (SelectedObject.Object is GameObject selectedObj) - { - int z = 0; - - if (selectedObj.Z < World.CustomHouseManager.MinHouseZ) - { - if ( - selectedObj.X >= World.CustomHouseManager.StartPos.X - && selectedObj.X <= World.CustomHouseManager.EndPos.X - 1 - && selectedObj.Y >= World.CustomHouseManager.StartPos.Y - && selectedObj.Y <= World.CustomHouseManager.EndPos.Y - 1 - ) - { - if (type != CUSTOM_HOUSE_BUILD_TYPE.CHBT_STAIR) - { - z += 7; - } - } - } - - for (int i = 0; i < _componentsList.Length; i++) - { - ref readonly CustomBuildObject item = ref _componentsList[i]; - - if (item.Graphic == 0) - { - break; - } - - _temp[i].SetInWorldTile( - (ushort)(selectedObj.X + item.X), - (ushort)(selectedObj.Y + item.Y), - (sbyte)(selectedObj.Z + z + item.Z) - ); - } - } - } - } - else if (_temp.Count != 0) - { - _temp.ForEach(s => s.Destroy()); - _temp.Clear(); - } - } - else if (_temp.Count != 0) - { - _temp.ForEach(s => s.Destroy()); - _temp.Clear(); - } - - if (ProfileManager.CurrentProfile.AuraOnMouse) - { - ushort id = Graphic; - - if (id < 0x206A) - { - id -= 0x2053; - } - else - { - id -= 0x206A; - } - - ushort hue = 0; - - switch (TargetManager.TargetingType) - { - case TargetType.Neutral: - hue = 0x03b2; - - break; - - case TargetType.Harmful: - hue = 0x0023; - - break; - - case TargetType.Beneficial: - hue = 0x005A; - - break; - } - - _aura.Draw(sb, Mouse.Position.X, Mouse.Position.Y, hue, 0f); - } - - if (ProfileManager.CurrentProfile.ShowTargetRangeIndicator) - { - if (UIManager.IsMouseOverWorld) - { - if (SelectedObject.Object is GameObject obj) - { - string dist = obj.Distance.ToString(); - - Vector3 hue = new Vector3(0, 1, 1f); - sb.DrawString( - Fonts.Bold, - dist, - Mouse.Position.X - 26, - Mouse.Position.Y - 21, - hue - ); - - hue.Y = 0; - sb.DrawString( - Fonts.Bold, - dist, - Mouse.Position.X - 25, - Mouse.Position.Y - 20, - hue - ); - } - } - } - } - else if (_temp.Count != 0) - { - _temp.ForEach(s => s.Destroy()); - _temp.Clear(); - } - - if (ItemHold.Enabled && !ItemHold.Dropped) - { - float scale = 1; - - if ( - ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.ScaleItemsInsideContainers - ) - { - scale = UIManager.ContainerScale; - } - - ushort draggingGraphic = GetDraggingItemGraphic(); - - ref readonly var artInfo = ref Client.Game.Arts.GetArt(draggingGraphic); - - if (artInfo.Texture != null) - { - Point offset = GetDraggingItemOffset(); - - int x = - (ItemHold.IsFixedPosition ? ItemHold.FixedX : Mouse.Position.X) - offset.X; - int y = - (ItemHold.IsFixedPosition ? ItemHold.FixedY : Mouse.Position.Y) - offset.Y; - - Vector3 hue = ShaderHueTranslator.GetHueVector( - ItemHold.Hue, - ItemHold.IsPartialHue, - ItemHold.HasAlpha ? .5f : 1f - ); - - var rect = new Rectangle( - x, - y, - (int)(artInfo.UV.Width * scale), - (int)(artInfo.UV.Height * scale) - ); - - sb.Draw(artInfo.Texture, rect, artInfo.UV, hue); - - if ( - ItemHold.Amount > 1 - && ItemHold.DisplayedGraphic == ItemHold.Graphic - && ItemHold.IsStackable - ) - { - rect.X += 5; - rect.Y += 5; - - sb.Draw(artInfo.Texture, rect, artInfo.UV, hue); - } - } - } - - DrawToolTip(sb, Mouse.Position); - - if (!Settings.GlobalSettings.RunMouseInASeparateThread) - { - Graphic = AssignGraphicByState(); - - ushort graphic = Graphic; - - if (graphic < 0x206A) - { - graphic -= 0x2053; - } - else - { - graphic -= 0x206A; - } - - int offX = _cursorOffset[0, graphic]; - int offY = _cursorOffset[1, graphic]; - - Vector3 hueVec; - - if (World.InGame && World.MapIndex != 0 && !World.Player.InWarMode) - { - hueVec = ShaderHueTranslator.GetHueVector(0x0033); - } - else - { - hueVec = ShaderHueTranslator.GetHueVector(0); - } - - ref readonly var artInfo = ref Client.Game.Arts.GetArt(Graphic); - - var rect = artInfo.UV; - - const int BORDER_SIZE = 1; - rect.X += BORDER_SIZE; - rect.Y += BORDER_SIZE; - rect.Width -= BORDER_SIZE * 2; - rect.Height -= BORDER_SIZE * 2; - - sb.Draw( - artInfo.Texture, - new Vector2(Mouse.Position.X - offX, Mouse.Position.Y - offY), - rect, - hueVec - ); - } - } - - private void DrawToolTip(UltimaBatcher2D batcher, Point position) - { - if (Client.Game.Scene is GameScene gs) - { - if ( - !World.ClientFeatures.TooltipsEnabled - || ( - SelectedObject.Object is Item selectedItem - && selectedItem.IsLocked - && selectedItem.ItemData.Weight == 255 - && !selectedItem.ItemData.IsContainer - && - // We need to check if OPL contains data. - // If not we can ignore tooltip. - !World.OPL.Contains(selectedItem) - ) - || (ItemHold.Enabled && !ItemHold.IsFixedPosition) - ) - { - if ( - !_tooltip.IsEmpty - && (UIManager.MouseOverControl == null || UIManager.IsMouseOverWorld) - ) - { - _tooltip.Clear(); - } - } - else - { - if ( - UIManager.IsMouseOverWorld - && SelectedObject.Object is Entity item - && World.OPL.Contains(item) - ) - { - if (_tooltip.IsEmpty || item != _tooltip.Serial) - { - _tooltip.SetGameObject(item); - } - - _tooltip.Draw(batcher, position.X, position.Y + 24); - - return; - } - - if ( - UIManager.MouseOverControl != null - && UIManager.MouseOverControl.Tooltip is uint serial - ) - { - if (SerialHelper.IsValid(serial) && World.OPL.Contains(serial)) - { - if (_tooltip.IsEmpty || serial != _tooltip.Serial) - { - _tooltip.SetGameObject(serial); - } - - _tooltip.Draw(batcher, position.X, position.Y + 24); - - return; - } - } - } - } - - if ( - UIManager.MouseOverControl != null - && UIManager.MouseOverControl.HasTooltip - && !Mouse.IsDragging - ) - { - if (UIManager.MouseOverControl.Tooltip is string text) - { - if (_tooltip.IsEmpty || _tooltip.Text != text) - { - _tooltip.SetText(text, UIManager.MouseOverControl.TooltipMaxLength); - } - - _tooltip.Draw(batcher, position.X, position.Y + 24); - } - } - else if (!_tooltip.IsEmpty) - { - _tooltip.Clear(); - } - } - - private ushort AssignGraphicByState() - { - int war = World.InGame && World.Player.InWarMode ? 1 : 0; - - if (TargetManager.IsTargeting) - { - return _cursorData[war, 12]; - } - - if (UIManager.IsDragging || IsDraggingCursorForced) - { - return _cursorData[war, 8]; - } - - if (IsLoading) - { - return _cursorData[war, 13]; - } - - if ( - UIManager.MouseOverControl != null - && UIManager.MouseOverControl.AcceptKeyboardInput - && UIManager.MouseOverControl.IsEditable - ) - { - return _cursorData[war, 14]; - } - - ushort result = _cursorData[war, 9]; - - if (!UIManager.IsMouseOverWorld) - { - return result; - } - - if (ProfileManager.CurrentProfile == null) - { - return result; - } - - var camera = Client.Game.Scene.Camera; - - int windowCenterX = camera.Bounds.X + (camera.Bounds.Width >> 1); - int windowCenterY = camera.Bounds.Y + (camera.Bounds.Height >> 1); - - return _cursorData[ - war, - GetMouseDirection( - windowCenterX, - windowCenterY, - Mouse.Position.X, - Mouse.Position.Y, - 1 - ) - ]; - } - - public static int GetMouseDirection(int x1, int y1, int to_x, int to_y, int current_facing) - { - int shiftX = to_x - x1; - int shiftY = to_y - y1; - int hashf = 100 * (Sgn(shiftX) + 2) + 10 * (Sgn(shiftY) + 2); - - if (shiftX != 0 && shiftY != 0) - { - shiftX = Math.Abs(shiftX); - shiftY = Math.Abs(shiftY); - - if (shiftY * 5 <= shiftX * 2) - { - hashf = hashf + 1; - } - else if (shiftY * 2 >= shiftX * 5) - { - hashf = hashf + 3; - } - else - { - hashf = hashf + 2; - } - } - else if (shiftX == 0) - { - if (shiftY == 0) - { - return current_facing; - } - } - - switch (hashf) - { - case 111: - return (int)Direction.West; // W - - case 112: - return (int)Direction.Up; // NW - - case 113: - return (int)Direction.North; // N - - case 120: - return (int)Direction.West; // W - - case 131: - return (int)Direction.West; // W - - case 132: - return (int)Direction.Left; // SW - - case 133: - return (int)Direction.South; // S - - case 210: - return (int)Direction.North; // N - - case 230: - return (int)Direction.South; // S - - case 311: - return (int)Direction.East; // E - - case 312: - return (int)Direction.Right; // NE - - case 313: - return (int)Direction.North; // N - - case 320: - return (int)Direction.East; // E - - case 331: - return (int)Direction.East; // E - - case 332: - return (int)Direction.Down; // SE - - case 333: - return (int)Direction.South; // S - } - - return current_facing; - } - - private static int Sgn(int val) - { - int a = 0 < val ? 1 : 0; - int b = val < 0 ? 1 : 0; - - return a - b; - } - - private readonly struct CursorInfo - { - public CursorInfo(IntPtr ptr, int w, int h) - { - CursorPtr = ptr; - Width = w; - Height = h; - } - - public readonly int Width, - Height; - public readonly IntPtr CursorPtr; - } - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/DragEffect.cs b/src/ClassicUO.Client/Game/GameObjects/DragEffect.cs deleted file mode 100644 index 0c6944fbf..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/DragEffect.cs +++ /dev/null @@ -1,151 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.GameObjects -{ - internal class DragEffect : GameEffect - { - private uint _lastMoveTime; - - public DragEffect - ( - EffectManager manager, - uint src, - uint trg, - ushort xSource, - ushort ySource, - sbyte zSource, - ushort xTarget, - ushort yTarget, - sbyte zTarget, - ushort graphic, - ushort hue, - int duration, - byte speed - ) - : base(manager, graphic, hue, duration, speed) - { - Entity source = World.Get(src); - - if (SerialHelper.IsValid(src) && source != null) - { - SetSource(source); - } - else - { - SetSource(xSource, ySource, zSource); - } - - - Entity target = World.Get(trg); - - if (SerialHelper.IsValid(trg) && target != null) - { - SetTarget(target); - } - else - { - SetTarget(xTarget, yTarget, zTarget); - } - - Hue = hue; - Graphic = graphic; - } - - public override void Update() - { - if (_lastMoveTime > Time.Ticks) - { - return; - } - - Offset.X += 8; - Offset.Y += 8; - - _lastMoveTime = Time.Ticks + 20; - - base.Update(); - } - - public override bool Draw(UltimaBatcher2D batcher, int posX, int posY, float depth) - { - if (IsDestroyed) - { - return false; - } - - ushort hue; - if (ProfileManager.CurrentProfile.NoColorObjectsOutOfRange && Distance > World.ClientViewRange) - { - hue = Constants.OUT_RANGE_COLOR; - } - else if (World.Player.IsDead && ProfileManager.CurrentProfile.EnableBlackWhiteEffect) - { - hue = Constants.DEAD_RANGE_COLOR; - } - else - { - hue = Hue; - } - - Vector3 hueVec = ShaderHueTranslator.GetHueVector(hue); - - //Engine.DebugInfo.EffectsRendered++; - - DrawStatic - ( - batcher, - AnimationGraphic, - posX - ((int) Offset.X + 22), - posY - ((int) -Offset.Y + 22), - hueVec, - depth - ); - - ref StaticTiles data = ref TileDataLoader.Instance.StaticData[Graphic]; - - if (data.IsLight && Source != null) - { - Client.Game.GetScene().AddLight(Source, Source, posX + 22, posY + 22); - } - - return true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/GameObjects/Entity.cs b/src/ClassicUO.Client/Game/GameObjects/Entity.cs deleted file mode 100644 index bb0a64e4e..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/Entity.cs +++ /dev/null @@ -1,342 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Runtime.CompilerServices; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Network; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using static ClassicUO.Network.NetClient; - -namespace ClassicUO.Game.GameObjects -{ - public enum HitsRequestStatus - { - None, - Pending, - Received - } - - public abstract class Entity : GameObject, IEquatable - { - private static readonly RenderedText[] _hitsPercText = new RenderedText[101]; - private Direction _direction; - - - protected Entity(uint serial) - { - Serial = serial; - } - - public byte AnimIndex; - public bool ExecuteAnimation = true; - internal long LastAnimationChangeTime; - public Flags Flags; - public ushort Hits { get => hits; set - { - if(this is PlayerMobile) - { - var arg = new PlayerStatChangedArgs(PlayerStatChangedArgs.PlayerStat.Hits, hits, value); - hits = value; - EventSink.InvokeOnPlayerStatChange(this, arg); - } - else - { - hits = value; - } - } - } - public ushort HitsMax; - public byte HitsPercentage; - public bool IsClicked; - public uint LastStepTime; - public string Name; - public uint Serial; - public HitsRequestStatus HitsRequest; - private ushort hits; - - public bool IsHidden => (Flags & Flags.Hidden) != 0; - - public Direction Direction - { - get => _direction; - set - { - if (_direction != value) - { - _direction = value; - OnDirectionChanged(); - } - } - } - - public bool Exists => World.Contains(Serial); - - public RenderedText HitsTexture => _hitsPercText[HitsPercentage % _hitsPercText.Length]; - - - public bool Equals(Entity e) - { - return e != null && Serial == e.Serial; - } - - public void FixHue(ushort hue) - { - ushort fixedColor = (ushort) (hue & 0x3FFF); - - if (fixedColor != 0) - { - if (fixedColor >= 0x0BB8) - { - fixedColor = 1; - } - - fixedColor |= (ushort) (hue & 0xC000); - } - else - { - fixedColor = (ushort) (hue & 0x8000); - } - - Hue = fixedColor; - } - - public void UpdateHits(byte perc) - { - if (perc != HitsPercentage) - { - HitsPercentage = perc; - - ref var rtext = ref _hitsPercText[perc % _hitsPercText.Length]; - - if (rtext == null || rtext.IsDestroyed) - { - ushort color = 0x0044; - - if (perc < 30) - { - color = 0x0021; - } - else if (perc < 50) - { - color = 0x0030; - } - else if (perc < 80) - { - color = 0x0058; - } - - rtext = RenderedText.Create($"[{perc}%]", color, 3, false); - } - } - } - - public virtual void CheckGraphicChange(byte animIndex = 0) - { - } - - public override void Update() - { - base.Update(); - - if (ObjectHandlesStatus == ObjectHandlesStatus.OPEN) - { - ObjectHandlesStatus = ObjectHandlesStatus.DISPLAYING; - - // TODO: Some servers may not want to receive this (causing original client to not send it), - //but all servers tested (latest POL, old POL, ServUO, Outlands) do. - if ( /*Client.Version > ClientVersion.CV_200 &&*/ SerialHelper.IsMobile(Serial)) - { - Socket.Send_NameRequest(Serial); - } - - UIManager.Add(new NameOverheadGump(this)); - } - - - if (HitsMax > 0) - { - var perc = MathHelper.PercetangeOf(Hits, HitsMax); - perc = perc > 100 ? 100 : perc < 0 ? 0 : perc; - - UpdateHits((byte)perc); - } - } - - public override void Destroy() - { - base.Destroy(); - - GameActions.SendCloseStatus(Serial, HitsRequest >= HitsRequestStatus.Pending); - - AnimIndex = 0; - LastAnimationChangeTime = 0; - } - - public Item FindItem(ushort graphic, ushort hue = 0xFFFF) - { - Item item = null; - - if (hue == 0xFFFF) - { - int minColor = 0xFFFF; - - for (LinkedObject i = Items; i != null; i = i.Next) - { - Item it = (Item) i; - - if (it.Graphic == graphic) - { - if (it.Hue < minColor) - { - item = it; - minColor = it.Hue; - } - } - - if (SerialHelper.IsValid(it.Container)) - { - Item found = it.FindItem(graphic, hue); - - if (found != null && found.Hue < minColor) - { - item = found; - minColor = found.Hue; - } - } - } - } - else - { - for (LinkedObject i = Items; i != null; i = i.Next) - { - Item it = (Item) i; - - if (it.Graphic == graphic && it.Hue == hue) - { - item = it; - } - - if (SerialHelper.IsValid(it.Container)) - { - Item found = it.FindItem(graphic, hue); - - if (found != null) - { - item = found; - } - } - } - } - - return item; - } - - public Item GetItemByGraphic(ushort graphic, bool deepsearch = false) - { - for (LinkedObject i = Items; i != null; i = i.Next) - { - Item item = (Item) i; - - if (item.Graphic == graphic) - { - return item; - } - - if (deepsearch && !item.IsEmpty) - { - for (LinkedObject ic = Items; ic != null; ic = ic.Next) - { - Item childItem = (Item) ic; - - Item res = childItem.GetItemByGraphic(graphic, deepsearch); - - if (res != null) - { - return res; - } - } - } - } - - return null; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Item FindItemByLayer(Layer layer) - { - for (LinkedObject i = Items; i != null; i = i.Next) - { - Item it = (Item) i; - - if (!it.IsDestroyed && it.Layer == layer) - { - return it; - } - } - - return null; - } - - public static implicit operator uint(Entity entity) - { - return entity.Serial; - } - - public static bool operator ==(Entity e, Entity s) - { - return Equals(e, s); - } - - public static bool operator !=(Entity e, Entity s) - { - return !Equals(e, s); - } - - public override bool Equals(object obj) - { - return obj is Entity ent && Equals(ent); - } - - public override int GetHashCode() - { - return (int) Serial; - } - - public abstract void ProcessAnimation(bool evalutate = false); - - public abstract ushort GetGraphicForAnimation(); - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/GameObjects/EntityCollection.cs b/src/ClassicUO.Client/Game/GameObjects/EntityCollection.cs deleted file mode 100644 index 458854160..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/EntityCollection.cs +++ /dev/null @@ -1,64 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections; -using System.Collections.Generic; - -namespace ClassicUO.Game.GameObjects -{ - static class DictExt - { - public static T Get(this Dictionary dict, uint serial) where T : Entity - { - dict.TryGetValue(serial, out var v); - - return v; - } - - public static bool Contains(this Dictionary dict, uint serial) where T : Entity - { - return dict.ContainsKey(serial); - } - - public static bool Add(this Dictionary dict, T entity) where T : Entity - { - if (dict.ContainsKey(entity.Serial)) - { - return false; - } - - dict[entity.Serial] = entity; - - return true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/GameObjects/EntityTextContainer.cs b/src/ClassicUO.Client/Game/GameObjects/EntityTextContainer.cs deleted file mode 100644 index 694fea242..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/EntityTextContainer.cs +++ /dev/null @@ -1,284 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Renderer; -using ClassicUO.Utility.Collections; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.GameObjects -{ - public class TextContainer : LinkedObject - { - public int Size, - MaxSize = 5; - - public void Add(TextObject obj) - { - PushToBack(obj); - - if (Size >= MaxSize) - { - ((TextObject)Items)?.Destroy(); - Remove(Items); - } - else - { - Size++; - } - } - - public new void Clear() - { - TextObject item = (TextObject)Items; - Items = null; - - while (item != null) - { - TextObject next = (TextObject)item.Next; - item.Next = null; - item.Destroy(); - Remove(item); - - item = next; - } - - Size = 0; - } - } - - internal class OverheadDamage - { - private const int DAMAGE_Y_MOVING_TIME = 25; - - private readonly Deque _messages; - - private Rectangle _rectangle; - - public OverheadDamage(GameObject parent) - { - Parent = parent; - _messages = new Deque(); - } - - public GameObject Parent { get; private set; } - public bool IsDestroyed { get; private set; } - public bool IsEmpty => _messages.Count == 0; - - public void SetParent(GameObject parent) - { - Parent = parent; - } - - public void Add(int damage) - { - TextObject text_obj = TextObject.Create(); - - ushort hue = ProfileManager.CurrentProfile == null ? (ushort)0x0021 : ProfileManager.CurrentProfile.DamageHueOther; - - if (ReferenceEquals(Parent, World.Player)) - hue = ProfileManager.CurrentProfile == null ? (ushort)0x0034 : ProfileManager.CurrentProfile.DamageHueSelf; - else if (Parent is Mobile) - { - Mobile _parent = (Mobile)Parent; - if (_parent.IsRenamable && _parent.NotorietyFlag != NotorietyFlag.Invulnerable && _parent.NotorietyFlag != NotorietyFlag.Enemy) - hue = ProfileManager.CurrentProfile == null ? (ushort)0x0033 : ProfileManager.CurrentProfile.DamageHuePet; - else if (_parent.NotorietyFlag == NotorietyFlag.Ally) - hue = ProfileManager.CurrentProfile == null ? (ushort)0x0030 : ProfileManager.CurrentProfile.DamageHueAlly; - - if (_parent.Serial == TargetManager.LastAttack) - hue = ProfileManager.CurrentProfile == null ? (ushort)0x1F : ProfileManager.CurrentProfile.DamageHueLastAttck; - } - - text_obj.TextBox = new UI.Controls.TextBox(damage.ToString(), ProfileManager.CurrentProfile.OverheadChatFont, ProfileManager.CurrentProfile.OverheadChatFontSize, ProfileManager.CurrentProfile.OverheadChatWidth, hue, align: FontStashSharp.RichText.TextHorizontalAlignment.Center) { AcceptMouseInput = !ProfileManager.CurrentProfile.DisableMouseInteractionOverheadText }; - - text_obj.Time = Time.Ticks + 1500; - - _messages.AddToFront(text_obj); - - if (_messages.Count > 10) - { - _messages.RemoveFromBack()?.Destroy(); - } - } - - public void Update() - { - if (IsDestroyed) - { - return; - } - - _rectangle.Width = 0; - - for (int i = 0; i < _messages.Count; i++) - { - TextObject c = _messages[i]; - - float delta = c.Time - Time.Ticks; - - if (c.SecondTime < Time.Ticks) - { - c.OffsetY += 1; - c.SecondTime = Time.Ticks + DAMAGE_Y_MOVING_TIME; - } - - if (delta <= 0) - { - _rectangle.Height -= c.TextBox?.Height ?? 0; - c.Destroy(); - _messages.RemoveAt(i--); - } - //else if (delta < 250) - // c.Alpha = 1f - delta / 250; - else if (c.TextBox != null) - { - if (_rectangle.Width < c.TextBox.Width) - { - _rectangle.Width = c.TextBox.Width; - } - } - } - } - - public void Draw(UltimaBatcher2D batcher) - { - if (IsDestroyed || _messages.Count == 0) - { - return; - } - - int offY = 0; - - Point p = new Point(); - - if (Parent != null) - { - p.X += Parent.RealScreenPosition.X; - p.Y += Parent.RealScreenPosition.Y; - - _rectangle.X = Parent.RealScreenPosition.X; - _rectangle.Y = Parent.RealScreenPosition.Y; - - if (Parent is Mobile m) - { - if (m.IsGargoyle && m.IsFlying) - { - offY += 22; - } - else if (!m.IsMounted) - { - offY = -22; - } - - Client.Game.Animations.GetAnimationDimensions( - m.AnimIndex, - m.GetGraphicForAnimation(), - /*(byte) m.GetDirectionForAnimation()*/ - 0, - /*Mobile.GetGroupForAnimation(m, isParent:true)*/ - 0, - m.IsMounted, - /*(byte) m.AnimIndex*/ - 0, - out int centerX, - out int centerY, - out int width, - out int height - ); - - p.X += (int)m.Offset.X + 22; - p.Y += (int)(m.Offset.Y - m.Offset.Z - (height + centerY + 8)); - } - else - { - ref readonly var artInfo = ref Client.Game.Arts.GetArt(Parent.Graphic); - - if (artInfo.Texture != null) - { - p.X += 22; - int yValue = artInfo.UV.Height >> 1; - - if (Parent is Item it) - { - if (it.IsCorpse) - { - offY = -22; - } - } - else if (Parent is Static || Parent is Multi) - { - offY = -44; - } - - p.Y -= yValue; - } - } - } - - p = Client.Game.Scene.Camera.WorldToScreen(p); - - foreach (TextObject item in _messages) - { - if (item.IsDestroyed || item.TextBox == null || item.TextBox.IsDisposed) - { - continue; - } - - item.X = p.X - (item.TextBox.Width >> 1); - item.Y = p.Y - offY - item.TextBox.Height - item.OffsetY; - item.TextBox.Draw(batcher, item.X, item.Y); - offY += item.TextBox.Height; - } - } - - public void Destroy() - { - if (IsDestroyed) - { - return; - } - - IsDestroyed = true; - - foreach (TextObject item in _messages) - { - item.Destroy(); - } - - _messages.Clear(); - } - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/FixedEffect.cs b/src/ClassicUO.Client/Game/GameObjects/FixedEffect.cs deleted file mode 100644 index 57a7f7a75..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/FixedEffect.cs +++ /dev/null @@ -1,106 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Managers; -using ClassicUO.Utility; - -namespace ClassicUO.Game.GameObjects -{ - internal sealed class FixedEffect : GameEffect - { - public FixedEffect(EffectManager manager, ushort graphic, ushort hue, int duration, byte speed) - : base(manager, graphic, hue, duration, speed) - { - - } - - public FixedEffect - ( - EffectManager manager, - ushort sourceX, - ushort sourceY, - sbyte sourceZ, - ushort graphic, - ushort hue, - int duration, - byte speed - ) : this(manager, graphic, hue, duration, speed) - { - SetSource(sourceX, sourceY, sourceZ); - } - - public FixedEffect - ( - EffectManager manager, - uint sourceSerial, - ushort sourceX, - ushort sourceY, - sbyte sourceZ, - ushort graphic, - ushort hue, - int duration, - byte speed - ) : this(manager, graphic, hue, duration, speed) - { - Entity source = World.Get(sourceSerial); - - if (source != null && SerialHelper.IsValid(sourceSerial)) - { - SetSource(source); - } - else - { - SetSource(sourceX, sourceY, sourceZ); - } - } - - public override void Update() - { - base.Update(); - - if (!IsDestroyed) - { - (var x, var y, var z) = GetSource(); - - if (Source != null) - { - Offset = Source.Offset; - } - - if (X != x || Y != y || Z != z) - { - SetInWorldTile(x, y, z); - } - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/GameObjects/GameEffect.cs b/src/ClassicUO.Client/Game/GameObjects/GameEffect.cs deleted file mode 100644 index e44deac31..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/GameEffect.cs +++ /dev/null @@ -1,219 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Assets; -using ClassicUO.Utility; - -namespace ClassicUO.Game.GameObjects -{ - internal abstract partial class GameEffect : GameObject - { - private readonly EffectManager _manager; - - protected GameEffect(EffectManager manager, ushort graphic, ushort hue, int duration, byte speed) - { - _manager = manager; - - Graphic = graphic; - Hue = hue; - AllowedToDraw = CanBeDrawn(graphic); - AlphaHue = 0xFF; - AnimDataFrame = AnimDataLoader.Instance?.CalculateCurrentGraphic(graphic) ?? default; - IsEnabled = true; - AnimIndex = 0; - - - speed *= 10; - - if (speed == 0) - { - speed = Constants.ITEM_EFFECT_ANIMATION_DELAY; - } - - if (AnimDataFrame.FrameInterval == 0) - { - IntervalInMs = speed; - - // NOTE: - // tested on outlands with arrows & bolts - // server sends duration = 50 , a very small amount of time so the arrow will be destroyed suddenly - // im not sure if this is the right fix, but keep it atm - - // NOTE 2: - // this fix causes issue with other effects. It makes perma effects. So bad - //duration = -1; - } - else - { - IntervalInMs = (uint)(AnimDataFrame.FrameInterval * speed); - } - - Duration = duration > 0 ? Time.Ticks + duration : -1; - } - - public bool IsMoving => Target != null || TargetX != 0 && TargetY != 0; - - public bool CanCreateExplosionEffect; - public ushort AnimationGraphic = 0xFFFF; - public AnimDataFrame AnimDataFrame; - public byte AnimIndex; - public float AngleToTarget; - public GraphicEffectBlendMode Blend; - public long Duration = -1; - public uint IntervalInMs; - public bool IsEnabled; - public long NextChangeFrameTime; - public GameObject Source; - protected GameObject Target; - protected ushort TargetX; - protected ushort TargetY; - protected sbyte TargetZ; - - - public override void Update() - { - base.Update(); - - - if (Source != null && Source.IsDestroyed) - { - Destroy(); - - return; - } - - if (IsDestroyed) - { - return; - } - - if (IsEnabled) - { - if (Duration < Time.Ticks && Duration >= 0) - { - Destroy(); - } - else if (NextChangeFrameTime < Time.Ticks) - { - if (AnimDataFrame.FrameCount != 0) - { - unsafe - { - AnimationGraphic = (ushort) (Graphic + AnimDataFrame.FrameData[AnimIndex]); - } - - AnimIndex++; - - if (AnimIndex >= AnimDataFrame.FrameCount) - { - AnimIndex = 0; - } - } - else - { - AnimationGraphic = Graphic; - } - - NextChangeFrameTime = (long)Time.Ticks + IntervalInMs; - } - } - else - { - AnimationGraphic = Graphic; - } - } - - protected (ushort x, ushort y, sbyte z) GetSource() - { - return Source == null ? (X, Y, Z) : (Source.X, Source.Y, Source.Z); - } - - protected void CreateExplosionEffect() - { - if (CanCreateExplosionEffect) - { - (var targetX, var targetY, var targetZ) = GetTarget(); - - FixedEffect effect = new FixedEffect(_manager, 0x36CB, Hue, 400, 0); - effect.Blend = Blend; - effect.SetSource(targetX, targetY, targetZ); - - _manager.PushToBack(effect); - } - } - - public void SetSource(GameObject source) - { - Source = source; - SetInWorldTile(source.X, source.Y, source.Z); - } - - public void SetSource(ushort x, ushort y, sbyte z) - { - Source = null; - - SetInWorldTile(x, y,z); - } - - protected (ushort x, ushort y, sbyte z) GetTarget() - { - return Target == null ? (TargetX, TargetY, TargetZ) : (Target.X, Target.Y, Target.Z); - } - - public void SetTarget(GameObject target) - { - Target = target; - } - - public void SetTarget(ushort x, ushort y, sbyte z) - { - Target = null; - TargetX = x; - TargetY = y; - TargetZ = z; - } - - public override void Destroy() - { - _manager?.Remove(this); - - AnimIndex = 0; - Source = null; - Target = null; - base.Destroy(); - } - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/GameObject.cs b/src/ClassicUO.Client/Game/GameObjects/GameObject.cs deleted file mode 100644 index e1244d54d..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/GameObject.cs +++ /dev/null @@ -1,442 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Runtime.CompilerServices; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Map; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.GameObjects -{ - public abstract class BaseGameObject : LinkedObject - { - public Point RealScreenPosition; - } - - public abstract partial class GameObject : BaseGameObject - { - public bool IsDestroyed { get; protected set; } - public bool IsPositionChanged { get; protected set; } - public TextContainer TextContainer { get; private set; } - - public int Distance - { - get - { - if ( - World.Player == null /*|| IsDestroyed*/ - ) - { - return ushort.MaxValue; - } - - if (ReferenceEquals(this, World.Player)) - { - return 0; - } - - int x = X, - y = Y; - - if (this is Mobile mobile && mobile.Steps.Count != 0) - { - ref Mobile.Step step = ref mobile.Steps.Back(); - x = step.X; - y = step.Y; - } - - int fx = World.RangeSize.X; - int fy = World.RangeSize.Y; - - return Math.Max(Math.Abs(x - fx), Math.Abs(y - fy)); - } - } - - public virtual void Update() { } - - public abstract bool CheckMouseSelection(); - - // FIXME: remove it - public sbyte FoliageIndex = -1; - public ushort Graphic; - public ushort Hue; - public Vector3 Offset; - public short PriorityZ; - public GameObject TNext; - public GameObject TPrevious; - public ushort X, - Y; - public sbyte Z; - public GameObject RenderListNext; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Vector2 GetScreenPosition() - { - return new Vector2( - RealScreenPosition.X + Offset.X, - RealScreenPosition.Y + (Offset.Y - Offset.Z) - ); - } - - public int DistanceFrom(Vector2 pos) - { - if (pos == null) { return int.MaxValue; } - - return Math.Max(Math.Abs(X - (int)pos.X), Math.Abs(Y - (int)pos.Y)); - } - - public void AddToTile() - { - AddToTile(X, Y); - } - - public void AddToTile(int x, int y) - { - AddToTile(World.Map?.GetChunk(x, y), x % 8, y % 8); - } - - public void AddToTile(Chunk chunk, int chunkX, int chunkY) - { - RemoveFromTile(); - - if (!IsDestroyed && chunk != null) - { - chunk.AddGameObject(this, chunkX, chunkY); - } - } - - public void RemoveFromTile() - { - if (TPrevious != null) - { - TPrevious.TNext = TNext; - } - - if (TNext != null) - { - TNext.TPrevious = TPrevious; - } - - TNext = null; - TPrevious = null; - } - - public virtual void UpdateGraphicBySeason() { } - - public void UpdateScreenPosition() - { - IsPositionChanged = true; - OnPositionChanged(); - } - - public void UpdateRealScreenPosition(int offsetX, int offsetY) - { - RealScreenPosition.X = ((X - Y) * 22) - offsetX - 22; - RealScreenPosition.Y = ((X + Y) * 22 - (Z << 2)) - offsetY - 22; - IsPositionChanged = false; - - UpdateTextCoordsV(); - } - - public void SetInWorldTile(ushort x, ushort y, sbyte z) - { - X = x; - Y = y; - Z = z; - UpdateScreenPosition(); - AddToTile(x, y); - } - - public void AddMessage(MessageType type, string message, TextType text_type) - { - AddMessage( - type, - message, - ProfileManager.CurrentProfile.ChatFont, - ProfileManager.CurrentProfile.SpeechHue, - true, - text_type - ); - } - - public virtual void UpdateTextCoordsV() - { - if (TextContainer == null) - { - return; - } - - TextObject last = (TextObject)TextContainer.Items; - - while (last?.Next != null) - { - last = (TextObject)last.Next; - } - - if (last == null) - { - return; - } - - int offY = 0; - - Point p = RealScreenPosition; - - var bounds = Client.Game.Arts.GetRealArtBounds(Graphic); - - p.Y -= bounds.Height >> 1; - - p.X += (int)Offset.X + 22; - p.Y += (int)(Offset.Y - Offset.Z) + 44; - - p = Client.Game.Scene.Camera.WorldToScreen(p); - - for (; last != null; last = (TextObject)last.Previous) - { - if (last.TextBox != null && !last.TextBox.IsDisposed) - { - if (offY == 0 && last.Time < Time.Ticks) - { - continue; - } - - last.OffsetY = offY; - offY += last.TextBox.Height; - - last.RealScreenPosition.X = p.X - (last.TextBox.Width >> 1); - last.RealScreenPosition.Y = p.Y - offY; - } - } - - FixTextCoordinatesInScreen(); - } - - protected void FixTextCoordinatesInScreen() - { - if (this is Item it && SerialHelper.IsValid(it.Container)) - { - return; - } - - int offsetY = 0; - - int minX = 6; - int maxX = minX + Client.Game.Scene.Camera.Bounds.Width - 6; - int minY = 0; - //int maxY = minY + ProfileManager.CurrentProfile.GameWindowSize.Y - 6; - - for ( - TextObject item = (TextObject)TextContainer.Items; - item != null; - item = (TextObject)item.Next - ) - { - if (item.TextBox == null || item.TextBox.IsDisposed || item.Time < Time.Ticks) - { - continue; - } - - int startX = item.RealScreenPosition.X; - int endX = startX + item.TextBox.Width; - - if (startX < minX) - { - item.RealScreenPosition.X += minX - startX; - } - - if (endX > maxX) - { - item.RealScreenPosition.X -= endX - maxX; - } - - int startY = item.RealScreenPosition.Y; - - if (startY < minY && offsetY == 0) - { - offsetY = minY - startY; - } - - //int endY = startY + item.RenderedText.Height; - - //if (endY > maxY) - // UseInRender = 0xFF; - // //item.RealScreenPosition.Y -= endY - maxY; - - if (offsetY != 0) - { - item.RealScreenPosition.Y += offsetY; - } - } - } - - public void AddMessage( - MessageType type, - string text, - byte font, - ushort hue, - bool isunicode, - TextType text_type - ) - { - if (string.IsNullOrEmpty(text)) - { - return; - } - - TextObject msg = MessageManager.CreateMessage( - text, - hue, - font, - isunicode, - type, - text_type - ); - - AddMessage(msg); - } - - public void AddMessage(TextObject msg) - { - if (TextContainer == null) - { - TextContainer = new TextContainer(); - } - - msg.Owner = this; - TextContainer.Add(msg); - - if (this is Item it && SerialHelper.IsValid(it.Container)) - { - UpdateTextCoordsV(); - } - else - { - IsPositionChanged = true; - World.WorldTextManager.AddMessage(msg); - } - } - - protected virtual void OnPositionChanged() { } - - protected virtual void OnDirectionChanged() { } - - public virtual void Destroy() - { - if (IsDestroyed) - { - return; - } - - Next = null; - Previous = null; - RenderListNext = null; - - Clear(); - RemoveFromTile(); - TextContainer?.Clear(); - - IsDestroyed = true; - PriorityZ = 0; - IsPositionChanged = false; - Hue = 0; - Offset = Vector3.Zero; - RealScreenPosition = Point.Zero; - IsFlipped = false; - Graphic = 0; - ObjectHandlesStatus = ObjectHandlesStatus.NONE; - FrameInfo = Rectangle.Empty; - } - - public static bool CanBeDrawn(ushort g) - { - switch (g) - { - case 0x0001: - case 0x21BC: - case 0xA1FE: - case 0xA1FF: - case 0xA200: - case 0xA201: - //case 0x5690: - return false; - - case 0x9E4C: - case 0x9E64: - case 0x9E65: - case 0x9E7D: - ref StaticTiles data = ref TileDataLoader.Instance.StaticData[g]; - - return !data.IsBackground && !data.IsSurface; - } - - if (g != 0x63D3) - { - if (g >= 0x2198 && g <= 0x21A4) - { - return false; - } - - // Easel fix. - // In older clients the tiledata flag for this - // item contains NoDiagonal for some reason. - // So the next check will make the item invisible. - if (g == 0x0F65 && Client.Version < ClientVersion.CV_60144) - { - return true; - } - - if (g < TileDataLoader.Instance?.StaticData?.Length) - { - ref StaticTiles data = ref TileDataLoader.Instance.StaticData[g]; - - if ( - !data.IsNoDiagonal - || data.IsAnimated - && World.Player != null - && World.Player.Race == RaceType.GARGOYLE - ) - { - return true; - } - } - } - - return false; - } - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/House.cs b/src/ClassicUO.Client/Game/GameObjects/House.cs deleted file mode 100644 index 7fa6d8d86..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/House.cs +++ /dev/null @@ -1,195 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Linq; -using ClassicUO.Game.Managers; -using ClassicUO.Utility.Collections; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.GameObjects -{ - public sealed class House : IEquatable - { - public House(uint serial, uint revision, bool isCustom) - { - Serial = serial; - Revision = revision; - IsCustom = isCustom; - } - - public uint Serial { get; } - public List Components { get; } = new List(); - - public Rectangle Bounds; - - public bool Equals(uint other) - { - return Serial == other; - } - - public bool IsCustom; - public uint Revision; - - public IEnumerable GetMultiAt(int x, int y) - { - return Components.Where(s => !s.IsDestroyed && s.X == x && s.Y == y); - } - - public Multi Add - ( - ushort graphic, - ushort hue, - ushort x, - ushort y, - sbyte z, - bool iscustom, - bool ismovable - ) - { - Multi m = Multi.Create(graphic); - m.Hue = hue; - m.IsCustom = iscustom; - m.IsMovable = ismovable; - - m.SetInWorldTile(x, y, z); - - Components.Add(m); - - return m; - } - - public void ClearCustomHouseComponents(CUSTOM_HOUSE_MULTI_OBJECT_FLAGS state) - { - Item item = World.Items.Get(Serial); - - if (item != null) - { - int checkZ = item.Z + 7; - - for (int i = 0; i < Components.Count; i++) - { - Multi component = Components[i]; - - component.State = component.State & ~(CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_TRANSPARENT | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_IGNORE_IN_RENDER | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_INCORRECT_PLACE); - - - if (component.IsCustom) - { - if (component.Z <= item.Z) - { - if ((component.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_STAIR) == 0) - { - component.State |= CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_DONT_REMOVE; - } - } - - if (state == 0 || (component.State & state) != 0) - { - component.Destroy(); - } - } - else if (component.Z <= checkZ) - { - component.State = component.State | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_IGNORE_IN_RENDER; - } - - if (component.IsDestroyed) - { - Components.RemoveAt(i--); - } - } - } - } - - public void Generate(bool recalculate = false, bool pushtotile = true, bool removePreview = false) - { - Item item = World.Items.Get(Serial); - //ClearCustomHouseComponents(0); - - foreach (Multi s in Components) - { - if (item != null) - { - if (recalculate) - { - s.SetInWorldTile((ushort)(item.X + s.MultiOffsetX), (ushort)(item.Y + s.MultiOffsetY), (sbyte)(item.Z + s.MultiOffsetZ)); - s.Offset = Vector3.Zero; - } - - - if (removePreview) - { - s.State &= ~CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_PREVIEW; - } - - s.Hue = item.Hue; - //s.State = CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE; - //s.IsCustom = IsCustom; - } - - if (!pushtotile) - { - s.RemoveFromTile(); - } - } - - World.CustomHouseManager?.GenerateFloorPlace(); - } - - public void ClearComponents(bool removeCustomOnly = false) - { - Item item = World.Items.Get(Serial); - - if (item != null && !item.IsDestroyed) - { - item.WantUpdateMulti = true; - } - - for (int i = 0; i < Components.Count; i++) - { - Multi s = Components[i]; - - if (!s.IsCustom && removeCustomOnly) - { - continue; - } - - s.Destroy(); - Components.RemoveAt(i--); - } - - //Components.Clear(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/GameObjects/IsometricLight.cs b/src/ClassicUO.Client/Game/GameObjects/IsometricLight.cs deleted file mode 100644 index b7951de62..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/IsometricLight.cs +++ /dev/null @@ -1,105 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.GameObjects -{ - public sealed class IsometricLight - { - private float _height = -0.75f; - private int _overall = 9, _realOveall = 9; - private int _personal = 9, _realPersonal = 9; - - public int Personal - { - get => _personal; - set - { - _personal = value; - Recalculate(); - } - } - - public int Overall - { - get => _overall; - set - { - _overall = value; - Recalculate(); - } - } - - public float Height - { - get => _height; - set - { - _height = value; - Recalculate(); - } - } - - public int RealPersonal - { - get => _realPersonal; - set - { - _realPersonal = value; - Recalculate(); - } - } - - public int RealOverall - { - get => _realOveall; - set - { - _realOveall = value; - Recalculate(); - } - } - - public float IsometricLevel { get; private set; } - - public Vector3 IsometricDirection { get; } = new Vector3(-1.0f, -1.0f, .5f); - - private void Recalculate() - { - int reverted = 32 - Overall; //if overall is 0, we have MAXIMUM light, if 30, we have the MINIMUM light, so 30 is the max, but we must have some remainder for visibility - - float current = Personal > reverted ? Personal : reverted; - IsometricLevel = current * 0.03125f; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/GameObjects/Item.cs b/src/ClassicUO.Client/Game/GameObjects/Item.cs deleted file mode 100644 index ce1637191..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/Item.cs +++ /dev/null @@ -1,783 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.IO; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using ClassicUO.Utility.Platforms; -using Microsoft.Xna.Framework; -using MathHelper = ClassicUO.Utility.MathHelper; - -namespace ClassicUO.Game.GameObjects -{ - public partial class Item : Entity - { - private static readonly QueuedPool _pool = new QueuedPool( - Constants.PREDICTABLE_CHUNKS * 3, - i => - { - i.IsDestroyed = false; - i.Graphic = 0; - i.Amount = 0; - i.Container = 0xFFFF_FFFF; - i._isMulti = false; - i.Layer = 0; - i.Price = 0; - i.UsedLayer = false; - i._displayedGraphic = null; - i.X = 0; - i.Y = 0; - i.Z = 0; - - i.LightID = 0; - i.MultiDistanceBonus = 0; - i.Flags = 0; - i.WantUpdateMulti = true; - i.MultiInfo = null; - i.MultiGraphic = 0; - - i.AlphaHue = 0; - i.Name = null; - i.Direction = 0; - i.AnimIndex = 0; - i.Hits = 0; - i.HitsMax = 0; - i.LastStepTime = 0; - i.LastAnimationChangeTime = 0; - - i.Clear(); - - i.IsClicked = false; - i.IsDamageable = false; - i.Offset = Vector3.Zero; - i.HitsPercentage = 0; - i.Opened = false; - i.TextContainer?.Clear(); - i.IsFlipped = false; - i.FrameInfo = Rectangle.Empty; - i.ObjectHandlesStatus = ObjectHandlesStatus.NONE; - i.AlphaHue = 0; - i.AllowedToDraw = true; - i.ExecuteAnimation = true; - i.HitsRequest = HitsRequestStatus.None; - } - ); - - private ushort? _displayedGraphic; - private bool _isMulti; - - public Item() : base(0) { } - - public bool IsCoin => Graphic == 0x0EEA || Graphic == 0x0EED || Graphic == 0x0EF0; - - public ushort DisplayedGraphic - { - get - { - if (_displayedGraphic.HasValue) - { - return _displayedGraphic.Value; - } - - if (IsCoin) - { - if (Amount > 5) - { - return (ushort)(Graphic + 2); - } - - if (Amount > 1) - { - return (ushort)(Graphic + 1); - } - } - else if (IsMulti) - { - return MultiGraphic; - } - - return Graphic; - } - set => _displayedGraphic = value; - } - - public bool IsLocked => (Flags & Flags.Movable) == 0 && ItemData.Weight > 90; - - public ushort MultiGraphic { get; private set; } - - public bool IsMulti - { - get => _isMulti; - set - { - _isMulti = value; - - if (!value) - { - MultiDistanceBonus = 0; - MultiInfo = null; - } - } - } - - public int MultiDistanceBonus { get; private set; } - - public bool IsCorpse => /*MathHelper.InRange(Graphic, 0x0ECA, 0x0ED2) ||*/ - Graphic == 0x2006; - - public bool IsHumanCorpse => IsCorpse && - MathHelper.InRange(Amount, 0x0190, 0x0193) || - MathHelper.InRange(Amount, 0x00B7, 0x00BA) || - MathHelper.InRange(Amount, 0x025D, 0x0260) || - MathHelper.InRange(Amount, 0x029A, 0x029B) || - MathHelper.InRange(Amount, 0x02B6, 0x02B7) || - Amount == 0x03DB || - Amount == 0x03DF || - Amount == 0x03E2 || - Amount == 0x02E8 || - Amount == 0x02E9; - - public bool OnGround => !SerialHelper.IsValid(Container); - - public uint RootContainer - { - get - { - Item item = this; - - while (SerialHelper.IsItem(item.Container)) - { - item = World.Items.Get(item.Container); - - if (item == null) - { - return 0; - } - } - - return SerialHelper.IsMobile(item.Container) ? item.Container : item; - } - } - - public ref StaticTiles ItemData => - ref TileDataLoader.Instance.StaticData[IsMulti ? MultiGraphic : Graphic]; - - public bool IsLootable => - ItemData.Layer != (int)Layer.Hair - && ItemData.Layer != (int)Layer.Beard - && ItemData.Layer != (int)Layer.Face - && Graphic != 0; - - public ushort Amount; - public uint Container = 0xFFFF_FFFF; - - public bool IsDamageable; - public Layer Layer; - public byte LightID; - - public Rectangle? MultiInfo; - public bool Opened; - - public uint Price; - public bool UsedLayer; - public bool WantUpdateMulti = true; - - public static Item Create(uint serial) - { - Item i = _pool.GetOne(); - i.Serial = serial; - - return i; - } - - public override void Destroy() - { - if (IsDestroyed) - { - return; - } - - if (Opened) - { - UIManager.GetGump(Serial)?.Dispose(); - #region GridContainer - UIManager.GetGump(Serial)?.Dispose(); - #endregion - UIManager.GetGump(Serial)?.Dispose(); - UIManager.GetGump(Serial)?.Dispose(); - - if (IsCorpse) - { - UIManager.GetGump(Serial)?.Dispose(); - } - - UIManager.GetGump(Serial)?.Dispose(); - UIManager.GetGump(Serial)?.Dispose(); - - Opened = false; - } - - base.Destroy(); - - _pool.ReturnOne(this); - } - - private unsafe void LoadMulti() - { - WantUpdateMulti = false; - - short minX = 0; - short minY = 0; - short maxX = 0; - short maxY = 0; - - if (!World.HouseManager.TryGetHouse(Serial, out House house)) - { - house = new House(Serial, 0, false); - World.HouseManager.Add(Serial, house); - } - else - { - house.ClearComponents(); - } - - ref UOFileIndex entry = ref MultiLoader.Instance.GetValidRefEntry(Graphic); - MultiLoader.Instance.File.SetData(entry.Address, entry.FileSize); - bool movable = false; - - if (MultiLoader.Instance.IsUOP) - { - if (entry.Length > 0 && entry.DecompressedLength > 0) - { - MultiLoader.Instance.File.Seek(entry.Offset); - - byte[] buffer = null; - Span span = - entry.DecompressedLength <= 1024 - ? stackalloc byte[entry.DecompressedLength] - : ( - buffer = System.Buffers.ArrayPool.Shared.Rent( - entry.DecompressedLength - ) - ); - - try - { - fixed (byte* dataPtr = span) - { - ZLib.Decompress( - MultiLoader.Instance.File.PositionAddress, - entry.Length, - 0, - (IntPtr)dataPtr, - entry.DecompressedLength - ); - - StackDataReader reader = new StackDataReader( - span.Slice(0, entry.DecompressedLength) - ); - reader.Skip(4); - - int count = reader.ReadInt32LE(); - - int sizeOf = sizeof(MultiBlockNew); - - for (int i = 0; i < count; i++) - { - MultiBlockNew* block = (MultiBlockNew*)( - reader.PositionAddress + i * sizeOf - ); - - if (block->Unknown != 0) - { - reader.Skip((int)(block->Unknown * 4)); - } - - if (block->X < minX) - { - minX = block->X; - } - - if (block->X > maxX) - { - maxX = block->X; - } - - if (block->Y < minY) - { - minY = block->Y; - } - - if (block->Y > maxY) - { - maxY = block->Y; - } - - if (block->Flags == 0 || block->Flags == 0x100) - { - Multi m = Multi.Create(block->ID); - m.MultiOffsetX = block->X; - m.MultiOffsetY = block->Y; - m.MultiOffsetZ = block->Z; - m.Hue = Hue; - m.AlphaHue = 255; - m.IsCustom = false; - m.State = CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_DONT_REMOVE; - m.IsMovable = ItemData.IsMultiMovable; - - m.SetInWorldTile( - (ushort)(X + block->X), - (ushort)(Y + block->Y), - (sbyte)(Z + block->Z) - ); - - house.Components.Add(m); - - if (m.ItemData.IsMultiMovable) - { - movable = true; - } - } - else if (i == 0) - { - MultiGraphic = block->ID; - } - } - - reader.Release(); - } - } - finally - { - if (buffer != null) - { - System.Buffers.ArrayPool.Shared.Return(buffer); - } - } - } - else - { - Log.Warn($"[MultiCollection.uop] invalid entry (0x{Graphic:X4})"); - } - } - else - { - int count = entry.Length / MultiLoader.Instance.Offset; - MultiLoader.Instance.File.Seek(entry.Offset); - - for (int i = 0; i < count; i++) - { - MultiBlock* block = (MultiBlock*)( - MultiLoader.Instance.File.PositionAddress + i * MultiLoader.Instance.Offset - ); - - if (block->X < minX) - { - minX = block->X; - } - - if (block->X > maxX) - { - maxX = block->X; - } - - if (block->Y < minY) - { - minY = block->Y; - } - - if (block->Y > maxY) - { - maxY = block->Y; - } - - if (block->Flags != 0) - { - Multi m = Multi.Create(block->ID); - m.MultiOffsetX = block->X; - m.MultiOffsetY = block->Y; - m.MultiOffsetZ = block->Z; - m.Hue = Hue; - m.AlphaHue = 255; - m.IsCustom = false; - m.State = CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_DONT_REMOVE; - m.IsMovable = ItemData.IsMultiMovable; - - m.SetInWorldTile( - (ushort)(X + block->X), - (ushort)(Y + block->Y), - (sbyte)(Z + block->Z) - ); - - house.Components.Add(m); - - if (m.ItemData.IsMultiMovable) - { - movable = true; - } - } - else if (i == 0) - { - MultiGraphic = block->ID; - } - } - } - - MultiInfo = new Rectangle - { - X = minX, - Y = minY, - Width = maxX, - Height = maxY - }; - - // hack to make baots movable. - // Mast is not the main center in bigger boats, so if we got a movable multi --> makes all multi movable - if (movable) - { - foreach (Multi m in house.Components) - { - m.IsMovable = movable; - } - } - - MultiDistanceBonus = Math.Max( - Math.Max(Math.Abs(minX), maxX), - Math.Max(Math.Abs(minY), maxY) - ); - - house.Bounds = MultiInfo.Value; - - UIManager.GetGump()?.RequestUpdateContents(); - - if (World.HouseManager.EntityIntoHouse(Serial, World.Player)) - { - Client.Game.GetScene()?.UpdateMaxDrawZ(true); - } - - BoatMovingManager.ClearSteps(Serial); - } - - public override void CheckGraphicChange(byte animIndex = 0) - { - if (!IsMulti) - { - if (!IsCorpse) - { - AllowedToDraw = CanBeDrawn(Graphic); - } - else - { - AnimIndex = 99; - - if ((Direction & Direction.Running) != 0) - { - UsedLayer = true; - Direction &= (Direction)0x7F; - } - else - { - UsedLayer = false; - } - - Layer = (Layer)Direction; - AllowedToDraw = true; - } - } - else if (WantUpdateMulti) - { - UoAssist.SignalAddMulti((ushort)(Graphic | 0x4000), X, Y); - - if ( - MultiDistanceBonus == 0 - || World.HouseManager.IsHouseInRange(Serial, World.ClientViewRange) - ) - { - LoadMulti(); - AllowedToDraw = MultiGraphic > 2; - } - } - } - - public override void Update() - { - if (IsDestroyed) - { - return; - } - - base.Update(); - - ProcessAnimation(); - } - - private static readonly Dictionary _mounts = new Dictionary< - ushort, - ushort - >() - { - { 0x3E90, 0x0114 }, // 16016 Reptalon - { 0x3E91, 0x0115 }, // 16017 - { 0x3E92, 0x011C }, // 16018 - { 0x3E94, 0x00F3 }, // 16020 - { 0x3E95, 0x00A9 }, // 16021 - { 0x3E97, 0x00C3 }, // 16023 Ethereal Giant Beetle - { 0x3E98, 0x00C2 }, // 16024 Ethereal Swamp Dragon - { 0x3E9A, 0x00C1 }, // 16026 Ethereal Ridgeback - { 0x3E9B, 0x00C0 }, // 16027 - { 0x3E9D, 0x00C0 }, // 16029 Ethereal Unicorn - { 0x3E9C, 0x00BF }, // 16028 Ethereal Kirin - { 0x3E9E, 0x00BE }, // 16030 - { 0x3EA0, 0x00E2 }, // 16032 light grey/horse3 - { 0x3EA1, 0x00E4 }, // 16033 greybrown/horse4 - { 0x3EA2, 0x00CC }, // 16034 dark brown/horse - { 0x3EA3, 0x00D2 }, // 16035 desert ostard - { 0x3EA4, 0x00DA }, // 16036 frenzied ostard (=zostrich) - { 0x3EA5, 0x00DB }, // 16037 forest ostard - { 0x3EA6, 0x00DC }, // 16038 Llama - { 0x3EA7, 0x0074 }, // 16039 Nightmare / Vortex - { 0x3EA8, 0x0075 }, // 16040 Silver Steed - { 0x3EA9, 0x0072 }, // 16041 Nightmare - { 0x3EAA, 0x0073 }, // 16042 Ethereal Horse - { 0x3EAB, 0x00AA }, // 16043 Ethereal Llama - { 0x3EAC, 0x00AB }, // 16044 Ethereal Ostard - { 0x3EAD, 0x0084 }, // 16045 Kirin - { 0x3EAF, 0x0078 }, // 16047 War Horse (Blood Red) - { 0x3EB0, 0x0079 }, // 16048 War Horse (Light Green) - { 0x3EB1, 0x0077 }, // 16049 War Horse (Light Blue) - { 0x3EB2, 0x0076 }, // 16050 War Horse (Purple) - { 0x3EB3, 0x0090 }, // 16051 Sea Horse (Medium Blue) - { 0x3EB4, 0x007A }, // 16052 Unicorn - { 0x3EB5, 0x00B1 }, // 16053 Nightmare - { 0x3EB6, 0x00B2 }, // 16054 Nightmare 4 - { 0x3EB7, 0x00B3 }, // 16055 Dark Steed - { 0x3EB8, 0x00BC }, // 16056 Ridgeback - { 0x3EBA, 0x00BB }, // 16058 Ridgeback, Savage - { 0x3EBB, 0x0319 }, // 16059 Skeletal Mount - { 0x3EBC, 0x0317 }, // 16060 Beetle - { 0x3EBD, 0x031A }, // 16061 SwampDragon - { 0x3EBE, 0x031F }, // 16062 Armored Swamp Dragon - { 0x3EC3, 0x02D4 }, // 16067 Beetle - { 0x3ECE, 0x059A }, // serpentine dragon - { 0x3EC5, 0x00D5 }, // 16069 - { 0x3F3A, 0x00D5 }, // 16186 snow bear ??? - { 0x3EC6, 0x01B0 }, // 16070 Boura - { 0x3EC7, 0x04E6 }, // 16071 Tiger - { 0x3EC8, 0x04E7 }, // 16072 Tiger - { 0x3EC9, 0x042D }, // 16073 - { 0x3ECA, 0x0579 }, // tarantula - { 0x3ECC, 0x0582 }, // 16016 - { 0x3ED1, 0x05E6 }, // CoconutCrab - { 0x3ECB, 0x057F }, // Lasher - { 0x3ED0, 0x05A1 }, // SkeletalCat - { 0x3ED2, 0x05F6 }, // war boar - { 0x3ECD, 0x0580 }, // Palomino - { 0x3ECF, 0x05A0 }, // Eowmu - { 0x3ED3, 0x05F7 }, // capybara - { 0x3ED4, 0x060A }, - { 0x3ED5, 0x060B }, // a wolf - { 0x3ED6, 0x060C }, // an orange dog 2? - { 0x3ED7, 0x060D }, - { 0x3ED8, 0x060F }, // a black dog? - { 0x3ED9, 0x0610 }, // a dobberman? - { 0x3EDA, 0x0590 } // Frostmites Beetles - }; - - public override ushort GetGraphicForAnimation() - { - var graphic = Graphic; - - if (Layer == Layer.Mount) - { - // ethereal unicorn - if (graphic == 0x3E9B || graphic == 0x3E9D) - { - return 0x00C0; - } - - // ethereal kirin - if (graphic == 0x3E9C) - { - return 0x00BF; - } - - if (_mounts.TryGetValue(graphic, out var newGraphic)) - { - graphic = newGraphic; - } - - if (ItemData.AnimID != 0) - { - graphic = ItemData.AnimID; - } - } - else if (IsCorpse) - { - return Amount; - } - - return graphic; - } - - public override void UpdateTextCoordsV() - { - if (TextContainer == null) - { - return; - } - - TextObject last = (TextObject)TextContainer.Items; - - while (last?.Next != null) - { - last = (TextObject)last.Next; - } - - if (last == null) - { - return; - } - - int offY = 0; - - if (OnGround) - { - Point p = RealScreenPosition; - - var bounds = Client.Game.Arts.GetRealArtBounds(Graphic); - p.Y -= bounds.Height >> 1; - - p.X += (int)Offset.X + 22; - p.Y += (int)(Offset.Y - Offset.Z) + 22; - - p = Client.Game.Scene.Camera.WorldToScreen(p); - - for (; last != null; last = (TextObject)last.Previous) - { - if (last.TextBox != null && !last.TextBox.IsDisposed) - { - if (offY == 0 && last.Time < Time.Ticks) - { - continue; - } - - last.OffsetY = offY; - offY += last.TextBox.Height; - - last.RealScreenPosition.X = p.X - (last.TextBox.Width >> 1); - last.RealScreenPosition.Y = p.Y - offY; - } - } - - FixTextCoordinatesInScreen(); - } - else - { - for (; last != null; last = (TextObject)last.Previous) - { - if (last.TextBox != null && !last.TextBox.IsDisposed) - { - if (offY == 0 && last.Time < Time.Ticks) - { - continue; - } - - last.OffsetY = offY; - offY += last.TextBox.Height; - - last.RealScreenPosition.X = last.X - (last.TextBox.Width >> 1); - last.RealScreenPosition.Y = last.Y - offY; - } - } - } - } - - public override void ProcessAnimation(bool evalutate = false) - { - if (IsCorpse) - { - var dir = (byte)Layer; - - if (LastAnimationChangeTime < Time.Ticks) - { - byte frameIndex = (byte)(AnimIndex + (ExecuteAnimation ? 1 : 0)); - ushort id = GetGraphicForAnimation(); - - bool mirror = false; - AnimationsLoader.Instance.GetAnimDirection(ref dir, ref mirror); - - if (id < Client.Game.Animations.MaxAnimationCount && dir < 5) - { - Client.Game.Animations.ConvertBodyIfNeeded(ref id); - var animGroup = Client.Game.Animations.GetAnimType(id); - var animFlags = Client.Game.Animations.GetAnimFlags(id); - byte action = AnimationsLoader.Instance.GetDeathAction( - id, - animFlags, - animGroup, - UsedLayer - ); - var frames = Client.Game.Animations.GetAnimationFrames( - id, - action, - dir, - out _, - out _, - isCorpse: true - ); - - if (frames.Length > 0) - { - // when the animation is done, stop to animate the corpse - if (frameIndex >= frames.Length) - { - frameIndex = (byte)(frames.Length - 1); - } - - AnimIndex = (byte)(frameIndex % frames.Length); - } - } - - LastAnimationChangeTime = Time.Ticks + Constants.CHARACTER_ANIMATION_DELAY; - } - } - } - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/Land.cs b/src/ClassicUO.Client/Game/GameObjects/Land.cs deleted file mode 100644 index 85642f5c1..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/Land.cs +++ /dev/null @@ -1,263 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Runtime.CompilerServices; -using ClassicUO.Game.Managers; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.GameObjects -{ - internal sealed partial class Land : GameObject - { - private static readonly QueuedPool _pool = new QueuedPool - ( - Constants.PREDICTABLE_TILE_COUNT, - l => - { - l.IsDestroyed = false; - l.AlphaHue = 255; - l.NormalTop = l.NormalRight = l.NormalLeft = l.NormalBottom = Vector3.Zero; - l.YOffsets.Top = l.YOffsets.Right = l.YOffsets.Left = l.YOffsets.Bottom = 0; - l.MinZ = l.AverageZ = 0; - } - ); - - public ref LandTiles TileData => ref TileDataLoader.Instance.LandData[Graphic]; - public sbyte AverageZ; - public bool IsStretched; - public sbyte MinZ; - public Vector3 NormalTop, NormalRight, NormalLeft, NormalBottom; - public ushort OriginalGraphic; - public UltimaBatcher2D.YOffsets YOffsets; - - public static Land Create(ushort graphic) - { - Land land = _pool.GetOne(); - land.Graphic = graphic; - land.OriginalGraphic = graphic; - land.IsStretched = land.TileData.TexID == 0 && land.TileData.IsWet; - land.AllowedToDraw = graphic > 2; - land.UpdateGraphicBySeason(); - - return land; - } - - public override void Destroy() - { - if (IsDestroyed) - { - return; - } - - base.Destroy(); - _pool.ReturnOne(this); - } - - public override void UpdateGraphicBySeason() - { - Graphic = SeasonManager.GetLandSeasonGraphic(World.Season, OriginalGraphic); - AllowedToDraw = Graphic > 2; - } - - public int CalculateCurrentAverageZ(int direction) - { - int result = GetDirectionZ(((byte) (direction >> 1) + 1) & 3); - - if ((direction & 1) != 0) - { - return result; - } - - return (result + GetDirectionZ(direction >> 1)) >> 1; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private int GetDirectionZ(int direction) - { - switch (direction) - { - case 1: return YOffsets.Right >> 2; - case 2: return YOffsets.Bottom >> 2; - case 3: return YOffsets.Left >> 2; - default: return Z; - } - } - - public void ApplyStretch(Map.Map map, int x, int y, sbyte z) - { - if (IsStretched || TexmapsLoader.Instance.GetValidRefEntry(TileData.TexID).Length <= 0) - { - IsStretched = false; - AverageZ = z; - MinZ = z; - - return; - } - - /* _____ _____ - * | top | rig | - * |_____|_____| - * | lef | bot | - * |_____|_____| - */ - sbyte zTop = z; - sbyte zRight = map.GetTileZ(x + 1, y); - sbyte zLeft = map.GetTileZ(x, y + 1); - sbyte zBottom = map.GetTileZ(x + 1, y + 1); - - YOffsets.Top = zTop * 4; - YOffsets.Right = zRight * 4; - YOffsets.Left = zLeft * 4; - YOffsets.Bottom = zBottom * 4; - - if (Math.Abs(zTop - zBottom) <= Math.Abs(zLeft - zRight)) - { - AverageZ = (sbyte) ((zTop + zBottom) >> 1); - } - else - { - AverageZ = (sbyte) ((zLeft + zRight) >> 1); - } - - MinZ = Math.Min(zTop, Math.Min(zRight, Math.Min(zLeft, zBottom))); - - - /* _____ _____ _____ _____ - * | | t10 | t20 | | - * |_____|_____|_____|_____| - * | t01 | z | t21 | t31 | - * |_____|_____|_____|_____| - * | t02 | t12 | t22 | t32 | - * |_____|_____|_____|_____| - * | | t13 | t23 | | - * |_____|_____|_____|_____| - */ - sbyte t10 = map.GetTileZ(x, y - 1); - sbyte t20 = map.GetTileZ(x + 1, y - 1); - sbyte t01 = map.GetTileZ(x - 1, y); - sbyte t21 = zRight; - sbyte t31 = map.GetTileZ(x + 2, y); - sbyte t02 = map.GetTileZ(x - 1, y + 1); - sbyte t12 = zLeft; - sbyte t22 = zBottom; - sbyte t32 = map.GetTileZ(x + 2, y + 1); - sbyte t13 = map.GetTileZ(x, y + 2); - sbyte t23 = map.GetTileZ(x + 1, y + 2); - - - IsStretched |= CalculateNormal(z, t10, t21, t12, t01, out NormalTop); - IsStretched |= CalculateNormal(t21, t20, t31, t22, z, out NormalRight); - IsStretched |= CalculateNormal(t22, t21, t32, t23, t12, out NormalBottom); - IsStretched |= CalculateNormal(t12, z, t22, t13, t02, out NormalLeft); - } - - private static bool CalculateNormal(sbyte tile, sbyte top, sbyte right, sbyte bottom, sbyte left, out Vector3 normal) - { - if (tile == top && tile == right && tile == bottom && tile == left) - { - normal.X = 0; - normal.Y = 0; - normal.Z = 1f; - - return false; - } - - Vector3 u = new Vector3(); - Vector3 v = new Vector3(); - Vector3 ret = new Vector3(); - - - // ========================== - u.X = -22; - u.Y = -22; - u.Z = (left - tile) * 4; - - v.X = -22; - v.Y = 22; - v.Z = (bottom - tile) * 4; - - Vector3.Cross(ref v, ref u, out ret); - // ========================== - - - // ========================== - u.X = -22; - u.Y = 22; - u.Z = (bottom - tile) * 4; - - v.X = 22; - v.Y = 22; - v.Z = (right - tile) * 4; - - Vector3.Cross(ref v, ref u, out normal); - Vector3.Add(ref ret, ref normal, out ret); - // ========================== - - - // ========================== - u.X = 22; - u.Y = 22; - u.Z = (right - tile) * 4; - - v.X = 22; - v.Y = -22; - v.Z = (top - tile) * 4; - - Vector3.Cross(ref v, ref u, out normal); - Vector3.Add(ref ret, ref normal, out ret); - // ========================== - - - // ========================== - u.X = 22; - u.Y = -22; - u.Z = (top - tile) * 4; - - v.X = -22; - v.Y = -22; - v.Z = (left - tile) * 4; - - Vector3.Cross(ref v, ref u, out normal); - Vector3.Add(ref ret, ref normal, out ret); - // ========================== - - - Vector3.Normalize(ref ret, out normal); - - return true; - } - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/LightningEffect.cs b/src/ClassicUO.Client/Game/GameObjects/LightningEffect.cs deleted file mode 100644 index 2348efe78..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/LightningEffect.cs +++ /dev/null @@ -1,85 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Managers; - -namespace ClassicUO.Game.GameObjects -{ - internal sealed partial class LightningEffect : GameEffect - { - public LightningEffect(EffectManager manager, uint src, ushort x, ushort y, sbyte z, ushort hue) - : base(manager, 0x4E20, hue, 400, 0) - { - IsEnabled = true; - AnimIndex = 0; - - Entity source = World.Get(src); - - if (SerialHelper.IsValid(src) && source != null) - { - SetSource(source); - } - else - { - SetSource(x, y, z); - } - } - - public override void Update() - { - if (!IsDestroyed) - { - if (AnimIndex >= 10 || (Duration < Time.Ticks && Duration >= 0)) - { - Destroy(); - } - else - { - AnimationGraphic = (ushort) (Graphic + AnimIndex); - - if (NextChangeFrameTime < Time.Ticks) - { - AnimIndex++; - NextChangeFrameTime = (long)Time.Ticks + IntervalInMs; - } - - (var x, var y, var z) = GetSource(); - - if (X != x || Y != y || Z != z) - { - SetInWorldTile(x, y, z); - } - } - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/GameObjects/Mobile.cs b/src/ClassicUO.Client/Game/GameObjects/Mobile.cs deleted file mode 100644 index 2fab6922f..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/Mobile.cs +++ /dev/null @@ -1,1104 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Assets; -using ClassicUO.Resources; -using ClassicUO.Utility; -using ClassicUO.Utility.Collections; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.GameObjects -{ - public partial class Mobile : Entity - { - private static readonly QueuedPool _pool = new QueuedPool( - Constants.PREDICTABLE_CHUNKS, - mobile => - { - mobile.IsDestroyed = false; - mobile.Graphic = 0; - mobile.Steps.Clear(); - mobile.Offset = Vector3.Zero; - mobile.SpeedMode = CharacterSpeedType.Normal; - mobile.Race = 0; - mobile.Hits = 0; - mobile.HitsMax = 0; - mobile.Mana = 0; - mobile.ManaMax = 0; - mobile.Stamina = 0; - mobile.StaminaMax = 0; - mobile.NotorietyFlag = 0; - mobile.IsRenamable = false; - mobile.Flags = 0; - mobile.IsFemale = false; - mobile.InWarMode = false; - mobile.IsRunning = false; - mobile._animationInterval = 0; - mobile.AnimationFrameCount = 0; - mobile._animationRepeateMode = 1; - mobile._animationRepeatModeCount = 1; - mobile._animationRepeat = false; - mobile.AnimationFromServer = false; - mobile._isAnimationForwardDirection = false; - mobile.LastStepSoundTime = 0; - mobile.StepSoundOffset = 0; - mobile.Title = string.Empty; - mobile._animationGroup = 0xFF; - mobile._isDead = false; - mobile._isSA_Poisoned = false; - mobile._lastAnimationIdleDelay = 0; - mobile.X = 0; - mobile.Y = 0; - mobile.Z = 0; - mobile.Direction = 0; - mobile.LastAnimationChangeTime = Time.Ticks; - mobile.TextContainer?.Clear(); - mobile.HitsPercentage = 0; - mobile.IsFlipped = false; - mobile.FrameInfo = Rectangle.Empty; - mobile.ObjectHandlesStatus = ObjectHandlesStatus.NONE; - mobile.AlphaHue = 0; - mobile.AllowedToDraw = true; - mobile.IsClicked = false; - mobile.RemoveFromTile(); - mobile.Clear(); - mobile.Next = null; - mobile.Previous = null; - mobile.Name = null; - mobile.ExecuteAnimation = true; - mobile.HitsRequest = HitsRequestStatus.None; - - mobile.CalculateRandomIdleTime(); - } - ); - - private static readonly byte[,] _animationIdle = - { - { - (byte)LowAnimationGroup.Fidget1, - (byte)LowAnimationGroup.Fidget2, - (byte)LowAnimationGroup.Fidget1 - }, - { - (byte)HighAnimationGroup.Fidget1, - (byte)HighAnimationGroup.Fidget2, - (byte)HighAnimationGroup.Fidget1 - }, - { - (byte)PeopleAnimationGroup.Fidget1, - (byte)PeopleAnimationGroup.Fidget2, - (byte)PeopleAnimationGroup.Fidget3 - } - }; - - private bool _isDead; - private bool _isSA_Poisoned; - private long _lastAnimationIdleDelay; - private bool _isAnimationForwardDirection; - private byte _animationGroup = 0xFF; - private byte _animationInterval; - private bool _animationRepeat; - private ushort _animationRepeateMode = 1; - private ushort _animationRepeatModeCount = 1; - - public Mobile(uint serial) : base(serial) - { - LastAnimationChangeTime = Time.Ticks; - CalculateRandomIdleTime(); - } - - public Mobile() : base(0) { } - - public Deque Steps { get; } = new Deque(Constants.MAX_STEP_COUNT); - public bool IsParalyzed => (Flags & Flags.Frozen) != 0; - public bool IsYellowHits => (Flags & Flags.YellowBar) != 0; - public bool IsPoisoned => - Client.Version >= ClientVersion.CV_7000 - ? _isSA_Poisoned - : (Flags & Flags.Poisoned) != 0; - public bool IgnoreCharacters => (Flags & Flags.IgnoreMobiles) != 0; - - public bool IsDead - { - get => - Graphic == 0x0192 - || Graphic == 0x0193 - || (Graphic >= 0x025F && Graphic <= 0x0260) - || Graphic == 0x2B6 - || Graphic == 0x02B7 - || _isDead; - set => _isDead = value; - } - - public bool IsFlying => - Client.Version >= ClientVersion.CV_7000 && (Flags & Flags.Poisoned) != 0; - - public virtual bool InWarMode - { - get => (Flags & Flags.WarMode) != 0; - set { } - } - - public bool IsHuman => - Graphic >= 0x0190 && Graphic <= 0x0193 - || Graphic >= 0x00B7 && Graphic <= 0x00BA - || Graphic >= 0x025D && Graphic <= 0x0260 - || Graphic == 0x029A - || Graphic == 0x029B - || Graphic == 0x02B6 - || Graphic == 0x02B7 - || Graphic == 0x03DB - || Graphic == 0x03DF - || Graphic == 0x03E2 - || Graphic == 0x02E8 - || Graphic == 0x02E9 - || Graphic == 0x04E5; - - public bool IsGargoyle => - Client.Version >= ClientVersion.CV_7000 && Graphic == 0x029A || Graphic == 0x029B; - - public bool IsMounted - { - get - { - Item it = FindItemByLayer(Layer.Mount); - - if (it != null && !IsDrivingBoat && it.GetGraphicForAnimation() != 0xFFFF) - { - return true; - } - - return false; - } - } - - public bool IsDrivingBoat - { - get - { - Item it = FindItemByLayer(Layer.Mount); - - return it != null && it.Graphic == 0x3E96; - } - } - - protected virtual bool IsWalking => LastStepTime > Time.Ticks - Constants.WALKING_DELAY; - - public byte AnimationFrameCount; - public bool AnimationFromServer; - public bool IsFemale; - public bool IsRenamable; - public bool IsRunning; - public long LastStepSoundTime; - public NotorietyFlag NotorietyFlag; - public RaceType Race; - public CharacterSpeedType SpeedMode = CharacterSpeedType.Normal; - public ushort Stamina; - public ushort StaminaMax; - public ushort Mana; - public ushort ManaMax; - public int StepSoundOffset; - public string Title = string.Empty; - - public static Mobile Create(uint serial) - { - Mobile mobile = _pool.GetOne(); - mobile.Serial = serial; - - return mobile; - } - - public Item GetSecureTradeBox() - { - for (LinkedObject i = Items; i != null; i = i.Next) - { - Item it = (Item)i; - - if (it.Graphic == 0x1E5E && it.Layer == 0) - { - return it; - } - } - - return null; - } - - public void SetSAPoison(bool value) - { - _isSA_Poisoned = value; - } - - private void CalculateRandomIdleTime() - { - const int TIME = 30000; - _lastAnimationIdleDelay = Time.Ticks + (TIME + RandomHelper.GetValue(0, TIME)); - } - - public override void Update() - { - if (IsDestroyed) - { - return; - } - - base.Update(); - - if (_lastAnimationIdleDelay < Time.Ticks) - { - SetIdleAnimation(); - } - - ProcessAnimation(true); - } - - public void ClearSteps() - { - Steps.Clear(); - Offset = Vector3.Zero; - } - - public bool EnqueueStep(int x, int y, sbyte z, Direction direction, bool run) - { - if (Steps.Count >= Constants.MAX_STEP_COUNT) - { - return false; - } - - GetEndPosition(out int endX, out int endY, out sbyte endZ, out Direction endDir); - - if (endX == x && endY == y && endZ == z && endDir == direction) - { - return true; - } - - if (Steps.Count == 0) - { - if (!IsWalking) - { - SetAnimation(0xFF); - } - - LastStepTime = Time.Ticks; - } - - Direction moveDir = DirectionHelper.CalculateDirection(endX, endY, x, y); - Step step = new Step(); - - if (moveDir != Direction.NONE) - { - if (moveDir != endDir) - { - step.X = endX; - step.Y = endY; - step.Z = endZ; - step.Direction = (byte)moveDir; - step.Run = run; - Steps.AddToBack(step); - } - - step.X = x; - step.Y = y; - step.Z = z; - step.Direction = (byte)moveDir; - step.Run = run; - Steps.AddToBack(step); - } - - if (moveDir != direction) - { - step.X = x; - step.Y = y; - step.Z = z; - step.Direction = (byte)direction; - step.Run = run; - Steps.AddToBack(step); - } - - return true; - } - - internal void GetEndPosition(out int x, out int y, out sbyte z, out Direction dir) - { - if (Steps.Count == 0) - { - x = X; - y = Y; - z = Z; - dir = Direction; - } - else - { - ref Step step = ref Steps.Back(); - x = step.X; - y = step.Y; - z = step.Z; - dir = (Direction)step.Direction; - } - } - - public void SetAnimation( - byte id, - byte interval = 0, - byte frameCount = 0, - ushort repeatCount = 0, - bool repeat = false, - bool forward = false, - bool fromServer = false - ) - { - _animationGroup = id; - AnimIndex = (byte)(forward ? 0 : frameCount); - _animationInterval = interval; - AnimationFrameCount = (byte)(forward ? 0 : frameCount); - _animationRepeateMode = repeatCount; - _animationRepeatModeCount = repeatCount; - _animationRepeat = repeat; - _isAnimationForwardDirection = forward; - AnimationFromServer = fromServer; - LastAnimationChangeTime = Time.Ticks; - - CalculateRandomIdleTime(); - } - - public void SetIdleAnimation() - { - CalculateRandomIdleTime(); - - if (!IsMounted && !InWarMode && ExecuteAnimation) - { - AnimIndex = 0; - AnimationFrameCount = 0; - _animationInterval = 1; - _animationRepeateMode = 1; - _animationRepeatModeCount = 1; - _isAnimationForwardDirection = true; - _animationRepeat = false; - AnimationFromServer = true; - - ushort graphic = GetGraphicForAnimation(); - - if (graphic >= Client.Game.Animations.MaxAnimationCount) - { - return; - } - - //byte action = 0; - //ushort hue = 0; - - //Client.Game.Animations.ReplaceAnimationValues( - // ref graphic, - // ref action, - // ref hue, - // out var useUOP - //); - - AnimationGroupsType type = Client.Game.Animations.GetAnimType(graphic); - AnimationFlags flags = Client.Game.Animations.GetAnimFlags(graphic); - AnimationGroups animGroup = AnimationGroups.None; - - bool isLowExtended = false; - - if ((flags & AnimationFlags.CalculateOffsetLowGroupExtended) != 0) - { - isLowExtended = true; - type = AnimationGroupsType.Monster; - } - else if ((flags & AnimationFlags.CalculateOffsetByLowGroup) != 0) - { - type = AnimationGroupsType.Animal; - } - - switch (type) - { - case AnimationGroupsType.SeaMonster: - case AnimationGroupsType.Monster: - animGroup = AnimationGroups.High; - - break; - - case AnimationGroupsType.Animal: - animGroup = AnimationGroups.Low; - - break; - - case AnimationGroupsType.Human: - case AnimationGroupsType.Equipment: - animGroup = AnimationGroups.People; - - break; - } - - if (animGroup == 0) - { - return; - } - - if ((flags & AnimationFlags.UseUopAnimation) != 0) - { - if (animGroup != AnimationGroups.People) - { - if (InWarMode) - { - _animationGroup = 28; - } - else - { - _animationGroup = 26; - } - - return; - } - - if (IsGargoyle && IsFlying) - { - if (RandomHelper.GetValue(0, 2) != 0) - { - _animationGroup = 66; - } - else - { - _animationGroup = 67; - } - - return; - } - } - - int first_value = RandomHelper.GetValue(0, 2); - - byte original_value = _animationGroup; - - _animationGroup = _animationIdle[(byte)animGroup - 1, first_value]; - - if (isLowExtended && _animationGroup == 18) - { - if ( - !Client.Game.Animations.AnimationExists(graphic, 18) - && Client.Game.Animations.AnimationExists(graphic, 17) - ) - { - _animationGroup = GetReplacedObjectAnimation(graphic, 17); - } - else - { - _animationGroup = 1; - } - } - - if (!Client.Game.Animations.AnimationExists(graphic, _animationGroup)) - { - if (first_value == 0) - { - first_value = 1; - } - else - { - first_value = 0; - } - - _animationGroup = _animationIdle[(byte)animGroup - 1, first_value]; - - if (!Client.Game.Animations.AnimationExists(graphic, _animationGroup)) - { - SetAnimation(original_value); - } - } - } - } - - private bool NoIterateAnimIndex() - { - return !ExecuteAnimation - || (LastStepTime > Time.Ticks - Constants.WALKING_DELAY && Steps.Count == 0); - } - - private void ProcessFootstepsSound() - { - if ( - ProfileManager.CurrentProfile.EnableFootstepsSound - && IsHuman - && !IsHidden - && !IsDead - && !IsFlying - ) - { - if (Steps.Count != 0 && LastStepSoundTime < Time.Ticks) - { - ref Step step = ref Steps.Back(); - - int incID = StepSoundOffset; - int soundID = 0x012B; - int delaySound = 400; - - if (IsMounted) - { - if (step.Run) - { - soundID = 0x0129; - delaySound = 150; - } - else - { - incID = 0; - delaySound = 350; - } - } - - delaySound = delaySound * 13 / 10; - - soundID += incID; - - StepSoundOffset = (incID + 1) % 2; - - Client.Game.Audio.PlaySoundWithDistance(soundID, step.X, step.Y); - LastStepSoundTime = Time.Ticks + delaySound; - } - } - } - - public override void ProcessAnimation(bool evalutate = false) - { - ProcessSteps(out var dir, evalutate); - ProcessFootstepsSound(); - - if (LastAnimationChangeTime < Time.Ticks && !NoIterateAnimIndex()) - { - ushort id = GetGraphicForAnimation(); - byte action = GetGroupForAnimation(this, id, true); - - bool mirror = false; - AnimationsLoader.Instance.GetAnimDirection(ref dir, ref mirror); - int currentDelay = Constants.CHARACTER_ANIMATION_DELAY; - - if (id < Client.Game.Animations.MaxAnimationCount && dir < 5) - { - var frames = Client.Game.Animations.GetAnimationFrames( - id, - action, - dir, - out _, - out _ - ); - - if (frames.Length != 0) - { - int fc = frames.Length; - - int frameIndex = - AnimIndex - + (AnimationFromServer && !_isAnimationForwardDirection ? -1 : 1); - - if (AnimationFromServer) - { - currentDelay += currentDelay * (_animationInterval + 1); - - if (AnimationFrameCount == 0) - { - AnimationFrameCount = (byte)fc; - } - else - { - fc = AnimationFrameCount; - } - - if (_isAnimationForwardDirection && frameIndex >= fc) - { - frameIndex = 0; - } - else if (!_isAnimationForwardDirection && frameIndex < 0) - { - if (fc == 0) - { - frameIndex = 0; - } - else - { - frameIndex = (byte)(frames.Length - 1); - } - } - else - { - goto SKIP; - } - - if (_animationRepeateMode == 0) // play animation infinite time - { - goto SKIP; - } - - if (--_animationRepeateMode > 0) // play animation n times - { - goto SKIP; - } - - if (_animationRepeat) - { - _animationRepeatModeCount = _animationRepeateMode; - - _animationRepeat = false; - } - else - { - SetAnimation(0xFF); - } - - SKIP: - ; - } - else - { - if (frameIndex >= fc) - { - frameIndex = 0; - - if ((Serial & 0x80000000) != 0) - { - World.CorpseManager.Remove(0, Serial); - World.RemoveMobile(Serial); - } - } - } - - AnimIndex = (byte)(frameIndex % frames.Length); - } - else if ((Serial & 0x80000000) != 0) - { - World.CorpseManager.Remove(0, Serial); - World.RemoveMobile(Serial); - } - } - else if ((Serial & 0x80000000) != 0) - { - World.CorpseManager.Remove(0, Serial); - World.RemoveMobile(Serial); - } - - LastAnimationChangeTime = Time.Ticks + currentDelay; - } - } - - public void ProcessSteps(out byte dir, bool evalutate = false) - { - dir = (byte)Direction; - dir &= 7; - - if (Steps.Count != 0 && !IsDestroyed) - { - ref Step step = ref Steps.Front(); - dir = step.Direction; - - if (step.Run) - { - dir &= 7; - } - - if (evalutate) - { - if (AnimationFromServer) - { - SetAnimation(0xFF); - } - - int delay = (int)Time.Ticks - (int)LastStepTime; - bool mounted = - IsMounted - || SpeedMode == CharacterSpeedType.FastUnmount - || SpeedMode == CharacterSpeedType.FastUnmountAndCantRun - || IsFlying; - bool run = step.Run; - - // Client auto movements sync. - // When server sends more than 1 packet in an amount of time less than 100ms if mounted (or 200ms if walking mount) - // we need to remove the "teleport" effect. - // When delay == 0 means that we received multiple movement packets in a single frame, so the patch becomes quite useless. - if (!mounted && Serial != World.Player && Steps.Count > 1 && delay > 0) - { - mounted = - delay - <= ( - run - ? MovementSpeed.STEP_DELAY_MOUNT_RUN - : MovementSpeed.STEP_DELAY_MOUNT_WALK - ); - } - - int maxDelay = - MovementSpeed.TimeToCompleteMovement(run, mounted) - - (int)Client.Game.FrameDelay[1]; - - bool removeStep = delay >= maxDelay; - bool directionChange = false; - - if (X != step.X || Y != step.Y) - { - bool badStep = false; - - if (Offset.X == 0 && Offset.Y == 0) - { - int absX = Math.Abs(X - step.X); - int absY = Math.Abs(Y - step.Y); - - badStep = absX > 1 || absY > 1 || absX + absY == 0; - - if (!badStep) - { - absX = X; - absY = Y; - - Pathfinder.GetNewXY((byte)(step.Direction & 7), ref absX, ref absY); - - badStep = absX != step.X || absY != step.Y; - } - } - - if (badStep) - { - removeStep = true; - } - else - { - float steps = maxDelay / (float)Constants.CHARACTER_ANIMATION_DELAY; - float x = delay / (float)Constants.CHARACTER_ANIMATION_DELAY; - float y = x; - Offset.Z = (sbyte)((step.Z - Z) * x * (4.0f / steps)); - MovementSpeed.GetPixelOffset(step.Direction, ref x, ref y, steps); - Offset.X = (sbyte)x; - Offset.Y = (sbyte)y; - } - } - else - { - directionChange = true; - removeStep = true; - } - - if (removeStep) - { - if (Serial == World.Player) - { - //if (Position.X != step.X || Position.Y != step.Y || Position.Z != step.Z) - //{ - //} - - if (Z - step.Z >= 22) - { - // oUCH!!!! - AddMessage(MessageType.Label, ResGeneral.Ouch, TextType.CLIENT); - } - - if ( - World.Player.Walker.StepInfos[ - World.Player.Walker.CurrentWalkSequence - ].Accepted - ) - { - int sequence = World.Player.Walker.CurrentWalkSequence + 1; - - if (sequence < World.Player.Walker.StepsCount) - { - int count = World.Player.Walker.StepsCount - sequence; - - for (int i = 0; i < count; i++) - { - World.Player.Walker.StepInfos[sequence - 1] = World - .Player - .Walker - .StepInfos[sequence]; - - sequence++; - } - } - - World.Player.Walker.StepsCount--; - } - else - { - World.Player.Walker.CurrentWalkSequence++; - } - } - - X = (ushort)step.X; - Y = (ushort)step.Y; - Z = step.Z; - UpdateScreenPosition(); - - if (World.InGame && Serial == World.Player) - { - World.Player.CloseRangedGumps(); - } - - Direction = (Direction)step.Direction; - IsRunning = step.Run; - Offset.X = 0; - Offset.Y = 0; - Offset.Z = 0; - Steps.RemoveFromFront(); - CalculateRandomIdleTime(); - - if (directionChange) - { - ProcessSteps(out dir, evalutate); - - return; - } - - if (TNext != null || TPrevious != null) - { - AddToTile(); - } - - LastStepTime = Time.Ticks; - } - - UpdateTextCoordsV(); - } - } - } - - public bool TryGetSittingInfo(out AnimationsLoader.SittingInfoData data) - { - ushort result = 0; - - if ( - IsHuman - && !IsMounted - && !IsFlying - && !TestStepNoChangeDirection(this, GetGroupForAnimation(this, isParent: true)) - ) - { - GameObject start = this; - - while (start?.TPrevious != null) - { - start = start.TPrevious; - } - - while (start != null && result == 0) - { - if ( - (start is Item || start is Static || start is Multi) - && Math.Abs(Z - start.Z) <= 1 - ) - { - if (ChairTable.Table.TryGetValue(start.Graphic, out data)) - { - return true; - } - } - - start = (GameObject)start.TNext; - } - } - - data = AnimationsLoader.SittingInfoData.Empty; - return false; - } - - public override void UpdateTextCoordsV() - { - if (TextContainer == null) - { - return; - } - - TextObject last = (TextObject)TextContainer.Items; - - while (last?.Next != null) - { - last = (TextObject)last.Next; - } - - if (last == null) - { - return; - } - - int offY = 0; - - bool health = ProfileManager.CurrentProfile.ShowMobilesHP; - int alwaysHP = ProfileManager.CurrentProfile.MobileHPShowWhen; - int mode = ProfileManager.CurrentProfile.MobileHPType; - - Point p = RealScreenPosition; - - if (IsGargoyle && IsFlying) - { - p.Y -= 22; - } - else if (!IsMounted) - { - p.Y += 22; - } - - Client.Game.Animations.GetAnimationDimensions( - AnimIndex, - GetGraphicForAnimation(), - /*(byte) m.GetDirectionForAnimation()*/ - 0, - /*Mobile.GetGroupForAnimation(m, isParent:true)*/ - 0, - IsMounted, - /*(byte) m.AnimIndex*/ - 0, - out _, - out int centerY, - out _, - out int height - ); - - p.X += (int)Offset.X + 22; - p.Y += (int)(Offset.Y - Offset.Z - (height + centerY + 8)); - p = Client.Game.Scene.Camera.WorldToScreen(p); - - if (ObjectHandlesStatus == ObjectHandlesStatus.DISPLAYING) - { - p.Y -= Constants.OBJECT_HANDLES_GUMP_HEIGHT; - } - - if ( - health - && HitsTexture != null - && mode != 1 - && (alwaysHP >= 1 && Hits != HitsMax || alwaysHP == 0) - ) - { - p.Y -= HitsTexture.Height; - } - - for (; last != null; last = (TextObject)last.Previous) - { - if (last.TextBox != null && !last.TextBox.IsDisposed) - { - if (offY == 0 && last.Time < Time.Ticks) - { - continue; - } - - last.OffsetY = offY; - offY += last.TextBox.Height; - - last.RealScreenPosition.X = p.X - (last.TextBox.Width >> 1); - last.RealScreenPosition.Y = p.Y - offY; - } - } - - FixTextCoordinatesInScreen(); - } - - public override void CheckGraphicChange(byte animIndex = 0) - { - switch (Graphic) - { - case 0x0190: - case 0x0192: - { - IsFemale = false; - Race = RaceType.HUMAN; - - break; - } - - case 0x0191: - case 0x0193: - { - IsFemale = true; - Race = RaceType.HUMAN; - - break; - } - - case 0x025D: - { - IsFemale = false; - Race = RaceType.ELF; - - break; - } - - case 0x025E: - { - IsFemale = true; - Race = RaceType.ELF; - - break; - } - - case 0x029A: - { - IsFemale = false; - Race = RaceType.GARGOYLE; - - break; - } - - case 0x029B: - { - IsFemale = true; - Race = RaceType.GARGOYLE; - - break; - } - } - } - - public override void Destroy() - { - uint serial = Serial & 0x3FFFFFFF; - - ClearSteps(); - - base.Destroy(); - - if (!(this is PlayerMobile)) - { - UIManager.GetGump(serial)?.Dispose(); - UIManager.GetGump(serial)?.Dispose(); - - _pool.ReturnOne(this); - } - } - - public struct Step - { - public int X, - Y; - public sbyte Z; - public byte Direction; - public bool Run; - } - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/MobileAnimation.cs b/src/ClassicUO.Client/Game/GameObjects/MobileAnimation.cs deleted file mode 100644 index 89723638a..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/MobileAnimation.cs +++ /dev/null @@ -1,2104 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using ClassicUO.Game.Data; -using ClassicUO.Assets; -using ClassicUO.Utility; - -namespace ClassicUO.Game.GameObjects -{ - public partial class Mobile - { - private static readonly ushort[] HANDS_BASE_ANIMID = - { - 0x0263, - 0x0264, - 0x0265, - 0x0266, - 0x0267, - 0x0268, - 0x0269, - 0x026D, - 0x0270, - 0x0272, - 0x0274, - 0x027A, - 0x027C, - 0x027F, - 0x0281, - 0x0286, - 0x0288, - 0x0289, - 0x028B, - 0 - }; - - private static readonly ushort[] HAND2_BASE_ANIMID = - { - 0x0240, - 0x0241, - 0x0242, - 0x0243, - 0x0244, - 0x0245, - 0x0246, - 0x03E0, - 0x03E1, - 0 - }; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override ushort GetGraphicForAnimation() - { - ushort g = Graphic; - - switch (g) - { - case 0x0192: - case 0x0193: - { - g -= 2; - - break; - } - - case 0x02B6: - g = 667; - - break; - - case 0x02B7: - g = 666; - - break; - } - - return g; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Direction GetDirectionForAnimation() - { - if (Steps.Count != 0) - { - ref Step step = ref Steps.Front(); - - return (Direction)step.Direction; - } - - return Direction; - } - - private static void CalculateHight( - ushort graphic, - Mobile mobile, - AnimationFlags flags, - bool isrun, - bool iswalking, - ref byte result - ) - { - if ((flags & AnimationFlags.CalculateOffsetByPeopleGroup) != 0) - { - if (result == 0xFF) - { - result = 0; - } - } - else if ((flags & AnimationFlags.CalculateOffsetByLowGroup) != 0) - { - if (!iswalking) - { - if (result == 0xFF) - { - result = 2; - } - } - else if (isrun) - { - result = 1; - } - else - { - result = 0; - } - } - else - { - if (mobile.IsFlying) - { - result = 19; - } - else if (!iswalking) - { - if (result == 0xFF) - { - if ( - (flags & AnimationFlags.IdleAt8Frame) != 0 - && Client.Game.Animations.AnimationExists(graphic, 8) - ) - { - result = 8; - } - else - { - if ( - (flags & AnimationFlags.UseUopAnimation) != 0 - && !mobile.InWarMode - ) - { - result = 25; - } - else - { - result = 1; - } - } - } - } - else if (isrun) - { - if ( - (flags & AnimationFlags.CanFlying) != 0 - && Client.Game.Animations.AnimationExists(graphic, 19) - ) - { - result = 19; - } - else - { - if ((flags & AnimationFlags.UseUopAnimation) != 0) - { - result = 24; - } - else - { - result = 0; - } - } - } - else - { - if ((flags & AnimationFlags.UseUopAnimation) != 0 && !mobile.InWarMode) - { - result = 22; - } - else - { - result = 0; - } - } - } - } - - private static void LABEL_222(AnimationFlags flags, ref ushort v13) - { - if ((flags & AnimationFlags.CalculateOffsetLowGroupExtended) != 0) - { - switch (v13) - { - case 0: - v13 = 0; - - goto LABEL_243; - - case 1: - v13 = 19; - - goto LABEL_243; - - case 5: - case 6: - - if ((flags & AnimationFlags.IdleAt8Frame) != 0) - { - v13 = 4; - } - else - { - v13 = (ushort)(6 - (RandomHelper.GetValue() % 2 != 0 ? 1 : 0)); - } - - goto LABEL_243; - - case 8: - v13 = 2; - - goto LABEL_243; - - case 9: - v13 = 17; - - goto LABEL_243; - - case 10: - v13 = 18; - - if ((flags & AnimationFlags.IdleAt8Frame) != 0) - { - v13--; - } - - goto LABEL_243; - - case 12: - v13 = 3; - - goto LABEL_243; - } - - // LABEL_241 - v13 = 1; - } - else - { - if ((flags & AnimationFlags.CalculateOffsetByLowGroup) != 0) - { - switch (v13) - { - case 0: - // LABEL_232 - v13 = 0; - - break; - - case 2: - v13 = 8; - - break; - - case 3: - v13 = 12; - - break; - - case 4: - case 6: - case 7: - case 8: - case 9: - case 12: - case 13: - case 14: - v13 = 5; - - break; - - case 5: - v13 = 6; - - break; - - case 10: - case 21: - v13 = 7; - - break; - - case 11: - //LABEL_238: - v13 = 3; - - break; - - case 17: - v13 = 9; - - break; - - case 18: - v13 = 10; - - break; - - case 19: - - v13 = 1; - - break; - - default: - //LABEL_242: - v13 = 2; - - break; - } - } - } - - LABEL_243: - v13 = (ushort)(v13 & 0x7F); - - //if (v13 > 34) - // v13 = 0; - } - - private static void LABEL_190(AnimationFlags flags, ref ushort v13) - { - if ((flags & AnimationFlags.Unknown80) != 0 && v13 == 4) - { - v13 = 5; - } - - if ((flags & AnimationFlags.Unknown200) != 0) - { - if (v13 - 7 > 9) - { - if (v13 == 19) - { - //LABEL_196 - v13 = 0; - } - else if (v13 > 19) - { - v13 = 1; - } - - LABEL_222(flags, ref v13); - - return; - } - } - else - { - if ((flags & AnimationFlags.Unknown100) != 0) - { - switch (v13) - { - case 10: - case 15: - case 16: - v13 = 1; - LABEL_222(flags, ref v13); - - return; - - case 11: - v13 = 17; - LABEL_222(flags, ref v13); - - return; - } - - LABEL_222(flags, ref v13); - - return; - } - - if ((flags & AnimationFlags.Unknown1) != 0) - { - if (v13 == 21) - { - v13 = 10; - } - - LABEL_222(flags, ref v13); - - return; - } - - if ((flags & AnimationFlags.CalculateOffsetByPeopleGroup) == 0) - { - //LABEL_222: - LABEL_222(flags, ref v13); - - return; - } - - switch (v13) - { - case 0: - v13 = 0; - - break; - - case 2: - v13 = 21; - LABEL_222(flags, ref v13); - - return; - - case 3: - v13 = 22; - LABEL_222(flags, ref v13); - - return; - - case 4: - case 9: - v13 = 9; - LABEL_222(flags, ref v13); - - return; - - case 5: - v13 = 11; - LABEL_222(flags, ref v13); - - return; - - case 6: - v13 = 13; - LABEL_222(flags, ref v13); - - return; - - case 7: - v13 = 18; - LABEL_222(flags, ref v13); - - return; - - case 8: - v13 = 19; - LABEL_222(flags, ref v13); - - return; - - case 10: - case 21: - v13 = 20; - LABEL_222(flags, ref v13); - - return; - - case 11: - v13 = 3; - LABEL_222(flags, ref v13); - - return; - - case 12: - case 14: - v13 = 16; - LABEL_222(flags, ref v13); - - return; - - case 13: - //LABEL_202: - v13 = 17; - LABEL_222(flags, ref v13); - - return; - - case 15: - case 16: - v13 = 30; - LABEL_222(flags, ref v13); - - return; - - case 17: - v13 = 5; - LABEL_222(flags, ref v13); - - return; - - case 18: - v13 = 6; - LABEL_222(flags, ref v13); - - return; - - case 19: - //LABEL_201: - v13 = 1; - LABEL_222(flags, ref v13); - - return; - } - } - - v13 = 4; - - LABEL_222(flags, ref v13); - } - - public static byte GetGroupForAnimation( - Mobile mobile, - ushort checkGraphic = 0, - bool isParent = false - ) - { - ushort graphic = checkGraphic; - - if (graphic == 0) - { - graphic = mobile.GetGraphicForAnimation(); - } - - if (graphic >= Client.Game.Animations.MaxAnimationCount) - { - return 0; - } - - AnimationGroupsType originalType = Client.Game.Animations.GetAnimType(graphic); - Client.Game.Animations.ConvertBodyIfNeeded(ref graphic, isParent); - AnimationGroupsType type = Client.Game.Animations.GetAnimType(graphic); - AnimationFlags flags = Client.Game.Animations.GetAnimFlags(graphic); - - bool uop = (flags & AnimationFlags.UseUopAnimation) != 0; - - if (mobile.AnimationFromServer && mobile._animationGroup != 0xFF) - { - ushort v13 = mobile._animationGroup; - - if (v13 == 12) - { - if ( - !( - type == AnimationGroupsType.Human - || type == AnimationGroupsType.Equipment - || (flags & AnimationFlags.Unknown1000) != 0 - ) - ) - { - if (type != AnimationGroupsType.Monster) - { - if ( - type == AnimationGroupsType.Human - || type == AnimationGroupsType.Equipment - ) - { - v13 = 16; - } - else - { - v13 = 5; - } - } - else - { - v13 = 4; - } - } - } - - if (type != AnimationGroupsType.Monster) - { - if (type != AnimationGroupsType.SeaMonster) - { - if (type == AnimationGroupsType.Animal) - { - if (IsReplacedObjectAnimation(0, v13)) - { - originalType = AnimationGroupsType.Unknown; - } - - if (v13 > 12) - { - switch (v13) - { - case 23: - v13 = 0; - - break; - - case 24: - v13 = 1; - - break; - - case 26: - - if ( - !Client.Game.Animations.AnimationExists(graphic, 26) - || ( - mobile.InWarMode - && Client.Game.Animations.AnimationExists( - graphic, - 9 - ) - ) - ) - { - v13 = 9; - } - - break; - - case 28: - - v13 = (ushort)( - Client.Game.Animations.AnimationExists(graphic, 10) - ? 10 - : 5 - ); - - break; - - default: - v13 = 2; - - break; - } - } - - //if (v13 > 12) - // v13 = 0; // 2 - } - else - { - if (IsReplacedObjectAnimation(1, v13)) - { - // LABEL_190: - - LABEL_190(flags, ref v13); - - return (byte)v13; - } - } - } - else - { - if (IsReplacedObjectAnimation(3, v13)) - { - originalType = AnimationGroupsType.Unknown; - } - - if (v13 > 8) - { - v13 = 2; - } - } - } - else - { - if (IsReplacedObjectAnimation(2, v13)) - { - originalType = AnimationGroupsType.Unknown; - } - - if (!Client.Game.Animations.AnimationExists(graphic, (byte)v13)) - { - v13 = 1; - } - - if ((flags & AnimationFlags.UseUopAnimation) != 0) - { - // do nothing? - } - else if (v13 > 21) - { - v13 = 1; - } - } - - if (originalType == AnimationGroupsType.Unknown) - { - LABEL_190(flags, ref v13); - - return (byte)v13; - } - - if (originalType != 0) - { - if ( - originalType == AnimationGroupsType.Animal - && type == AnimationGroupsType.Monster - ) - { - switch (v13) - { - case 0: - v13 = 0; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 1: - v13 = 19; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 3: - v13 = 11; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 5: - v13 = 4; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 6: - v13 = 5; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 7: - case 11: - v13 = 10; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 8: - v13 = 2; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 9: - v13 = 17; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 10: - v13 = 18; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 12: - v13 = 3; - LABEL_190(flags, ref v13); - - return (byte)v13; - } - - // LABEL_187 - v13 = 1; - } - - LABEL_190(flags, ref v13); - - return (byte)v13; - } - - switch (type) - { - case AnimationGroupsType.Human: - - switch (v13) - { - case 0: - v13 = 0; - - goto LABEL_189; - - case 2: - v13 = 21; - - goto LABEL_189; - - case 3: - v13 = 22; - - goto LABEL_189; - - case 4: - case 9: - v13 = 9; - - goto LABEL_189; - - case 5: - //LABEL_163: - v13 = 11; - - goto LABEL_189; - - case 6: - v13 = 13; - - goto LABEL_189; - - case 7: - //LABEL_165: - v13 = 18; - - goto LABEL_189; - - case 8: - //LABEL_172: - v13 = 19; - - goto LABEL_189; - - case 10: - case 21: - v13 = 20; - - goto LABEL_189; - - case 12: - case 14: - v13 = 16; - - goto LABEL_189; - - case 13: - //LABEL_164: - v13 = 17; - - goto LABEL_189; - - case 15: - case 16: - v13 = 30; - - goto LABEL_189; - - case 17: - v13 = 5; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 18: - v13 = 6; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 19: - v13 = 1; - LABEL_190(flags, ref v13); - - return (byte)v13; - } - - //LABEL_161: - v13 = 4; - - goto LABEL_189; - - case AnimationGroupsType.Animal: - - switch (v13) - { - case 0: - v13 = 0; - - goto LABEL_189; - - case 2: - v13 = 8; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 3: - v13 = 12; - - goto LABEL_189; - - case 4: - case 6: - case 7: - case 8: - case 9: - case 12: - case 13: - case 14: - v13 = 5; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 5: - v13 = 6; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 10: - case 21: - v13 = 7; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 11: - v13 = 3; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case 17: - //LABEL_170: - v13 = 9; - - goto LABEL_189; - - case 18: - //LABEL_162: - v13 = 10; - - goto LABEL_189; - - case 19: - v13 = 1; - LABEL_190(flags, ref v13); - - return (byte)v13; - } - - v13 = 2; - LABEL_190(flags, ref v13); - - return (byte)v13; - - case AnimationGroupsType.SeaMonster: - - switch (v13) - { - case 0: - //LABEL_182: - v13 = 0; - - goto LABEL_189; - - case 2: - case 3: - //LABEL_178: - v13 = 8; - - goto LABEL_189; - - case 4: - case 6: - case 7: - case 8: - case 9: - case 12: - case 13: - case 14: - //LABEL_183: - v13 = 5; - - goto LABEL_189; - - case 5: - //LABEL_184: - v13 = 6; - - goto LABEL_189; - - case 10: - case 21: - //LABEL_185: - v13 = 7; - - goto LABEL_189; - - case 17: - //LABEL_186: - v13 = 3; - - goto LABEL_189; - - case 18: - v13 = 4; - - goto LABEL_189; - - case 19: - LABEL_190(flags, ref v13); - - return (byte)v13; - } - - v13 = 2; - LABEL_190(flags, ref v13); - - return (byte)v13; - - default: - LABEL_189: - - LABEL_190(flags, ref v13); - - return (byte)v13; - } - - // LABEL_188 - v13 = 2; - - LABEL_190(flags, ref v13); - - return (byte)v13; - } - - byte result = mobile._animationGroup; - - bool isWalking = mobile.IsWalking; - bool isRun = mobile.IsRunning; - - if (mobile.Steps.Count != 0) - { - isWalking = true; - ref Step step = ref mobile.Steps.Front(); - isRun = step.Run; - } - - switch (type) - { - case AnimationGroupsType.Animal: - - if ((flags & AnimationFlags.CalculateOffsetLowGroupExtended) != 0) - { - CalculateHight(graphic, mobile, flags, isRun, isWalking, ref result); - } - else - { - if (!isWalking) - { - if (result == 0xFF) - { - if ((flags & AnimationFlags.UseUopAnimation) != 0) - { - if ( - mobile.InWarMode - && Client.Game.Animations.AnimationExists(graphic, 1) - ) - { - result = 1; - } - else - { - result = 25; - } - } - else - { - result = 2; - } - } - } - else if (isRun) - { - if ((flags & AnimationFlags.UseUopAnimation) != 0) - { - result = 24; - } - else - { - result = Client.Game.Animations.AnimationExists(graphic, 1) - ? (byte)1 - : (byte)2; - } - } - else if ( - (flags & AnimationFlags.UseUopAnimation) != 0 - && ( - !mobile.InWarMode - || !Client.Game.Animations.AnimationExists(graphic, 0) - ) - ) - { - result = 22; - } - else - { - result = 0; - } - } - - break; - - case AnimationGroupsType.Monster: - CalculateHight(graphic, mobile, flags, isRun, isWalking, ref result); - - break; - - case AnimationGroupsType.SeaMonster: - - if (!isWalking) - { - if (result == 0xFF) - { - result = 2; - } - } - else if (isRun) - { - result = 1; - } - else - { - result = 0; - } - - break; - - default: - { - Item hand2 = mobile.FindItemByLayer(Layer.TwoHanded); - - if (!isWalking) - { - if (result == 0xFF) - { - bool haveLightAtHand2 = - hand2 != null - && hand2.ItemData.IsLight - && hand2.ItemData.AnimID == graphic; - - if (mobile.IsMounted) - { - if (haveLightAtHand2) - { - result = 28; - } - else - { - result = 25; - } - } - else if (mobile.IsGargoyle && mobile.IsFlying) // TODO: what's up when it is dead? - { - if (mobile.InWarMode) - { - result = 65; - } - else - { - result = 64; - } - } - else if (!mobile.InWarMode || mobile.IsDead) - { - if (haveLightAtHand2) - { - // TODO: UOP EQUIPMENT ? - result = 0; - } - else - { - if ( - uop - && type == AnimationGroupsType.Equipment - && Client.Game.Animations.AnimationExists(graphic, 37) - ) - { - result = 37; - } - else - { - result = 4; - } - } - } - else if (haveLightAtHand2) - { - // TODO: UOP EQUIPMENT ? - - result = 2; - } - else - { - unsafe - { - ushort* handAnimIDs = stackalloc ushort[2]; - Item hand1 = mobile.FindItemByLayer(Layer.OneHanded); - - if (hand1 != null) - { - handAnimIDs[0] = hand1.ItemData.AnimID; - } - - if (hand2 != null) - { - handAnimIDs[1] = hand2.ItemData.AnimID; - } - - if (hand1 == null) - { - if (hand2 != null) - { - if ( - uop - && type == AnimationGroupsType.Equipment - && !Client.Game.Animations.AnimationExists( - graphic, - 7 - ) - ) - { - result = 8; - } - else - { - result = 7; - } - - for (int i = 0; i < 2; i++) - { - if ( - handAnimIDs[i] >= 0x0263 - && handAnimIDs[i] <= 0x028B - ) - { - for ( - int k = 0; - k < HANDS_BASE_ANIMID.Length; - k++ - ) - { - if (handAnimIDs[i] == HANDS_BASE_ANIMID[k]) - { - result = 8; - i = 2; - - break; - } - } - } - } - } - else if (mobile.IsGargoyle && mobile.IsFlying) - { - result = 64; - } - else - { - result = 7; - } - } - else - { - result = 7; - } - } - } - } - } - else if (mobile.IsMounted) - { - if (isRun) - { - result = 24; - } - else - { - result = 23; - } - } - //else if (EquippedGraphic0x3E96) - //{ - - //} - else if (isRun || !mobile.InWarMode || mobile.IsDead) - { - if ((flags & AnimationFlags.UseUopAnimation) != 0) - { - // i'm not sure here if it's necessary the isgargoyle - if (mobile.IsGargoyle && mobile.IsFlying) - { - if (isRun) - { - result = 63; - } - else - { - result = 62; - } - } - else - { - if (isRun && Client.Game.Animations.AnimationExists(graphic, 24)) - { - result = 24; - } - else - { - if (isRun) - { - if ( - uop - && type == AnimationGroupsType.Equipment - && !Client.Game.Animations.AnimationExists(graphic, 2) - ) - { - result = 3; - } - else - { - result = 2; - - if (mobile.IsGargoyle) - { - hand2 = mobile.FindItemByLayer(Layer.OneHanded); - } - } - } - else - { - if ( - uop - && type == AnimationGroupsType.Equipment - && !Client.Game.Animations.AnimationExists(graphic, 0) - ) - { - result = 1; - } - else - { - result = 0; - } - } - } - } - } - else - { - if (isRun) - { - result = (byte)(hand2 != null ? 3 : 2); - } - else - { - result = (byte)(hand2 != null ? 1 : 0); - } - } - - if (hand2 != null) - { - ushort hand2Graphic = hand2.ItemData.AnimID; - - if (hand2Graphic < 0x0240 || hand2Graphic > 0x03E1) - { - if (mobile.IsGargoyle && mobile.IsFlying) - { - if (isRun) - { - result = 63; - } - else - { - result = 62; - } - } - else - { - if (isRun) - { - result = 3; - } - else - { - result = 1; - } - } - } - else - { - for (int i = 0; i < HAND2_BASE_ANIMID.Length; i++) - { - if (HAND2_BASE_ANIMID[i] == hand2Graphic) - { - if (mobile.IsGargoyle && mobile.IsFlying) - { - if (isRun) - { - result = 63; - } - else - { - result = 62; - } - } - else - { - if (isRun) - { - result = 3; - } - else - { - result = 1; - } - } - - break; - } - } - } - } - } - else if (mobile.IsGargoyle && mobile.IsFlying) - { - result = 62; - } - else - { - result = 15; - } - - break; - } - } - - return result; - } - - public static bool IsReplacedObjectAnimation(byte anim, ushort v13) - { - if (anim < AnimationsLoader.Instance.GroupReplaces.Length) - { - foreach (var tuple in AnimationsLoader.Instance.GroupReplaces[anim]) - { - if (tuple.Item1 == v13) - { - return tuple.Item2 != 0xFF; - } - } - } - - return false; - } - - public static byte GetReplacedObjectAnimation(ushort graphic, ushort index) - { - ushort getReplacedGroup(List<(ushort, byte)> list, ushort idx, ushort walkIdx) - { - foreach (var item in list) - { - if (item.Item1 == idx) - { - if (item.Item2 == 0xFF) - { - return walkIdx; - } - - return item.Item2; - } - } - - return idx; - } - - AnimationGroups group = AnimationsLoader.Instance.GetGroupIndex( - graphic, - Client.Game.Animations.GetAnimType(graphic) - ); - - if (group == AnimationGroups.Low) - { - return (byte)( - getReplacedGroup( - AnimationsLoader.Instance.GroupReplaces[0], - index, - (ushort)LowAnimationGroup.Walk - ) % (ushort)LowAnimationGroup.AnimationCount - ); - } - - if (group == AnimationGroups.People) - { - return (byte)( - getReplacedGroup( - AnimationsLoader.Instance.GroupReplaces[1], - index, - (ushort)PeopleAnimationGroup.WalkUnarmed - ) % (ushort)PeopleAnimationGroup.AnimationCount - ); - } - - return (byte)(index % (ushort)HighAnimationGroup.AnimationCount); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte GetObjectNewAnimation( - Mobile mobile, - ushort type, - ushort action, - byte mode - ) - { - if (mobile.Graphic >= Client.Game.Animations.MaxAnimationCount) - { - return 0; - } - - switch (type) - { - case 0: - return GetObjectNewAnimationType_0(mobile, action, mode); - - case 1: - case 2: - return GetObjectNewAnimationType_1_2(mobile, action, mode); - - case 3: - return GetObjectNewAnimationType_3(mobile, action, mode); - - case 4: - return GetObjectNewAnimationType_4(mobile, action, mode); - - case 5: - return GetObjectNewAnimationType_5(mobile, action, mode); - - case 6: - case 14: - return GetObjectNewAnimationType_6_14(mobile, action, mode); - - case 7: - return GetObjectNewAnimationType_7(mobile, action, mode); - - case 8: - return GetObjectNewAnimationType_8(mobile, action, mode); - - case 9: - return GetObjectNewAnimationType_9(mobile, action, mode); - case 10: - return GetObjectNewAnimationType_10(mobile, action, mode); - - case 11: - return GetObjectNewAnimationType_11(mobile, action, mode); - } - - return 0; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TestStepNoChangeDirection(Mobile mob, byte group) - { - switch ((PeopleAnimationGroup)group) - { - case PeopleAnimationGroup.OnmountRideFast: - case PeopleAnimationGroup.RunUnarmed: - case PeopleAnimationGroup.RunArmed: - case PeopleAnimationGroup.OnmountRideSlow: - case PeopleAnimationGroup.WalkWarmode: - case PeopleAnimationGroup.WalkArmed: - case PeopleAnimationGroup.WalkUnarmed: - - if (mob.Steps.Count != 0) - { - ref Step s = ref mob.Steps.Front(); - - if (s.X != mob.X || s.Y != mob.Y) - { - return true; - } - } - - break; - } - - return false; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static byte GetObjectNewAnimationType_0(Mobile mobile, ushort action, byte mode) - { - if (action <= 10) - { - AnimationFlags flags = Client.Game.Animations.GetAnimFlags(mobile.Graphic); - AnimationGroupsType type = AnimationGroupsType.Monster; - - if ((flags & AnimationFlags.Found) != 0) - { - type = Client.Game.Animations.GetAnimType(mobile.Graphic); - } - - if (type == AnimationGroupsType.Monster) - { - switch (mode % 4) - { - case 1: - return 5; - - case 2: - return 6; - - case 3: - - if ((flags & AnimationFlags.Unknown1) != 0) - { - return 12; - } - - goto case 0; - - case 0: - return 4; - } - } - else if (type == AnimationGroupsType.SeaMonster) - { - if (mode % 2 != 0) - { - return 6; - } - - return 5; - } - else if (type != AnimationGroupsType.Animal) - { - if (mobile.IsMounted) - { - if (action > 0) - { - if (action == 1) - { - return 27; - } - - if (action == 2) - { - return 28; - } - - return 26; - } - - return 29; - } - - switch (action) - { - default: - if ( - mobile.IsGargoyle - && mobile.IsFlying - && Client.Game.Animations.AnimationExists(mobile.Graphic, 71) - ) - { - return 71; - } - else if (Client.Game.Animations.AnimationExists(mobile.Graphic, 31)) - { - return 31; - } - - break; - - case 1: - return 18; - - case 2: - return 19; - - case 6: - return 12; - - case 7: - if ( - mobile.IsGargoyle - && mobile.IsFlying - && Client.Game.Animations.AnimationExists(mobile.Graphic, 72) - ) - { - return 72; - } - - return 13; - - case 8: - return 14; - - case 3: - return 11; - - case 4: - return 9; - - case 5: - return 10; - } - } - - if ((flags & AnimationFlags.Use2IfHittedWhileRunning) != 0) - { - return 2; - } - - if (mode % 2 != 0 && Client.Game.Animations.AnimationExists(mobile.Graphic, 6)) - { - return 6; - } - - return 5; - } - - return 0; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static byte GetObjectNewAnimationType_1_2(Mobile mobile, ushort action, byte mode) - { - AnimationFlags flags = Client.Game.Animations.GetAnimFlags(mobile.Graphic); - AnimationGroupsType type = AnimationGroupsType.Monster; - - if ((flags & AnimationFlags.Found) != 0) - { - type = Client.Game.Animations.GetAnimType(mobile.Graphic); - } - - if (type != AnimationGroupsType.Monster) - { - if (type <= AnimationGroupsType.Animal || mobile.IsMounted) - { - return 0xFF; - } - - return 30; - } - - if (mode % 2 != 0) - { - return 15; - } - - return 16; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static byte GetObjectNewAnimationType_3(Mobile mobile, ushort action, byte mode) - { - AnimationFlags flags = Client.Game.Animations.GetAnimFlags(mobile.Graphic); - AnimationGroupsType type = AnimationGroupsType.Monster; - - if ((flags & AnimationFlags.Found) != 0) - { - type = Client.Game.Animations.GetAnimType(mobile.Graphic); - } - - if (type != AnimationGroupsType.Monster) - { - if (type == AnimationGroupsType.SeaMonster) - { - return 8; - } - - if (type == AnimationGroupsType.Animal) - { - if (mode % 2 != 0) - { - return 21; - } - - return 22; - } - - if (mode % 2 != 0) - { - return 8; - } - - return 12; - } - - if (mode % 2 != 0) - { - return 2; - } - - return 3; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static byte GetObjectNewAnimationType_4(Mobile mobile, ushort action, byte mode) - { - AnimationFlags flags = Client.Game.Animations.GetAnimFlags(mobile.Graphic); - AnimationGroupsType type = AnimationGroupsType.Monster; - - if ((flags & AnimationFlags.Found) != 0) - { - type = Client.Game.Animations.GetAnimType(mobile.Graphic); - } - - if (type != AnimationGroupsType.Monster) - { - if (type > AnimationGroupsType.Animal) - { - if ( - mobile.IsGargoyle - && mobile.IsFlying - && Client.Game.Animations.AnimationExists(mobile.Graphic, 77) - ) - { - return 77; - } - - if (mobile.IsMounted) - { - return 0xFF; - } - - return 20; - } - - return 7; - } - - return 10; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static byte GetObjectNewAnimationType_5(Mobile mobile, ushort action, byte mode) - { - AnimationFlags flags = Client.Game.Animations.GetAnimFlags(mobile.Graphic); - AnimationGroupsType type = AnimationGroupsType.Monster; - - if ((flags & AnimationFlags.Found) != 0) - { - type = Client.Game.Animations.GetAnimType(mobile.Graphic); - } - - if (type <= AnimationGroupsType.SeaMonster) - { - if (mode % 2 != 0) - { - return 18; - } - - return 17; - } - - if (type != AnimationGroupsType.Animal) - { - if (mobile.IsMounted) - { - return 0xFF; - } - - if (mode % 2 != 0) - { - return 6; - } - - return 5; - } - - switch (mode % 3) - { - case 1: - return 10; - - case 2: - return 3; - } - - return 9; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static byte GetObjectNewAnimationType_6_14(Mobile mobile, ushort action, byte mode) - { - AnimationFlags flags = Client.Game.Animations.GetAnimFlags(mobile.Graphic); - AnimationGroupsType type = AnimationGroupsType.Monster; - - if ((flags & AnimationFlags.Found) != 0) - { - type = Client.Game.Animations.GetAnimType(mobile.Graphic); - } - - if (type != AnimationGroupsType.Monster) - { - if (type != AnimationGroupsType.SeaMonster) - { - if (type == AnimationGroupsType.Animal) - { - return 3; - } - - if (mobile.IsMounted) - { - return 0xFF; - } - - return 34; - } - - return 5; - } - - return 11; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static byte GetObjectNewAnimationType_7(Mobile mobile, ushort action, byte mode) - { - if (mobile.IsMounted) - { - return 0xFF; - } - - if (action > 0) - { - if (action == 1) - { - return 33; - } - } - else - { - return 32; - } - - return 0; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static byte GetObjectNewAnimationType_8(Mobile mobile, ushort action, byte mode) - { - AnimationFlags flags = Client.Game.Animations.GetAnimFlags(mobile.Graphic); - AnimationGroupsType type = AnimationGroupsType.Monster; - - if ((flags & AnimationFlags.Found) != 0) - { - type = Client.Game.Animations.GetAnimType(mobile.Graphic); - } - - if (type != AnimationGroupsType.Monster) - { - if (type != AnimationGroupsType.SeaMonster) - { - if (type == AnimationGroupsType.Animal) - { - return 9; - } - - return mobile.IsMounted ? (byte)0xFF : (byte)33; - } - - return 3; - } - - return 11; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static byte GetObjectNewAnimationType_9(Mobile mobile, ushort action, byte mode) - { - AnimationFlags flags = Client.Game.Animations.GetAnimFlags(mobile.Graphic); - AnimationGroupsType type = AnimationGroupsType.Monster; - - if ((flags & AnimationFlags.Found) != 0) - { - type = Client.Game.Animations.GetAnimType(mobile.Graphic); - } - - if (type != AnimationGroupsType.Monster) - { - if (mobile.IsGargoyle) - { - if (action == 0) - { - return 60; - } - } - - return 0xFF; - } - - return 20; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static byte GetObjectNewAnimationType_10(Mobile mobile, ushort action, byte mode) - { - AnimationFlags flags = Client.Game.Animations.GetAnimFlags(mobile.Graphic); - AnimationGroupsType type = AnimationGroupsType.Monster; - - if ((flags & AnimationFlags.Found) != 0) - { - type = Client.Game.Animations.GetAnimType(mobile.Graphic); - } - - if (type != AnimationGroupsType.Monster) - { - if (mobile.IsGargoyle) - { - if (action == 0) - { - return 61; - } - } - - return 0xFF; - } - - return 20; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static byte GetObjectNewAnimationType_11(Mobile mobile, ushort action, byte mode) - { - AnimationFlags flags = Client.Game.Animations.GetAnimFlags(mobile.Graphic); - AnimationGroupsType type = AnimationGroupsType.Monster; - - if ((flags & AnimationFlags.Found) != 0) - { - type = Client.Game.Animations.GetAnimType(mobile.Graphic); - } - - if (type != AnimationGroupsType.Monster) - { - if (type >= AnimationGroupsType.Animal) - { - if (mobile.IsMounted) - { - return 0xFF; - } - - switch (action) - { - case 1: - case 2: - if (mobile.IsGargoyle && mobile.IsFlying) - { - return 76; - } - - return 17; - } - - if (mobile.IsGargoyle && mobile.IsFlying) - { - return 75; - } - - return 16; - } - - return 5; - } - - return 12; - } - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/MovingEffect.cs b/src/ClassicUO.Client/Game/GameObjects/MovingEffect.cs deleted file mode 100644 index 3b3e117d9..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/MovingEffect.cs +++ /dev/null @@ -1,257 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Game.Managers; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.GameObjects -{ - internal sealed class MovingEffect : GameEffect - { - public MovingEffect - ( - EffectManager manager, - uint src, - uint trg, - ushort xSource, - ushort ySource, - sbyte zSource, - ushort xTarget, - ushort yTarget, - sbyte zTarget, - ushort graphic, - ushort hue, - bool fixedDir, - int duration, - byte speed - ) : base(manager, graphic, hue, 0, speed) - { - FixedDir = fixedDir; - - // we override interval time with speed - var d = Constants.ITEM_EFFECT_ANIMATION_DELAY * 2; - - IntervalInMs = (uint)(d + (speed * d)); - - // moving effects want a +22 to the X - Offset.X += 22; - - Entity source = World.Get(src); - - if (SerialHelper.IsValid(src) && source != null) - { - SetSource(source); - } - else - { - SetSource(xSource, ySource, zSource); - } - - - Entity target = World.Get(trg); - - if (SerialHelper.IsValid(trg) && target != null) - { - SetTarget(target); - } - else - { - SetTarget(xTarget, yTarget, zTarget); - } - } - - public readonly bool FixedDir; - - - public override void Update() - { - base.Update(); - UpdateOffset(); - } - - - private void UpdateOffset() - { - if (Target != null && Target.IsDestroyed) - { - TargetX = Target.X; - TargetY = Target.Y; - TargetZ = Target.Z; - } - - int playerX = World.Player.X; - int playerY = World.Player.Y; - int playerZ = World.Player.Z; - - (int sX, int sY, int sZ) = GetSource(); - int offsetSourceX = sX - playerX; - int offsetSourceY = sY - playerY; - int offsetSourceZ = sZ - playerZ; - - (int tX, int tY, int tZ) = GetTarget(); - int offsetTargetX = tX - playerX; - int offsetTargetY = tY - playerY; - int offsetTargetZ = tZ - playerZ; - - Vector2 source = new Vector2((offsetSourceX - offsetSourceY) * 22, (offsetSourceX + offsetSourceY) * 22 - offsetSourceZ * 4); - - source.X += Offset.X; - source.Y += Offset.Y; - - Vector2 target = new Vector2((offsetTargetX - offsetTargetY) * 22, (offsetTargetX + offsetTargetY) * 22 - offsetTargetZ * 4); - - var offset = target - source; - var distance = offset.Length(); - var frameIndependentSpeed = IntervalInMs * Time.Delta; - Vector2 s0; - - if (distance > frameIndependentSpeed) - { - offset.Normalize(); - s0 = offset * frameIndependentSpeed; - } - else - { - s0 = target; - } - - - if (distance <= 22) - { - RemoveMe(); - - return; - } - - int newOffsetX = (int) (source.X / 22f); - int newOffsetY = (int) (source.Y / 22f); - - TileOffsetOnMonitorToXY(ref newOffsetX, ref newOffsetY, out int newCoordX, out int newCoordY); - - int newX = playerX + newCoordX; - int newY = playerY + newCoordY; - - if (newX == tX && newY == tY) - { - RemoveMe(); - - return; - } - - - IsPositionChanged = true; - AngleToTarget = (float) Math.Atan2(-offset.Y, -offset.X); - - if (newX != sX || newY != sY) - { - // TODO: Z is wrong. We have to calculate an average - SetSource((ushort) newX, (ushort) newY, (sbyte)sZ); - - Vector2 nextSource = new Vector2((newCoordX - newCoordY) * 22, (newCoordX + newCoordY) * 22 - offsetSourceZ * 4); - - Offset.X = source.X - nextSource.X; - Offset.Y = source.Y - nextSource.Y; - } - - Offset.X += s0.X; - Offset.Y += s0.Y; - } - - - private void RemoveMe() - { - CreateExplosionEffect(); - - Destroy(); - } - - private static void TileOffsetOnMonitorToXY(ref int ofsX, ref int ofsY, out int x, out int y) - { - y = 0; - - if (ofsX == 0) - { - x = y = ofsY >> 1; - } - else if (ofsY == 0) - { - x = ofsX >> 1; - y = -x; - } - else - { - int absX = Math.Abs(ofsX); - int absY = Math.Abs(ofsY); - x = ofsX; - - if (ofsY > ofsX) - { - if (ofsX < 0 && ofsY < 0) - { - y = absX - absY; - } - else if (ofsX > 0 && ofsY > 0) - { - y = absY - absX; - } - } - else if (ofsX > ofsY) - { - if (ofsX < 0 && ofsY < 0) - { - y = -(absY - absX); - } - else if (ofsX > 0 && ofsY > 0) - { - y = -(absX - absY); - } - } - - if (y == 0 && ofsY != ofsX) - { - if (ofsY < 0) - { - y = -(absX + absY); - } - else - { - y = absX + absY; - } - } - - y /= 2; - x += y; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/GameObjects/Multi.cs b/src/ClassicUO.Client/Game/GameObjects/Multi.cs deleted file mode 100644 index 6e3c69df3..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/Multi.cs +++ /dev/null @@ -1,118 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Assets; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.GameObjects -{ - public sealed partial class Multi : GameObject - { - private static readonly QueuedPool _pool = new QueuedPool - ( - Constants.PREDICTABLE_MULTIS, - m => - { - m.IsDestroyed = false; - m.AlphaHue = 0; - m.FoliageIndex = 0; - m.IsHousePreview = false; - m.MultiOffsetX = m.MultiOffsetY = m.MultiOffsetZ = 0; - m.IsCustom = false; - m.State = 0; - m.IsMovable = false; - m.Offset = Vector3.Zero; - } - ); - private ushort _originalGraphic; - - - public string Name => ItemData.Name; - - public ref StaticTiles ItemData => ref TileDataLoader.Instance.StaticData[Graphic]; - public bool IsCustom; - public bool IsVegetation; - public int MultiOffsetX; - public int MultiOffsetY; - public int MultiOffsetZ; - public bool IsMovable; - public CUSTOM_HOUSE_MULTI_OBJECT_FLAGS State = 0; - - - public static Multi Create(ushort graphic) - { - Multi m = _pool.GetOne(); - m.Graphic = m._originalGraphic = graphic; - m.UpdateGraphicBySeason(); - m.AllowedToDraw = CanBeDrawn(m.Graphic); - - if (m.ItemData.Height > 5 || m.ItemData.Height == 0) - { - m._canBeTransparent = 1; - } - else if (m.ItemData.IsRoof || m.ItemData.IsSurface && m.ItemData.IsBackground || m.ItemData.IsWall) - { - m._canBeTransparent = 1; - } - else if (m.ItemData.Height == 5 && m.ItemData.IsSurface && !m.ItemData.IsBackground) - { - m._canBeTransparent = 1; - } - else - { - m._canBeTransparent = 0; - } - - return m; - } - - public override void UpdateGraphicBySeason() - { - Graphic = SeasonManager.GetSeasonGraphic(World.Season, _originalGraphic); - IsVegetation = StaticFilters.IsVegetation(Graphic); - } - - public override void Destroy() - { - if (IsDestroyed) - { - return; - } - - base.Destroy(); - _pool.ReturnOne(this); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/GameObjects/PlayerMobile.cs b/src/ClassicUO.Client/Game/GameObjects/PlayerMobile.cs deleted file mode 100644 index 6377cd64c..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/PlayerMobile.cs +++ /dev/null @@ -1,1777 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Network; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using System.Collections.Generic; -using System.Linq; - -namespace ClassicUO.Game.GameObjects -{ - public class PlayerMobile : Mobile - { - private readonly Dictionary _buffIcons = new Dictionary(); - - private static SpellVisualRangeManager.CastTimerProgressBar castTimer; - - public PlayerMobile(uint serial) : base(serial) - { - Skills = new Skill[SkillsLoader.Instance.SkillsCount]; - - for (int i = 0; i < Skills.Length; i++) - { - SkillEntry skill = SkillsLoader.Instance.Skills[i]; - Skills[i] = new Skill(skill.Name, skill.Index, skill.HasAction); - } - - Skill.SkillValueChangedEvent += (s, e) => - { - if (ProfileManager.CurrentProfile.DisplaySkillBarOnChange) - { - SkillProgressBar.QueManager.AddSkill(e.Index); - } - }; - - UIManager.Add(castTimer = new SpellVisualRangeManager.CastTimerProgressBar()); - } - - public Skill[] Skills { get; } - public override bool InWarMode { get; set; } - public IReadOnlyDictionary BuffIcons => _buffIcons; - - public ref Ability PrimaryAbility => ref Abilities[0]; - public ref Ability SecondaryAbility => ref Abilities[1]; - protected override bool IsWalking => LastStepTime > Time.Ticks - Constants.PLAYER_WALKING_DELAY; - - internal WalkerManager Walker { get; } = new WalkerManager(); - public Ability[] Abilities = new Ability[2] - { - Ability.Invalid, Ability.Invalid - }; - - //private bool _lastRun, _lastMount; - //private int _lastDir = -1, _lastDelta, _lastStepTime; - - - public readonly HashSet AutoOpenedCorpses = new HashSet(); - public readonly HashSet ManualOpenedCorpses = new HashSet(); - - public short ColdResistance; - public short DamageIncrease; - public short DamageMax; - public short DamageMin; - public long DeathScreenTimer; - public short DefenseChanceIncrease; - public Lock DexLock; - public ushort Dexterity; - public short DexterityIncrease; - public short EnergyResistance; - public short EnhancePotions; - public short FasterCasting; - public short FasterCastRecovery; - public short FireResistance; - public byte Followers; - public byte FollowersMax; - public uint Gold; - public short HitChanceIncrease; - public short HitPointsIncrease; - public short HitPointsRegeneration; - public ushort Intelligence; - public short IntelligenceIncrease; - public Lock IntLock; - public short LowerManaCost; - public short LowerReagentCost; - public ushort Luck; - public short ManaIncrease; - public short ManaRegeneration; - public short MaxColdResistence; - public short MaxDefenseChanceIncrease; - public short MaxEnergyResistence; - public short MaxFireResistence; - public short MaxHitPointsIncrease; - public short MaxManaIncrease; - public short MaxPhysicResistence; - public short MaxPoisonResistence; - public short MaxStaminaIncrease; - public short PhysicalResistance; - public short PoisonResistance; - public short ReflectPhysicalDamage; - public short SpellDamageIncrease; - public short StaminaIncrease; - public short StaminaRegeneration; - public short StatsCap; - public ushort Strength; - public short StrengthIncrease; - public Lock StrLock; - public short SwingSpeedIncrease; - public uint TithingPoints; - public ushort Weight; - public ushort WeightMax; - - public Item FindBandage() - { - Item backpack = FindItemByLayer(Layer.Backpack); - Item item = null; - - if (backpack != null) - { - item = backpack.FindItem(0x0E21); - } - - return item; - } - - public Item FindItemByGraphic(ushort graphic) - { - Item backpack = FindItemByLayer(Layer.Backpack); - - if (backpack != null) - { - return FindItemInContainerRecursive(backpack, graphic); - } - - return null; - } - - public Item FindItemByCliloc(int cliloc) - { - Item backpack = FindItemByLayer(Layer.Backpack); - - if (backpack != null) - { - return FindItemByClilocInContainerRecursive(backpack, cliloc); - } - - return null; - } - - private Item FindItemInContainerRecursive(Item container, ushort graphic) - { - Item found = null; - - if (container != null) - { - for (LinkedObject i = container.Items; i != null; i = i.Next) - { - Item item = (Item)i; - - if (item.Graphic == graphic) - { - return item; - } - - if (!item.IsEmpty) - { - found = FindItemInContainerRecursive(item, graphic); - - if (found != null && found.Graphic == graphic) - { - return found; - } - } - } - } - - return found; - } - - private Item FindItemByClilocInContainerRecursive(Item container, int cliloc) - { - Item found = null; - - if (container != null) - { - for (LinkedObject i = container.Items; i != null; i = i.Next) - { - Item item = (Item)i; - - - if (cliloc == World.OPL.GetNameCliloc(item.Serial)) - { - return item; - } - - if (!item.IsEmpty) - { - found = FindItemByClilocInContainerRecursive(item, cliloc); - - if (found != null && cliloc == World.OPL.GetNameCliloc(found.Serial)) - { - return found; - } - } - } - } - - return found; - } - - public Item FindPreferredItemByCliloc(System.Span clilocs) - { - Item item = null; - - for (int i = 0; i < clilocs.Length; i++) - { - item = World.Player.FindItemByCliloc(clilocs[i]); - - if (item != null) - { - break; - } - } - - return item; - } - - public void AddBuff(BuffIconType type, ushort graphic, uint time, string text, string title = "") - { - _buffIcons[type] = new BuffIcon(type, graphic, time, text, title); - - if (ProfileManager.CurrentProfile.UseImprovedBuffBar) - { - ImprovedBuffGump gump = UIManager.GetGump(); - if (gump != null) - gump.AddBuff(new BuffIcon(type, graphic, time, text, title)); - } - - EventSink.InvokeOnBuffAdded(null, new BuffEventArgs(_buffIcons[type])); - } - - public bool IsBuffIconExists(BuffIconType graphic) - { - return _buffIcons.ContainsKey(graphic); - } - - public void RemoveBuff(BuffIconType graphic) - { - if (_buffIcons.TryGetValue(graphic, out BuffIcon ev)) - { - EventSink.InvokeOnBuffRemoved(null, new BuffEventArgs(ev)); - _buffIcons.Remove(graphic); - } - - if (ProfileManager.CurrentProfile.UseImprovedBuffBar) - { - ImprovedBuffGump gump = UIManager.GetGump(); - if (gump != null) - gump.RemoveBuff(graphic); - } - } - - public void UpdateAbilities() - { - ushort equippedGraphic = 0; - - Item layerObject = FindItemByLayer(Layer.OneHanded); - - if (layerObject != null) - { - equippedGraphic = layerObject.Graphic; - } - else - { - layerObject = FindItemByLayer(Layer.TwoHanded); - - if (layerObject != null) - { - equippedGraphic = layerObject.Graphic; - } - } - - Abilities[0] = Ability.Invalid; - Abilities[1] = Ability.Invalid; - - if (equippedGraphic != 0) - { - ushort graphic0 = equippedGraphic; - ushort graphic1 = 0; - - if (layerObject != null) - { - ushort imageID = layerObject.ItemData.AnimID; - - int count = 1; - - ushort testGraphic = (ushort)(equippedGraphic - 1); - - if (TileDataLoader.Instance.StaticData[testGraphic].AnimID == imageID) - { - graphic1 = testGraphic; - count = 2; - } - else - { - testGraphic = (ushort)(equippedGraphic + 1); - - if (TileDataLoader.Instance.StaticData[testGraphic].AnimID == imageID) - { - graphic1 = testGraphic; - count = 2; - } - } - - for (int i = 0; i < count; i++) - { - ushort g = i == 0 ? graphic0 : graphic1; - - switch (g) - { - case 0x0901: // Gargish Cyclone - Abilities[0] = Ability.MovingShot; - Abilities[1] = Ability.InfusedThrow; - - goto done; - - case 0x0902: // Gargish Dagger - Abilities[0] = Ability.InfectiousStrike; - Abilities[1] = Ability.ShadowStrike; - - goto done; - - case 0x0905: // Glass Staff - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x0906: // serpentstone staff - Abilities[0] = Ability.CrushingBlow; - Abilities[1] = Ability.Dismount; - - goto done; - - case 0x090C: // Glass Sword - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x0DF0: - case 0x0DF1: // Black Staves - Abilities[0] = Ability.WhirlwindAttack; - Abilities[1] = Ability.ParalyzingBlow; - - goto done; - - case 0x0DF2: - case 0x0DF3: - case 0x0DF4: - case 0x0DF5: // Wands BookType A-D - Abilities[0] = Ability.Dismount; - Abilities[1] = Ability.Disarm; - - goto done; - - case 0x0E81: - case 0x0E82: // Shepherd's Crooks - Abilities[0] = Ability.CrushingBlow; - Abilities[1] = Ability.Disarm; - - goto done; - - case 0x0E85: - case 0x0E86: // Pickaxes - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.Disarm; - - goto done; - - case 0x0E87: - case 0x0E88: // Pitchforks - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.Dismount; - - goto done; - - case 0x0E89: - case 0x0E8A: // Quarter Staves - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.ConcussionBlow; - - goto done; - - case 0x0EC2: - case 0x0EC3: // Cleavers - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.InfectiousStrike; - - goto done; - - case 0x0EC4: - case 0x0EC5: // Skinning Knives - Abilities[0] = Ability.ShadowStrike; - Abilities[1] = Ability.BleedAttack; - - goto done; - - case 0x0F43: - case 0x0F44: // Hatchets - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.Disarm; - - goto done; - - case 0x0F45: - case 0x0F46: // Executioner Axes - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x0F47: - case 0x0F48: // Battle Axes - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.ConcussionBlow; - - goto done; - - case 0x0F49: - case 0x0F4A: // Axes - Abilities[0] = Ability.CrushingBlow; - Abilities[1] = Ability.Dismount; - - goto done; - - case 0x0F4B: // Double Axe - case 0x0F4C: - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.WhirlwindAttack; - - goto done; - - case 0x0F4D: - case 0x0F4E: // Bardiches - Abilities[0] = Ability.ParalyzingBlow; - Abilities[1] = Ability.Dismount; - - goto done; - - case 0x0F4F: - case 0x0F50: // Crossbows - Abilities[0] = Ability.ConcussionBlow; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x0F51: - case 0x0F52: // Daggers - Abilities[0] = Ability.InfectiousStrike; - Abilities[1] = Ability.ShadowStrike; - - goto done; - - case 0x0F5C: - case 0x0F5D: // Maces - Abilities[0] = Ability.ConcussionBlow; - Abilities[1] = Ability.Disarm; - - goto done; - - case 0x0F5E: - case 0x0F5F: // Broadswords - Abilities[0] = Ability.CrushingBlow; - Abilities[1] = Ability.ArmorIgnore; - - goto done; - - case 0x0F60: - case 0x0F61: // Longswords - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.ConcussionBlow; - - goto done; - - case 0x0F62: - case 0x0F63: // Spears - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.ParalyzingBlow; - - goto done; - - case 0x0FB5: - Abilities[0] = Ability.CrushingBlow; - Abilities[1] = Ability.ShadowStrike; - - goto done; - - case 0x13AF: - case 0x13B0: // War Axes - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.BleedAttack; - - goto done; - - case 0x13B1: - case 0x13B2: // Bows - Abilities[0] = Ability.ParalyzingBlow; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x13B3: - case 0x13B4: // Clubs - Abilities[0] = Ability.ShadowStrike; - Abilities[1] = Ability.Dismount; - - goto done; - - case 0x13B6: - case 0x13B7: - case 0x13B8: // Scimitars - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.ParalyzingBlow; - - goto done; - - case 0x13B9: - case 0x13BA: // Viking Swords - Abilities[0] = Ability.ParalyzingBlow; - Abilities[1] = Ability.CrushingBlow; - - goto done; - - case 0x13FD: // Heavy Crossbows - Abilities[0] = Ability.MovingShot; - Abilities[1] = Ability.Dismount; - - goto done; - - case 0x13E3: // Smith's Hammers - Abilities[0] = Ability.CrushingBlow; - Abilities[1] = Ability.ShadowStrike; - - goto done; - - case 0x13F6: // Butcher Knives - Abilities[0] = Ability.InfectiousStrike; - Abilities[1] = Ability.Disarm; - - goto done; - - case 0x13F8: // Gnarled Staves - Abilities[0] = Ability.ConcussionBlow; - Abilities[1] = Ability.ForceOfNature; - - goto done; - - case 0x13FB: // Large Battle Axes - Abilities[0] = Ability.WhirlwindAttack; - Abilities[1] = Ability.BleedAttack; - - goto done; - - case 0x13FF: // Katana - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.ArmorIgnore; - - goto done; - - case 0x1401: // Kryss - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.InfectiousStrike; - - goto done; - - case 0x1402: - case 0x1403: // Short Spears - Abilities[0] = Ability.ShadowStrike; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x1404: - case 0x1405: // War Forks - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.Disarm; - - goto done; - - case 0x1406: - case 0x1407: // War Maces - Abilities[0] = Ability.CrushingBlow; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x1438: - case 0x1439: // War Hammers - Abilities[0] = Ability.WhirlwindAttack; - Abilities[1] = Ability.CrushingBlow; - - goto done; - - case 0x143A: - case 0x143B: // Mauls - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.ConcussionBlow; - - goto done; - - case 0x143C: - case 0x143D: // Hammer Picks - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x143E: - case 0x143F: // Halberds - Abilities[0] = Ability.WhirlwindAttack; - Abilities[1] = Ability.ConcussionBlow; - - goto done; - - case 0x1440: - case 0x1441: // Cutlasses - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.ShadowStrike; - - goto done; - - case 0x1442: - case 0x1443: // Two Handed Axes - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.ShadowStrike; - - goto done; - - case 0x26BA: // Scythes - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.ParalyzingBlow; - - goto done; - - case 0x26BB: // Bone Harvesters - Abilities[0] = Ability.ParalyzingBlow; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x26BC: // Scepters - Abilities[0] = Ability.CrushingBlow; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x26BD: // Bladed Staves - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.Dismount; - - goto done; - - case 0x26BE: // Pikes - Abilities[0] = Ability.ParalyzingBlow; - Abilities[1] = Ability.InfectiousStrike; - - goto done; - - case 0x26BF: // Double Bladed Staff - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.InfectiousStrike; - - goto done; - - case 0x26C0: // Lances - Abilities[0] = Ability.Dismount; - Abilities[1] = Ability.ConcussionBlow; - - goto done; - - case 0x26C1: // Crescent Blades - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x26C2: // Composite Bows - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.MovingShot; - - goto done; - - case 0x26C3: // Repeating Crossbows - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.MovingShot; - - goto done; - - case 0x26C4: // also Scythes - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.ParalyzingBlow; - - goto done; - - case 0x26C5: // also Bone Harvesters - Abilities[0] = Ability.ParalyzingBlow; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x26C6: // also Scepters - Abilities[0] = Ability.CrushingBlow; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x26C7: // also Bladed Staves - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.Dismount; - - goto done; - - case 0x26C8: // also Pikes - Abilities[0] = Ability.ParalyzingBlow; - Abilities[1] = Ability.InfectiousStrike; - - goto done; - - case 0x26C9: // also Double Bladed Staff - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.InfectiousStrike; - - goto done; - - case 0x26CA: // also Lances - Abilities[0] = Ability.Dismount; - Abilities[1] = Ability.ConcussionBlow; - - goto done; - - case 0x26CB: // also Crescent Blades - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x26CC: // also Composite Bows - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.MovingShot; - - goto done; - - case 0x26CD: // also Repeating Crossbows - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.MovingShot; - - goto done; - - case 0x26CE: - case 0x26CF: // paladin sword - Abilities[0] = Ability.WhirlwindAttack; - Abilities[1] = Ability.Disarm; - - goto done; - - case 0x27A2: // No-Dachi - Abilities[0] = Ability.CrushingBlow; - Abilities[1] = Ability.RidingSwipe; - - goto done; - - case 0x27A3: // Tessen - Abilities[0] = Ability.Feint; - Abilities[1] = Ability.Block; - - goto done; - - case 0x27A4: // Wakizashi - Abilities[0] = Ability.FrenziedWhirlwind; - Abilities[1] = Ability.DoubleStrike; - - goto done; - - case 0x27A5: // Yumi - Abilities[0] = Ability.ArmorPierce; - Abilities[1] = Ability.DoubleShot; - - goto done; - - case 0x27A6: // Tetsubo - Abilities[0] = Ability.FrenziedWhirlwind; - Abilities[1] = Ability.CrushingBlow; - - goto done; - - case 0x27A7: // Lajatang - Abilities[0] = Ability.DefenseMastery; - Abilities[1] = Ability.FrenziedWhirlwind; - - goto done; - - case 0x27A8: // Bokuto - Abilities[0] = Ability.Feint; - Abilities[1] = Ability.NerveStrike; - - goto done; - - case 0x27A9: // Daisho - Abilities[0] = Ability.Feint; - Abilities[1] = Ability.DoubleStrike; - - goto done; - - case 0x27AA: // Fukya - Abilities[0] = Ability.Disarm; - Abilities[1] = Ability.ParalyzingBlow; - - goto done; - - case 0x27AB: // Tekagi - Abilities[0] = Ability.DualWield; - Abilities[1] = Ability.TalonStrike; - - goto done; - - case 0x27AD: // Kama - Abilities[0] = Ability.WhirlwindAttack; - Abilities[1] = Ability.DefenseMastery; - - goto done; - - case 0x27AE: // Nunchaku - Abilities[0] = Ability.Block; - Abilities[1] = Ability.Feint; - - goto done; - - case 0x27AF: // Sai - Abilities[0] = Ability.Block; - Abilities[1] = Ability.ArmorPierce; - - goto done; - - case 0x27ED: // also No-Dachi - Abilities[0] = Ability.CrushingBlow; - Abilities[1] = Ability.RidingSwipe; - - goto done; - - case 0x27EE: // also Tessen - Abilities[0] = Ability.Feint; - Abilities[1] = Ability.Block; - - goto done; - - case 0x27EF: // also Wakizashi - Abilities[0] = Ability.FrenziedWhirlwind; - Abilities[1] = Ability.DoubleStrike; - - goto done; - - case 0x27F0: // also Yumi - Abilities[0] = Ability.ArmorPierce; - Abilities[1] = Ability.DoubleShot; - - goto done; - - case 0x27F1: // also Tetsubo - Abilities[0] = Ability.FrenziedWhirlwind; - Abilities[1] = Ability.CrushingBlow; - - goto done; - - case 0x27F2: // also Lajatang - Abilities[0] = Ability.DefenseMastery; - Abilities[1] = Ability.FrenziedWhirlwind; - - goto done; - - case 0x27F3: // also Bokuto - Abilities[0] = Ability.Feint; - Abilities[1] = Ability.NerveStrike; - - goto done; - - case 0x27F4: // also Daisho - Abilities[0] = Ability.Feint; - Abilities[1] = Ability.DoubleStrike; - - goto done; - - case 0x27F5: // also Fukya - Abilities[0] = Ability.Disarm; - Abilities[1] = Ability.ParalyzingBlow; - - goto done; - - case 0x27F6: // also Tekagi - Abilities[0] = Ability.DualWield; - Abilities[1] = Ability.TalonStrike; - - goto done; - - case 0x27F8: // Kama - Abilities[0] = Ability.WhirlwindAttack; - Abilities[1] = Ability.DefenseMastery; - - goto done; - - case 0x27F9: // Nunchaku - Abilities[0] = Ability.Block; - Abilities[1] = Ability.Feint; - - goto done; - - case 0x27FA: // Sai - Abilities[0] = Ability.Block; - Abilities[1] = Ability.ArmorPierce; - - goto done; - - case 0x2D1E: // Elven Composite Longbows - Abilities[0] = Ability.ForceArrow; - Abilities[1] = Ability.SerpentArrow; - - goto done; - - case 0x2D1F: // Magical Shortbows - Abilities[0] = Ability.LightningArrow; - Abilities[1] = Ability.PsychicAttack; - - goto done; - - case 0x2D20: // Elven Spellblades - Abilities[0] = Ability.PsychicAttack; - Abilities[1] = Ability.BleedAttack; - - goto done; - - case 0x2D21: // Assassin Spikes - Abilities[0] = Ability.InfectiousStrike; - Abilities[1] = Ability.ShadowStrike; - - goto done; - - case 0x2D22: // Leafblades - Abilities[0] = Ability.Feint; - Abilities[1] = Ability.ArmorIgnore; - - goto done; - - case 0x2D23: // War Cleavers - Abilities[0] = Ability.Disarm; - Abilities[1] = Ability.Bladeweave; - - goto done; - - case 0x2D24: // Diamond Maces - Abilities[0] = Ability.ConcussionBlow; - Abilities[1] = Ability.CrushingBlow; - - goto done; - - case 0x2D25: // Wild Staves - Abilities[0] = Ability.Block; - Abilities[1] = Ability.ForceOfNature; - - goto done; - - case 0x2D26: // Rune Blades - Abilities[0] = Ability.Disarm; - Abilities[1] = Ability.Bladeweave; - - goto done; - - case 0x2D27: // Radiant Scimitars - Abilities[0] = Ability.WhirlwindAttack; - Abilities[1] = Ability.Bladeweave; - - goto done; - - case 0x2D28: // Ornate Axes - Abilities[0] = Ability.Disarm; - Abilities[1] = Ability.CrushingBlow; - - goto done; - - case 0x2D29: // Elven Machetes - Abilities[0] = Ability.DefenseMastery; - Abilities[1] = Ability.Bladeweave; - - goto done; - - case 0x2D2A: // also Elven Composite Longbows - Abilities[0] = Ability.ForceArrow; - Abilities[1] = Ability.SerpentArrow; - - goto done; - - case 0x2D2B: // also Magical Shortbows - Abilities[0] = Ability.LightningArrow; - Abilities[1] = Ability.PsychicAttack; - - goto done; - - case 0x2D2C: // also Elven Spellblades - Abilities[0] = Ability.PsychicAttack; - Abilities[1] = Ability.BleedAttack; - - goto done; - - case 0x2D2D: // also Assassin Spikes - Abilities[0] = Ability.InfectiousStrike; - Abilities[1] = Ability.ShadowStrike; - - goto done; - - case 0x2D2E: // also Leafblades - Abilities[0] = Ability.Feint; - Abilities[1] = Ability.ArmorIgnore; - - goto done; - - case 0x2D2F: // also War Cleavers - Abilities[0] = Ability.Disarm; - Abilities[1] = Ability.Bladeweave; - - goto done; - - case 0x2D30: // also Diamond Maces - Abilities[0] = Ability.ConcussionBlow; - Abilities[1] = Ability.CrushingBlow; - - goto done; - - case 0x2D31: // also Wild Staves - Abilities[0] = Ability.Block; - Abilities[1] = Ability.ForceOfNature; - - goto done; - - case 0x2D32: // also Rune Blades - Abilities[0] = Ability.Disarm; - Abilities[1] = Ability.Bladeweave; - - goto done; - - case 0x2D33: // also Radiant Scimitars - Abilities[0] = Ability.WhirlwindAttack; - Abilities[1] = Ability.Bladeweave; - - goto done; - - case 0x2D34: // also Ornate Axes - Abilities[0] = Ability.Disarm; - Abilities[1] = Ability.CrushingBlow; - - goto done; - - case 0x2D35: // also Elven Machetes - Abilities[0] = Ability.DefenseMastery; - Abilities[1] = Ability.Bladeweave; - - goto done; - - case 0x4067: // Boomerang - Abilities[0] = Ability.MysticArc; - Abilities[1] = Ability.ConcussionBlow; - - goto done; - - case 0x8FD: - case 0x4068: // Dual Short Axes - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.InfectiousStrike; - - goto done; - - case 0x406B: // Soul Glaive - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x406C: // Cyclone - Abilities[0] = Ability.MovingShot; - Abilities[1] = Ability.InfusedThrow; - - goto done; - - case 0x904: - case 0x406D: // Dual Pointed Spear - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.Disarm; - - goto done; - - case 0x903: - case 0x406E: // Disc Mace - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.Disarm; - - goto done; - - case 0x8FE: - case 0x4072: // Blood Blade - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.ParalyzingBlow; - - goto done; - - case 0x90B: - case 0x4074: // Dread Sword - Abilities[0] = Ability.CrushingBlow; - Abilities[1] = Ability.ConcussionBlow; - - goto done; - - case 0x908: - case 0x4075: // Gargish Talwar - Abilities[0] = Ability.WhirlwindAttack; - Abilities[1] = Ability.Dismount; - - goto done; - - case 0x4076: // Shortblade - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x48AE: // Gargish Cleaver - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.InfectiousStrike; - - goto done; - - case 0x48B0: // Gargish Battle Axe - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.ConcussionBlow; - - goto done; - - case 0x48B3: - case 0x48B2: // Gargish Axe - Abilities[0] = Ability.CrushingBlow; - Abilities[1] = Ability.Dismount; - - goto done; - - case 0x48B5: - case 0x48B4: // Gargish Bardiche - Abilities[0] = Ability.ParalyzingBlow; - Abilities[1] = Ability.Dismount; - - goto done; - - case 0x48B7: - case 0x48B6: // Gargish Butcher Knife - Abilities[0] = Ability.InfectiousStrike; - Abilities[1] = Ability.Disarm; - - goto done; - - case 0x48B9: - case 0x48B8: // Gargish Gnarled Staff - Abilities[0] = Ability.ConcussionBlow; - Abilities[1] = Ability.ParalyzingBlow; - - goto done; - - case 0x48BB: - case 0x48BA: // Gargish Katana - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.ArmorIgnore; - - goto done; - - case 0x48BD: - case 0x48BC: // Gargish Kryss - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.InfectiousStrike; - - goto done; - - case 0x48BF: - case 0x48BE: // Gargish War Fork - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.Disarm; - - goto done; - - case 0x48CB: - case 0x48CA: // Gargish Lance - Abilities[0] = Ability.Dismount; - Abilities[1] = Ability.ConcussionBlow; - - goto done; - - case 0x481: - case 0x48C0: // Gargish War Hammer - Abilities[0] = Ability.WhirlwindAttack; - Abilities[1] = Ability.CrushingBlow; - - goto done; - - case 0x48C3: - case 0x48C2: // Gargish Maul - Abilities[0] = Ability.DoubleStrike; - Abilities[1] = Ability.ConcussionBlow; - - goto done; - - case 0x48C5: - case 0x48C4: // Gargish Scyte - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.ParalyzingBlow; - - goto done; - - case 0x48C7: - case 0x48C6: // Gargish Bone Harvester - Abilities[0] = Ability.ParalyzingBlow; - Abilities[1] = Ability.MortalStrike; - - goto done; - - case 0x48C9: - case 0x48C8: // Gargish Pike - Abilities[0] = Ability.ParalyzingBlow; - Abilities[1] = Ability.InfectiousStrike; - - goto done; - - case 0x48CC: - case 0x48CD: // Gargish Tessen - Abilities[0] = Ability.Feint; - Abilities[1] = Ability.Block; - - goto done; - - case 0x48CF: - case 0x48CE: // Gargish Tekagi - Abilities[0] = Ability.DualWield; - Abilities[1] = Ability.TalonStrike; - - goto done; - - case 0x48D1: - case 0x48D0: // Gargish Daisho - Abilities[0] = Ability.Feint; - Abilities[1] = Ability.DoubleStrike; - - goto done; - - // TODO: these are the new whips. More info here: https://uo.com/wiki/ultima-online-wiki/publish-notes/publish-103/ . They needed a version check? - case 0xA289: // Barbed Whip - Abilities[0] = Ability.ConcussionBlow; - Abilities[1] = Ability.WhirlwindAttack; - - goto done; - - case 0xA292: // Spiked Whip - Abilities[0] = Ability.ArmorPierce; - Abilities[1] = Ability.WhirlwindAttack; - - goto done; - - case 0xA28B: // Bladed Whip - Abilities[0] = Ability.BleedAttack; - Abilities[1] = Ability.WhirlwindAttack; - - goto done; - - case 0x08FF: // Boomerang - Abilities[0] = Ability.MysticArc; - Abilities[1] = Ability.ConcussionBlow; - - break; - - case 0x0900: // Stone War Sword - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.ParalyzingBlow; - - break; - - case 0x090A: // Soul Glaive - Abilities[0] = Ability.ArmorIgnore; - Abilities[1] = Ability.MortalStrike; - - break; - } - } - } - - done:; - } - - - if (Abilities[0] == Ability.Invalid) - { - Abilities[0] = Ability.Disarm; - Abilities[1] = Ability.ParalyzingBlow; - } - - int max = 0; - - for (LinkedListNode last = UIManager.Gumps.Last; last != null; last = last.Previous) - { - Control control = last.Value; - - if (control is UseAbilityButtonGump s) - { - s.RequestUpdateContents(); - max++; - } - - if (max >= 2) - { - break; - } - } - } - - protected override void OnPositionChanged() - { - base.OnPositionChanged(); - - Plugin.UpdatePlayerPosition(X, Y, Z); - - TryOpenDoors(); - TryOpenCorpses(); - - EventSink.InvokeOnPositionChanged(this, new PositionChangedArgs(new Microsoft.Xna.Framework.Vector3(X, Y, Z))); - } - - public void TryOpenCorpses() - { - if (ProfileManager.CurrentProfile.AutoOpenCorpses) - { - if ((ProfileManager.CurrentProfile.CorpseOpenOptions == 1 || ProfileManager.CurrentProfile.CorpseOpenOptions == 3) && TargetManager.IsTargeting) - { - return; - } - - if ((ProfileManager.CurrentProfile.CorpseOpenOptions == 2 || ProfileManager.CurrentProfile.CorpseOpenOptions == 3) && IsHidden) - { - return; - } - - foreach (Item item in World.Items.Values) - { - if (!item.IsDestroyed && item.IsCorpse && item.Distance <= ProfileManager.CurrentProfile.AutoOpenCorpseRange && !AutoOpenedCorpses.Contains(item.Serial)) - { - AutoOpenedCorpses.Add(item.Serial); - GameActions.DoubleClickQueued(item.Serial); - } - } - } - } - - protected override void OnDirectionChanged() - { - base.OnDirectionChanged(); - TryOpenDoors(); - } - - private void TryOpenDoors() - { - if (!World.Player.IsDead && ProfileManager.CurrentProfile.AutoOpenDoors) - { - int x = X, y = Y, z = Z; - Pathfinder.GetNewXY((byte)Direction, ref x, ref y); - - if (World.Items.Values.Any(s => s.ItemData.IsDoor && s.X == x && s.Y == y && s.Z - 15 <= z && s.Z + 15 >= z)) - { - GameActions.OpenDoor(); - } - } - } - - public override void Destroy() - { - if (IsDestroyed) - { - return; - } - - DeathScreenTimer = 0; - - Log.Warn("PlayerMobile disposed!"); - base.Destroy(); - } - - public void CloseBank() - { - Item bank = FindItemByLayer(Layer.Bank); - - if (bank != null && bank.Opened) - { - if (!bank.IsEmpty) - { - Item first = (Item)bank.Items; - - while (first != null) - { - Item next = (Item)first.Next; - - World.RemoveItem(first, true); - - first = next; - } - - bank.Items = null; - } - - UIManager.GetGump(bank.Serial)?.Dispose(); - #region GridContainer - UIManager.GetGump(bank.Serial)?.Dispose(); - #endregion - - bank.Opened = false; - } - } - - public void CloseRangedGumps() - { - for (int i = 0; i < UIManager.Gumps.Count; i++) - { - if (UIManager.Gumps.Count > i) - continue; - - Gump gump = UIManager.Gumps.ElementAt(i); - //} - //foreach (Gump gump in UIManager.Gumps) - //{ - switch (gump) - { - case ModernPaperdoll _: - case PaperDollGump _: - case MapGump _: - case SpellbookGump _: - - if (World.Get(gump.LocalSerial) == null) - { - gump.Dispose(); - } - - break; - - case TradingGump _: - case ShopGump _: - - Entity ent = World.Get(gump.LocalSerial); - int distance = int.MaxValue; - - if (ent != null) - { - if (SerialHelper.IsItem(ent.Serial)) - { - Entity top = World.Get(((Item)ent).RootContainer); - - if (top != null) - { - distance = top.Distance; - } - } - else - { - distance = ent.Distance; - } - } - - if (distance > Constants.MIN_VIEW_RANGE) - { - gump.Dispose(); - } - - break; - - case ContainerGump _: - distance = int.MaxValue; - - ent = World.Get(gump.LocalSerial); - - if (ent != null) - { - if (SerialHelper.IsItem(ent.Serial)) - { - Entity top = World.Get(((Item)ent).RootContainer); - - if (top != null) - { - distance = top.Distance; - } - } - else - { - distance = ent.Distance; - } - } - - if (distance > Constants.MAX_CONTAINER_OPENED_ON_GROUND_RANGE) - { - gump.Dispose(); - } - - break; - #region GridContainer - case GridContainer _: - distance = int.MaxValue; - - ent = World.Get(gump.LocalSerial); - - if (ent != null) - { - if (SerialHelper.IsItem(ent.Serial)) - { - Entity top = World.Get(((Item)ent).RootContainer); - - if (top != null) - { - distance = top.Distance; - } - } - else - { - distance = ent.Distance; - } - } - - if (distance > Constants.MAX_CONTAINER_OPENED_ON_GROUND_RANGE) - { - gump.Dispose(); - } - - break; - #endregion - } - } - } - - - //public override void Update() - //{ - // base.Update(); - - // //const int TIME_TURN_TO_LASTTARGET = 2000; - - // //if (TargetManager.LastAttack != 0 && - // // InWarMode && - // // Walker.LastStepRequestTime + TIME_TURN_TO_LASTTARGET < Time.Ticks) - // //{ - // // Mobile enemy = World.Mobiles.Get(TargetManager.LastAttack); - - // // if (enemy != null && enemy.Distance <= 1) - // // { - // // Direction pdir = DirectionHelper.GetDirectionAB(World.Player.X, - // // World.Player.Y, - // // enemy.X, - // // enemy.Y); - - // // if (Direction != pdir) - // // Walk(pdir, false); - // // } - // //} - //} - - // ############# DO NOT DELETE IT! ############# - //protected override bool NoIterateAnimIndex() - //{ - // return false; - //} - // ############################################# - - public bool Walk(Direction direction, bool run) - { - if (Walker.WalkingFailed || Walker.LastStepRequestTime > Time.Ticks || Walker.StepsCount >= Constants.MAX_STEP_COUNT || Client.Version >= ClientVersion.CV_60142 && IsParalyzed) - { - return false; - } - - run |= ProfileManager.CurrentProfile.AlwaysRun; - - if (SpeedMode >= CharacterSpeedType.CantRun || Stamina <= 1 && !IsDead || IsHidden && ProfileManager.CurrentProfile.AlwaysRunUnlessHidden) - { - run = false; - } - - int x = X; - int y = Y; - sbyte z = Z; - Direction oldDirection = Direction; - - bool emptyStack = Steps.Count == 0; - - if (!emptyStack) - { - ref Step walkStep = ref Steps.Back(); - x = walkStep.X; - y = walkStep.Y; - z = walkStep.Z; - oldDirection = (Direction)walkStep.Direction; - } - - sbyte oldZ = z; - ushort walkTime = Constants.TURN_DELAY; - - if ((oldDirection & Direction.Mask) == (direction & Direction.Mask)) - { - Direction newDir = direction; - int newX = x; - int newY = y; - sbyte newZ = z; - - if (!Pathfinder.CanWalk(ref newDir, ref newX, ref newY, ref newZ)) - { - return false; - } - - if ((direction & Direction.Mask) != newDir) - { - direction = newDir; - } - else - { - direction = newDir; - x = newX; - y = newY; - z = newZ; - - walkTime = (ushort)MovementSpeed.TimeToCompleteMovement(run, IsMounted || SpeedMode == CharacterSpeedType.FastUnmount || SpeedMode == CharacterSpeedType.FastUnmountAndCantRun || IsFlying); - } - } - else - { - Direction newDir = direction; - int newX = x; - int newY = y; - sbyte newZ = z; - - if (!Pathfinder.CanWalk(ref newDir, ref newX, ref newY, ref newZ)) - { - if ((oldDirection & Direction.Mask) == newDir) - { - return false; - } - } - - if ((oldDirection & Direction.Mask) == newDir) - { - x = newX; - y = newY; - z = newZ; - - walkTime = (ushort)MovementSpeed.TimeToCompleteMovement(run, IsMounted || SpeedMode == CharacterSpeedType.FastUnmount || SpeedMode == CharacterSpeedType.FastUnmountAndCantRun || IsFlying); - } - - direction = newDir; - } - - CloseBank(); - - if (emptyStack) - { - if (!IsWalking) - { - SetAnimation(0xFF); - } - - LastStepTime = Time.Ticks; - } - - ref StepInfo step = ref Walker.StepInfos[Walker.StepsCount]; - step.Sequence = Walker.WalkSequence; - step.Accepted = false; - step.Running = run; - step.OldDirection = (byte)(oldDirection & Direction.Mask); - step.Direction = (byte)direction; - step.Timer = Time.Ticks; - step.X = (ushort)x; - step.Y = (ushort)y; - step.Z = z; - step.NoRotation = step.OldDirection == (byte)direction && oldZ - z >= 11; - - Walker.StepsCount++; - - Steps.AddToBack - ( - new Step - { - X = x, - Y = y, - Z = z, - Direction = (byte)direction, - Run = run - } - ); - - - NetClient.Socket.Send_WalkRequest(direction, Walker.WalkSequence, run, Walker.FastWalkStack.GetValue()); - - - if (Walker.WalkSequence == 0xFF) - { - Walker.WalkSequence = 1; - } - else - { - Walker.WalkSequence++; - } - - Walker.UnacceptedPacketsCount++; - - AddToTile(); - - int nowDelta = 0; - - //if (_lastDir == (int) direction && _lastMount == IsMounted && _lastRun == run) - //{ - // nowDelta = (int) (Time.Ticks - _lastStepTime - walkTime + _lastDelta); - - // if (Math.Abs(nowDelta) > 70) - // nowDelta = 0; - // _lastDelta = nowDelta; - //} - //else - // _lastDelta = 0; - - //_lastStepTime = (int) Time.Ticks; - //_lastRun = run; - //_lastMount = IsMounted; - //_lastDir = (int) direction; - - - Walker.LastStepRequestTime = Time.Ticks + walkTime - nowDelta; - GetGroupForAnimation(this, 0, true); - - return true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/GameObjects/RenderedText.cs b/src/ClassicUO.Client/Game/GameObjects/RenderedText.cs deleted file mode 100644 index 6ff6e2926..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/RenderedText.cs +++ /dev/null @@ -1,728 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.IO; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using StbTextEditSharp; -using System; -using System.Collections.Generic; - -namespace ClassicUO.Game -{ - [Flags] - public enum FontStyle : ushort - { - None = 0x0000, - Solid = 0x0001, - Italic = 0x0002, - Indention = 0x0004, - BlackBorder = 0x0008, - Underline = 0x0010, - Fixed = 0x0020, - Cropped = 0x0040, - BQ = 0x0080, - ExtraHeight = 0x0100, - CropTexture = 0x0200 - } - - public sealed class RenderedText - { - private static readonly QueuedPool _pool = new QueuedPool( - 3000, - r => - { - r.IsDestroyed = false; - r.Links.Clear(); - } - ); - - private static PixelPicker _picker = new PixelPicker(); - private byte _font; - - private MultilinesFontInfo _info; - private string _text; - - public bool IsUnicode { get; set; } - - public byte Font - { - get => _font; - set - { - if (value == 0xFF) - { - value = (byte)(Client.Version >= ClientVersion.CV_305D ? 1 : 0); - } - - _font = value; - } - } - - public TEXT_ALIGN_TYPE Align { get; set; } - - public int MaxWidth { get; set; } - - public int MaxHeight { get; set; } = 0; - - public FontStyle FontStyle { get; set; } - - public byte Cell { get; set; } - - public bool IsHTML { get; set; } - - public bool RecalculateWidthByInfo { get; set; } - - public List Links { get; set; } = new List(); - - public ushort Hue { get; set; } - - public uint HTMLColor { get; set; } = 0xFFFFFFFF; - - public bool HasBackgroundColor { get; set; } - - public string Text - { - get => _text; - set - { - if (_text != value) - { - _text = value; - - if (string.IsNullOrEmpty(value)) - { - Width = 0; - Height = 0; - - if (IsHTML) - { - FontsLoader.Instance.SetUseHTML(false); - } - - Links.Clear(); - Texture?.Dispose(); - Texture = null; - _info = null; - } - else - { - CreateTexture(); - - if (IsUnicode) - { - _info = FontsLoader.Instance.GetInfoUnicode( - Font, - Text, - Text.Length, - Align, - (ushort)FontStyle, - MaxWidth > 0 ? MaxWidth : Width, - true, - true - ); - } - else - { - _info = FontsLoader.Instance.GetInfoASCII( - Font, - Text, - Text.Length, - Align, - (ushort)FontStyle, - MaxWidth > 0 ? MaxWidth : Width, - true, - true - ); - } - } - } - } - } - - public int LinesCount { get; set; } - - public bool SaveHitMap { get; private set; } - - public bool IsDestroyed { get; private set; } - - public int Width { get; private set; } - - public int Height { get; private set; } - - public Texture2D Texture { get; set; } - - public static RenderedText Create( - string text, - ushort hue = 0xFFFF, - byte font = 0xFF, - bool isunicode = true, - FontStyle style = 0, - TEXT_ALIGN_TYPE align = 0, - int maxWidth = 0, - byte cell = 30, - bool isHTML = false, - bool recalculateWidthByInfo = false, - bool saveHitmap = false - ) - { - RenderedText r = _pool.GetOne(); - r.Hue = hue; - r.Font = font; - r.IsUnicode = isunicode; - r.FontStyle = style; - r.Cell = cell; - r.Align = align; - r.MaxWidth = maxWidth; - r.IsHTML = isHTML; - r.RecalculateWidthByInfo = recalculateWidthByInfo; - r.Width = 0; - r.Height = 0; - r.SaveHitMap = saveHitmap; - r.HTMLColor = 0xFFFF_FFFF; - r.HasBackgroundColor = false; - - if (r.Text != text) - { - r.Text = text; // here makes the texture - } - else - { - r.CreateTexture(); - } - - return r; - } - - public Point GetCaretPosition(int caret_index) - { - Point p; - - if (IsUnicode) - { - (p.X, p.Y) = FontsLoader.Instance.GetCaretPosUnicode( - Font, - Text, - caret_index, - MaxWidth, - Align, - (ushort)FontStyle - ); - } - else - { - (p.X, p.Y) = FontsLoader.Instance.GetCaretPosASCII( - Font, - Text, - caret_index, - MaxWidth, - Align, - (ushort)FontStyle - ); - } - - return p; - } - - public MultilinesFontInfo GetInfo() - { - return _info; - } - - public bool PixelCheck(int x, int y) - { - if (string.IsNullOrWhiteSpace(Text)) - { - return false; - } - - ushort hue = Hue; - - if (!IsUnicode && SaveHitMap) - { - hue = 0x7FFF; - } - - ulong b = (ulong)( - Text.GetHashCode() - ^ hue - ^ ((int)Align) - ^ ((int)FontStyle) - ^ Font - ^ (IsUnicode ? 0x01 : 0x00) - ); - - return _picker.Get(b, x, y); - } - - public TextEditRow GetLayoutRow(int startIndex) - { - TextEditRow r = new TextEditRow(); - - if (string.IsNullOrEmpty(Text)) - { - return r; - } - - MultilinesFontInfo info = _info; - - if (info == null) - { - return r; - } - - switch (Align) - { - case TEXT_ALIGN_TYPE.TS_LEFT: - r.x0 = 0; - r.x1 = Width; - - break; - - case TEXT_ALIGN_TYPE.TS_CENTER: - r.x0 = (Width - info.Width) >> 1; - - if (r.x0 < 0) - { - r.x0 = 0; - } - - r.x1 = r.x0; - - break; - - case TEXT_ALIGN_TYPE.TS_RIGHT: - r.x0 = Width; - - // TODO: r.x1 ??? i don't know atm :D - break; - } - - int start = 0; - - while (info != null) - { - if (startIndex >= start && startIndex < start + info.CharCount) - { - r.num_chars = info.CharCount; - r.ymax = info.MaxHeight; - r.baseline_y_delta = info.MaxHeight; - - break; - } - - start += info.CharCount; - info = info.Next; - } - - return r; - } - - public int GetCharWidthAtIndex(int index) - { - if (string.IsNullOrEmpty(Text)) - { - return 0; - } - - MultilinesFontInfo info = _info; - - int start = 0; - - while (info != null) - { - if (index >= start && index < start + info.CharCount) - { - int x = index - start; - - if (x >= 0) - { - char c = x >= info.Data.Length ? '\n' : info.Data[x].Item; - - if (IsUnicode) - { - return FontsLoader.Instance.GetCharWidthUnicode(Font, c); - } - - return FontsLoader.Instance.GetCharWidthASCII(Font, c); - } - } - - start += info.CharCount; - info = info.Next; - } - - return 0; - } - - public int GetCharWidth(char c) - { - if (IsUnicode) - { - return FontsLoader.Instance.GetCharWidthUnicode(Font, c); - } - - return FontsLoader.Instance.GetCharWidthASCII(Font, c); - } - - public bool Draw( - UltimaBatcher2D batcher, - int swidth, - int sheight, - int dx, - int dy, - int dwidth, - int dheight, - int offsetX, - int offsetY, - ushort hue = 0 - ) - { - if (string.IsNullOrEmpty(Text) || Texture == null || IsDestroyed || Texture.IsDisposed) - { - return false; - } - - if (offsetX > swidth || offsetX < -swidth || offsetY > sheight || offsetY < -sheight) - { - return false; - } - - int srcX = offsetX; - int srcY = offsetY; - int maxX = srcX + dwidth; - - int srcWidth; - int srcHeight; - - if (maxX <= swidth) - { - srcWidth = dwidth; - } - else - { - srcWidth = swidth - srcX; - dwidth = srcWidth; - } - - int maxY = srcY + dheight; - - if (maxY <= sheight) - { - srcHeight = dheight; - } - else - { - srcHeight = sheight - srcY; - dheight = srcHeight; - } - - if (!IsUnicode && SaveHitMap && hue == 0) - { - hue = Hue; - } - - if (hue > 0) - { - --hue; - } - - Vector3 hueVector = new Vector3(hue, 0, 1f); - - if (hue != 0) - { - if (IsUnicode) - { - hueVector.Y = ShaderHueTranslator.SHADER_TEXT_HUE_NO_BLACK; - } - else if (Font != 5 && Font != 8) - { - hueVector.Y = ShaderHueTranslator.SHADER_PARTIAL_HUED; - } - else - { - hueVector.Y = ShaderHueTranslator.SHADER_HUED; - } - } - else - { - hueVector.Y = 0; - } - - batcher.Draw( - Texture, - new Rectangle(dx, dy, dwidth, dheight), - new Rectangle(srcX, srcY, srcWidth, srcHeight), - hueVector - ); - - return true; - } - - public bool Draw( - UltimaBatcher2D batcher, - int dx, - int dy, - int sx, - int sy, - int swidth, - int sheight, - int hue = -1 - ) - { - if (string.IsNullOrEmpty(Text) || Texture == null || IsDestroyed || Texture.IsDisposed) - { - return false; - } - - if (sx > Texture.Width || sy > Texture.Height) - { - return false; - } - - if (!IsUnicode && SaveHitMap && hue == -1) - { - hue = Hue; - } - - if (hue > 0) - { - --hue; - } - - Vector3 hueVector = new Vector3(hue, 0, 1f); - - if (hue != -1) - { - hueVector.X = hue; - - if (hue != 0) - { - if (IsUnicode) - { - hueVector.Y = ShaderHueTranslator.SHADER_TEXT_HUE_NO_BLACK; - } - else if (Font != 5 && Font != 8) - { - hueVector.Y = ShaderHueTranslator.SHADER_PARTIAL_HUED; - } - else - { - hueVector.Y = ShaderHueTranslator.SHADER_HUED; - } - } - else - { - hueVector.Y = 0; - } - } - - batcher.Draw( - Texture, - new Vector2(dx, dy), - new Rectangle(sx, sy, swidth, sheight), - hueVector - ); - - return true; - } - - public bool Draw(UltimaBatcher2D batcher, int x, int y, float alpha = 1, ushort hue = 0) - { - if (string.IsNullOrEmpty(Text) || Texture == null || IsDestroyed || Texture.IsDisposed) - { - return false; - } - - if (!IsUnicode && SaveHitMap && hue == 0) - { - hue = Hue; - } - - if (hue > 0) - { - --hue; - } - - Vector3 hueVector = new Vector3(hue, 0, alpha); - - if (hue != 0) - { - if (IsUnicode) - { - hueVector.Y = ShaderHueTranslator.SHADER_TEXT_HUE_NO_BLACK; - } - else if (Font != 5 && Font != 8) - { - hueVector.Y = ShaderHueTranslator.SHADER_PARTIAL_HUED; - } - else - { - hueVector.Y = ShaderHueTranslator.SHADER_HUED; - } - } - else - { - hueVector.Y = 0; - } - - batcher.Draw(Texture, new Rectangle(x, y, Width, Height), hueVector); - - return true; - } - - public unsafe void CreateTexture() - { - if (Texture != null && !Texture.IsDisposed) - { - Texture.Dispose(); - Texture = null; - } - - if (IsHTML) - { - FontsLoader.Instance.SetUseHTML(true, HTMLColor, HasBackgroundColor); - } - - FontsLoader.Instance.RecalculateWidthByInfo = RecalculateWidthByInfo; - - FontsLoader.FontInfo fi; - if (IsUnicode) - { - fi = FontsLoader.Instance.GenerateUnicode( - Font, - Text, - Hue, - Cell, - MaxWidth, - Align, - (ushort)FontStyle, - SaveHitMap, - MaxHeight - ); - } - else - { - fi = FontsLoader.Instance.GenerateASCII( - Font, - Text, - Hue, - MaxWidth, - Align, - (ushort)FontStyle, - SaveHitMap, - MaxHeight - ); - } - - if (SaveHitMap) - { - var b = (ulong)( - Text.GetHashCode() - ^ Hue - ^ ((int)Align) - ^ ((int)FontStyle) - ^ Font - ^ (IsUnicode ? 0x01 : 0x00) - ); - _picker.Set(b, fi.Width, fi.Height, fi.Data); - } - - var isValid = fi.Data != null && fi.Data.Length > 0; - - if (isValid && (Texture == null || Texture.IsDisposed)) - { - Texture = new Texture2D( - Client.Game.GraphicsDevice, - fi.Width, - fi.Height, - false, - SurfaceFormat.Color - ); - } - - Links.Clear(); - if (fi.Links != null) - { - for (int i = 0; i < fi.Links.Length; ++i) - { - Links.Add(fi.Links[i]); - } - } - - LinesCount = fi.LineCount; - - if (Texture != null && isValid) - { - fixed (uint* dataPtr = fi.Data) - { - Texture.SetDataPointerEXT( - 0, - null, - (IntPtr)dataPtr, - fi.Width * fi.Height * sizeof(uint) - ); - } - - Width = Texture.Width; - Height = Texture.Height; - } - - if (IsHTML) - { - FontsLoader.Instance.SetUseHTML(false); - } - - FontsLoader.Instance.RecalculateWidthByInfo = false; - } - - public void Destroy() - { - if (IsDestroyed) - { - return; - } - - IsDestroyed = true; - - if (Texture != null && !Texture.IsDisposed) - { - Texture.Dispose(); - } - - _pool.ReturnOne(this); - } - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/Static.cs b/src/ClassicUO.Client/Game/GameObjects/Static.cs deleted file mode 100644 index a8c7690ae..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/Static.cs +++ /dev/null @@ -1,119 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Assets; -using ClassicUO.Utility; - -namespace ClassicUO.Game.GameObjects -{ - internal sealed partial class Static : GameObject - { - private static readonly QueuedPool _pool = new QueuedPool - ( - Constants.PREDICTABLE_STATICS, - s => - { - s.IsDestroyed = false; - s.AlphaHue = 0; - s.FoliageIndex = 0; - } - ); - - public string Name => ItemData.Name; - - public ushort OriginalGraphic { get; private set; } - - public ref StaticTiles ItemData => ref TileDataLoader.Instance.StaticData[Graphic]; - - public bool IsVegetation; - public int Index; - - - public static Static Create(ushort graphic, ushort hue, int index) - { - Static s = _pool.GetOne(); - s.Graphic = s.OriginalGraphic = graphic; - s.Hue = hue; - s.UpdateGraphicBySeason(); - s.Index = index; - - if (s.ItemData.Height > 5 || s.ItemData.Height == 0) - { - s._canBeTransparent = 1; - } - else if (s.ItemData.IsRoof || s.ItemData.IsSurface && s.ItemData.IsBackground || s.ItemData.IsWall) - { - s._canBeTransparent = 1; - } - else if (s.ItemData.Height == 5 && s.ItemData.IsSurface && !s.ItemData.IsBackground) - { - s._canBeTransparent = 1; - } - else - { - s._canBeTransparent = 0; - } - - return s; - } - - public void SetGraphic(ushort g) - { - Graphic = g; - } - - public void RestoreOriginalGraphic() - { - Graphic = OriginalGraphic; - } - - public override void UpdateGraphicBySeason() - { - SetGraphic(SeasonManager.GetSeasonGraphic(World.Season, OriginalGraphic)); - AllowedToDraw = CanBeDrawn(Graphic); - IsVegetation = StaticFilters.IsVegetation(Graphic); - } - - public override void Destroy() - { - if (IsDestroyed) - { - return; - } - - base.Destroy(); - _pool.ReturnOne(this); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/GameObjects/TextObject.cs b/src/ClassicUO.Client/Game/GameObjects/TextObject.cs deleted file mode 100644 index 27a30fa0f..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/TextObject.cs +++ /dev/null @@ -1,141 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.GameObjects -{ - public class TextObject : BaseGameObject - { - private static readonly QueuedPool _queue = new QueuedPool - ( - 1000, - o => - { - o.IsDestroyed = false; - o.Alpha = 0xFF; - o.Hue = 0; - o.Time = 0; - o.IsTransparent = false; - o.SecondTime = 0; - o.Type = 0; - o.X = 0; - o.Y = 0; - o.RealScreenPosition = Point.Zero; - o.OffsetY = 0; - o.Owner = null; - o.UnlinkD(); - o.IsTextGump = false; - o.TextBox?.Dispose(); - o.TextBox = null; - o.Clear(); - } - ); - - public byte Alpha; - public TextObject DLeft, DRight; - public ushort Hue; - public bool IsDestroyed; - public bool IsTextGump; - public bool IsTransparent; - public GameObject Owner; - - public TextBox TextBox; - public long Time, SecondTime; - public MessageType Type; - public int X, Y, OffsetY; - - - public static TextObject Create() - { - return _queue.GetOne(); - } - - - public virtual void Destroy() - { - if (IsDestroyed) - { - return; - } - - UnlinkD(); - - RealScreenPosition = Point.Zero; - IsDestroyed = true; - TextBox?.Dispose(); - TextBox = null; - Owner = null; - - _queue.ReturnOne(this); - } - - public void UnlinkD() - { - if (DRight != null) - { - DRight.DLeft = DLeft; - } - - if (DLeft != null) - { - DLeft.DRight = DRight; - } - - DRight = null; - DLeft = null; - } - - public void ToTopD() - { - TextObject obj = this; - - while (obj != null) - { - if (obj.DLeft == null) - { - break; - } - - obj = obj.DLeft; - } - - TextRenderer next = (TextRenderer) obj; - next.MoveToTop(this); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/GameObjects/Views/GameEffectView.cs b/src/ClassicUO.Client/Game/GameObjects/Views/GameEffectView.cs deleted file mode 100644 index 438f6b8bd..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/Views/GameEffectView.cs +++ /dev/null @@ -1,262 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.Scenes; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.GameObjects -{ - partial class GameEffect - { - private static readonly Lazy _multiplyBlendState = new Lazy - ( - () => - { - BlendState state = new BlendState - { - ColorSourceBlend = Microsoft.Xna.Framework.Graphics.Blend.Zero, - ColorDestinationBlend = Microsoft.Xna.Framework.Graphics.Blend.SourceColor - }; - - return state; - } - ); - - private static readonly Lazy _screenBlendState = new Lazy - ( - () => - { - BlendState state = new BlendState - { - ColorSourceBlend = Microsoft.Xna.Framework.Graphics.Blend.One, - ColorDestinationBlend = Microsoft.Xna.Framework.Graphics.Blend.One - }; - - return state; - } - ); - - private static readonly Lazy _screenLessBlendState = new Lazy - ( - () => - { - BlendState state = new BlendState - { - ColorSourceBlend = Microsoft.Xna.Framework.Graphics.Blend.DestinationColor, - ColorDestinationBlend = Microsoft.Xna.Framework.Graphics.Blend.InverseSourceAlpha - }; - - return state; - } - ); - - private static readonly Lazy _normalHalfBlendState = new Lazy - ( - () => - { - BlendState state = new BlendState - { - ColorSourceBlend = Microsoft.Xna.Framework.Graphics.Blend.DestinationColor, - ColorDestinationBlend = Microsoft.Xna.Framework.Graphics.Blend.SourceColor - }; - - return state; - } - ); - - private static readonly Lazy _shadowBlueBlendState = new Lazy - ( - () => - { - BlendState state = new BlendState - { - ColorSourceBlend = Microsoft.Xna.Framework.Graphics.Blend.SourceColor, - ColorDestinationBlend = Microsoft.Xna.Framework.Graphics.Blend.InverseSourceColor, - ColorBlendFunction = BlendFunction.ReverseSubtract - }; - - return state; - } - ); - - - public override bool Draw(UltimaBatcher2D batcher, int posX, int posY, float depth) - { - if (IsDestroyed || !AllowedToDraw) - { - return false; - } - - if (AnimationGraphic == 0xFFFF) - { - return false; - } - - ref StaticTiles data = ref TileDataLoader.Instance.StaticData[Graphic]; - - posX += (int)Offset.X; - posY += (int)(Offset.Z + Offset.Y); - - ushort hue = Hue; - - if (ProfileManager.CurrentProfile.NoColorObjectsOutOfRange && Distance > World.ClientViewRange) - { - hue = Constants.OUT_RANGE_COLOR; - } - else if (World.Player.IsDead && ProfileManager.CurrentProfile.EnableBlackWhiteEffect) - { - hue = Constants.DEAD_RANGE_COLOR; - } - - Vector3 hueVec = ShaderHueTranslator.GetHueVector(hue, data.IsPartialHue, data.IsTranslucent ? .5f : 1f, effect: true); - - if (Source != null) - { - depth = Source.CalculateDepthZ() + 1f; - } - - switch (Blend) - { - case GraphicEffectBlendMode.Multiply: - batcher.SetBlendState(_multiplyBlendState.Value); - - DrawStaticRotated - ( - batcher, - AnimationGraphic, - posX, - posY, - AngleToTarget, - hueVec, - depth - ); - - batcher.SetBlendState(null); - - break; - - case GraphicEffectBlendMode.Screen: - case GraphicEffectBlendMode.ScreenMore: - batcher.SetBlendState(_screenBlendState.Value); - - DrawStaticRotated - ( - batcher, - AnimationGraphic, - posX, - posY, - AngleToTarget, - hueVec, - depth - ); - - batcher.SetBlendState(null); - - break; - - case GraphicEffectBlendMode.ScreenLess: - batcher.SetBlendState(_screenLessBlendState.Value); - - DrawStaticRotated - ( - batcher, - AnimationGraphic, - posX, - posY, - AngleToTarget, - hueVec, - depth - ); - - batcher.SetBlendState(null); - - break; - - case GraphicEffectBlendMode.NormalHalfTransparent: - batcher.SetBlendState(_normalHalfBlendState.Value); - - DrawStaticRotated - ( - batcher, - AnimationGraphic, - posX, - posY, - AngleToTarget, - hueVec, - depth - ); - - batcher.SetBlendState(null); - - break; - - case GraphicEffectBlendMode.ShadowBlue: - batcher.SetBlendState(_shadowBlueBlendState.Value); - - DrawStaticRotated - ( - batcher, - AnimationGraphic, - posX, - posY, - AngleToTarget, - hueVec, - depth - ); - - batcher.SetBlendState(null); - - break; - - default: - //if (Graphic == 0x36BD) - //{ - // hueVector = ShaderHueTranslator.GetHueVector(0); - // HueVector.X = 0; - // HueVector.Y = ShaderHueTranslator.SHADER_LIGHTS; - // HueVector.Z = 0; - // batcher.SetBlendState(BlendState.Additive); - // base.Draw(batcher, posX, posY); - // batcher.SetBlendState(null); - //} - //else - - DrawStaticRotated - ( - batcher, - AnimationGraphic, - posX, - posY, - AngleToTarget, - hueVec, - depth - ); - - break; - } - - //Engine.DebugInfo.EffectsRendered++; - - - if (data.IsLight && Source != null) - { - Client.Game.GetScene().AddLight(Source, Source, posX + 22, posY + 22); - } - - return true; - } - - public override bool CheckMouseSelection() - { - return false; - } - - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/Views/ItemView.cs b/src/ClassicUO.Client/Game/GameObjects/Views/ItemView.cs deleted file mode 100644 index d9cf2c106..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/Views/ItemView.cs +++ /dev/null @@ -1,676 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.IO; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using MathHelper = ClassicUO.Utility.MathHelper; - -namespace ClassicUO.Game.GameObjects -{ - public partial class Item - { - private static EquipConvData? _equipConvData; - - public override bool Draw(UltimaBatcher2D batcher, int posX, int posY, float depth) - { - if (IsDestroyed) - { - return false; - } - - if ( - ItemData.IsLight - || DisplayedGraphic >= 0x3E02 && DisplayedGraphic <= 0x3E0B - || DisplayedGraphic >= 0x3914 && DisplayedGraphic <= 0x3929 - ) - { - Client.Game.GetScene().AddLight(this, this, posX + 22, posY + 22); - } - - if (!AllowedToDraw) - { - return false; - } - - //Engine.DebugInfo.ItemsRendered++; - Vector3 hueVec; - - posX += (int)Offset.X; - posY += (int)(Offset.Y + Offset.Z); - - float alpha = AlphaHue / 255f; - - if (IsCorpse) - { - hueVec = ShaderHueTranslator.GetHueVector(0, false, alpha); - return DrawCorpse(batcher, posX, posY - 3, hueVec, depth); - } - - ushort hue = Hue; - ushort graphic = DisplayedGraphic; - bool partial = ItemData.IsPartialHue; - - if (OnGround) - { - if (ItemData.IsAnimated) - { - if (ProfileManager.CurrentProfile.FieldsType == 2) - { - if (StaticFilters.IsFireField(Graphic)) - { - graphic = Constants.FIELD_REPLACE_GRAPHIC; - hue = 0x0020; - } - else if (StaticFilters.IsParalyzeField(Graphic)) - { - graphic = Constants.FIELD_REPLACE_GRAPHIC; - hue = 0x0058; - } - else if (StaticFilters.IsEnergyField(Graphic)) - { - graphic = Constants.FIELD_REPLACE_GRAPHIC; - hue = 0x0070; - } - else if (StaticFilters.IsPoisonField(Graphic)) - { - graphic = Constants.FIELD_REPLACE_GRAPHIC; - hue = 0x0044; - } - else if (StaticFilters.IsWallOfStone(Graphic)) - { - graphic = Constants.FIELD_REPLACE_GRAPHIC; - hue = 0x038A; - } - } - } - - if (ItemData.IsContainer && SelectedObject.SelectedContainer == this) - { - hue = 0x0035; - partial = false; - } - } - - if ( - ProfileManager.CurrentProfile.HighlightGameObjects - && ReferenceEquals(SelectedObject.Object, this) - ) - { - hue = Constants.HIGHLIGHT_CURRENT_OBJECT_HUE; - partial = false; - } - else if ( - ProfileManager.CurrentProfile.NoColorObjectsOutOfRange - && Distance > World.ClientViewRange - ) - { - hue = Constants.OUT_RANGE_COLOR; - } - else if (World.Player.IsDead && ProfileManager.CurrentProfile.EnableBlackWhiteEffect) - { - hue = Constants.DEAD_RANGE_COLOR; - } - else - { - if (!IsLocked && !IsMulti && ReferenceEquals(SelectedObject.Object, this)) - { - // TODO: check why i put this. - //isPartial = ItemData.Weight == 0xFF; - hue = 0x0035; - } - else if (IsHidden) - { - hue = 0x038E; - } - } - - hueVec = ShaderHueTranslator.GetHueVector(hue, partial, alpha); - - if (!IsMulti && !IsCoin && Amount > 1 && ItemData.IsStackable) - { - DrawStaticAnimated(batcher, graphic, posX - 5, posY - 5, hueVec, false, depth); - } - - if ( - !SerialHelper.IsValid(Serial) - && IsMulti - && TargetManager.TargetingState == CursorTarget.MultiPlacement - ) - { - hueVec.Z = 0.5f; - } - - DrawStaticAnimated(batcher, graphic, posX, posY, hueVec, false, depth); - - return true; - } - - private bool DrawCorpse( - UltimaBatcher2D batcher, - int posX, - int posY, - Vector3 hueVec, - float depth - ) - { - if (IsDestroyed || World.CorpseManager.Exists(Serial, 0)) - { - return false; - } - - posX += 22; - posY += 22; - - byte direction = (byte)((byte)Layer & 0x7F & 7); - AnimationsLoader.Instance.GetAnimDirection(ref direction, ref IsFlipped); - - byte animIndex = (byte)AnimIndex; - ushort graphic = GetGraphicForAnimation(); - - Client.Game.Animations.ConvertBodyIfNeeded(ref graphic); - var animGroup = Client.Game.Animations.GetAnimType(graphic); - var animFlags = Client.Game.Animations.GetAnimFlags(graphic); - byte group = AnimationsLoader.Instance.GetDeathAction( - graphic, - animFlags, - animGroup, - UsedLayer - ); - - bool ishuman = IsHumanCorpse; - - DrawLayer( - batcher, - posX, - posY, - this, - Layer.Invalid, - animIndex, - ishuman, - Hue, - IsFlipped, - hueVec.Z, - group, - direction, - hueVec, - depth - ); - - for (int i = 0; i < Constants.USED_LAYER_COUNT; i++) - { - Layer layer = LayerOrder.UsedLayers[direction, i]; - - DrawLayer( - batcher, - posX, - posY, - this, - layer, - animIndex, - ishuman, - 0, - IsFlipped, - hueVec.Z, - group, - direction, - hueVec, - depth - ); - } - - return true; - } - - private static void DrawLayer( - UltimaBatcher2D batcher, - int posX, - int posY, - Item owner, - Layer layer, - byte animIndex, - bool ishuman, - ushort color, - bool flipped, - float alpha, - byte animGroup, - byte dir, - Vector3 hueVec, - float depth - ) - { - _equipConvData = null; - bool ispartialhue = false; - - ushort graphic; - - if (layer == Layer.Invalid) - { - graphic = owner.GetGraphicForAnimation(); - } - else if (ishuman) - { - Item itemEquip = owner.FindItemByLayer(layer); - - if (itemEquip == null) - { - return; - } - - graphic = itemEquip.ItemData.AnimID; - ispartialhue = itemEquip.ItemData.IsPartialHue; - - if ( - AnimationsLoader.Instance.EquipConversions.TryGetValue( - graphic, - out Dictionary map - ) - ) - { - if (map.TryGetValue(graphic, out EquipConvData data)) - { - _equipConvData = data; - graphic = data.Graphic; - } - } - - color = itemEquip.Hue; - } - else - { - return; - } - - var frames = Client.Game.Animations.GetAnimationFrames( - graphic, - animGroup, - dir, - out var newHue, - out _, - isEquip: layer != Layer.Invalid, - isCorpse: layer == Layer.Invalid - ); - - if (color == 0) - { - color = newHue; - } - - if (frames.Length == 0) - { - return; - } - - int fc = frames.Length; - - if (fc > 0 && animIndex >= fc) - { - animIndex = (byte)(fc - 1); - } - - if (animIndex < frames.Length) - { - ref var spriteInfo = ref frames[animIndex]; - - if (spriteInfo.Texture == null) - { - return; - } - - if (flipped) - { - posX -= spriteInfo.UV.Width - spriteInfo.Center.X; - } - else - { - posX -= spriteInfo.Center.X; - } - - posY -= spriteInfo.UV.Height + spriteInfo.Center.Y; - - if (color == 0) - { - if ((color & 0x8000) != 0) - { - ispartialhue = true; - color &= 0x7FFF; - } - - if (color == 0 && _equipConvData.HasValue) - { - color = _equipConvData.Value.Color; - ispartialhue = false; - } - } - - if ( - ProfileManager.CurrentProfile.NoColorObjectsOutOfRange - && owner.Distance > World.ClientViewRange - ) - { - hueVec = ShaderHueTranslator.GetHueVector( - Constants.OUT_RANGE_COLOR + 1, - false, - 1 - ); - } - else if ( - World.Player.IsDead && ProfileManager.CurrentProfile.EnableBlackWhiteEffect - ) - { - hueVec = ShaderHueTranslator.GetHueVector( - Constants.DEAD_RANGE_COLOR + 1, - false, - 1 - ); - } - else - { - if ((ProfileManager.CurrentProfile.GridLootType > 0 || ProfileManager.CurrentProfile.UseGridLayoutContainerGumps) && SelectedObject.CorpseObject == owner) - { - color = 0x0034; - } - else if ( - ProfileManager.CurrentProfile.HighlightGameObjects - && ReferenceEquals(SelectedObject.Object, owner) - ) - { - color = Constants.HIGHLIGHT_CURRENT_OBJECT_HUE; - } - - hueVec = ShaderHueTranslator.GetHueVector(color, ispartialhue, alpha); - } - - Vector2 pos = new Vector2(posX, posY); - Rectangle rect = spriteInfo.UV; - - int diffY = (spriteInfo.UV.Height + spriteInfo.Center.Y); - int value = /*!isMounted && diffX <= 44 ? spriteInfo.UV.Height * 2 :*/ - Math.Max(1, diffY); - int count = Math.Max((spriteInfo.UV.Height / value) + 1, 2); - - rect.Height = Math.Min(value, rect.Height); - int remains = spriteInfo.UV.Height - rect.Height; - - int tiles = (byte)owner.Direction % 2 == 0 ? 2 : 2; - - for (int i = 0; i < count; ++i) - { - //hueVec.Y = 1; - //hueVec.X = 0x44 + (i * 20); - - batcher.Draw( - spriteInfo.Texture, - pos, - rect, - hueVec, - 0f, - Vector2.Zero, - 1f, - flipped ? SpriteEffects.FlipHorizontally : SpriteEffects.None, - depth + 1f + (i * tiles) - //depth + (i * tiles) + (owner.PriorityZ * 0.001f) - ); - - pos.Y += rect.Height; - rect.Y += rect.Height; - rect.Height = remains; // Math.Min(value, remains); - remains -= rect.Height; - } - } - } - - public override bool CheckMouseSelection() - { - if (!IsCorpse) - { - if ( - ReferenceEquals(SelectedObject.Object, this) - || TargetManager.TargetingState == CursorTarget.MultiPlacement - ) - { - return false; - } - - ushort graphic = DisplayedGraphic; - - if (OnGround && ItemData.IsAnimated) - { - if ( - ProfileManager.CurrentProfile.FieldsType == 2 - && ( - StaticFilters.IsFireField(Graphic) - || StaticFilters.IsParalyzeField(Graphic) - || StaticFilters.IsEnergyField(Graphic) - || StaticFilters.IsPoisonField(Graphic) - || StaticFilters.IsWallOfStone(Graphic) - ) - ) - { - graphic = Constants.FIELD_REPLACE_GRAPHIC; - } - else - { - ref UOFileIndex index = ref ArtLoader.Instance.GetValidRefEntry( - graphic + 0x4000 - ); - - graphic += (ushort)index.AnimOffset; - } - } - - if (Client.Game.Arts.GetArt(graphic).Texture != null) - { - ref var index = ref ArtLoader.Instance.GetValidRefEntry(graphic + 0x4000); - - Point position = RealScreenPosition; - position.X += (int)Offset.X; - position.Y += (int)(Offset.Y + Offset.Z); - position.X -= index.Width; - position.Y -= index.Height; - - if ( - Client.Game.Arts.PixelCheck( - graphic, - SelectedObject.TranslatedMousePositionByViewport.X - position.X, - SelectedObject.TranslatedMousePositionByViewport.Y - position.Y - ) - ) - { - return true; - } - else if (!IsMulti && !IsCoin && Amount > 1 && ItemData.IsStackable) - { - if ( - Client.Game.Arts.PixelCheck( - graphic, - SelectedObject.TranslatedMousePositionByViewport.X - position.X + 5, - SelectedObject.TranslatedMousePositionByViewport.Y - position.Y + 5 - ) - ) - { - return true; - } - } - } - } - else - { - if (!SerialHelper.IsValid(Serial)) - { - return false; - } - - if (ReferenceEquals(SelectedObject.Object, this)) - { - return true; - } - - Point position = RealScreenPosition; - position.X += 22; - position.Y += 22; - - byte direction = (byte)((byte)Layer & 0x7F & 7); - AnimationsLoader.Instance.GetAnimDirection(ref direction, ref IsFlipped); - byte animIndex = AnimIndex; - bool ishuman = - MathHelper.InRange(Amount, 0x0190, 0x0193) - || MathHelper.InRange(Amount, 0x00B7, 0x00BA) - || MathHelper.InRange(Amount, 0x025D, 0x0260) - || MathHelper.InRange(Amount, 0x029A, 0x029B) - || MathHelper.InRange(Amount, 0x02B6, 0x02B7) - || Amount == 0x03DB - || Amount == 0x03DF - || Amount == 0x03E2 - || Amount == 0x02E8 - || Amount == 0x02E9; - - for (int i = -1; i < Constants.USED_LAYER_COUNT; i++) - { - // yes im lazy - Layer layer = i == -1 ? Layer.Invalid : LayerOrder.UsedLayers[direction, i]; - - ushort graphic; - - if (layer == Layer.Invalid) - { - graphic = GetGraphicForAnimation(); - } - else if (ishuman) - { - Item itemEquip = FindItemByLayer(layer); - - if (itemEquip == null) - { - continue; - } - - graphic = itemEquip.ItemData.AnimID; - - if ( - AnimationsLoader.Instance.EquipConversions.TryGetValue( - graphic, - out Dictionary map - ) - ) - { - if (map.TryGetValue(graphic, out EquipConvData data)) - { - _equipConvData = data; - graphic = data.Graphic; - } - } - } - else - { - continue; - } - - Client.Game.Animations.ConvertBodyIfNeeded(ref graphic); - var animGroup = Client.Game.Animations.GetAnimType(graphic); - var animFlags = Client.Game.Animations.GetAnimFlags(graphic); - byte group = AnimationsLoader.Instance.GetDeathAction( - graphic, - animFlags, - animGroup, - UsedLayer - ); - var frames = Client.Game.Animations.GetAnimationFrames( - graphic, - group, - direction, - out _, - out var isUOP - ); - - if (frames.IsEmpty) - { - continue; - } - - if (animIndex < 0) - { - animIndex = 0; - } - - if (animIndex >= 0) - { - animIndex = (byte)(animIndex % frames.Length); - } - - ref var spriteInfo = ref frames[animIndex]; - - if (spriteInfo.Texture != null) - { - int x = - position.X - - ( - IsFlipped - ? spriteInfo.UV.Width - spriteInfo.Center.X - : spriteInfo.Center.X - ); - int y = position.Y - (spriteInfo.UV.Height + spriteInfo.Center.Y); - - if ( - Client.Game.Animations.PixelCheck( - graphic, - group, - direction, - isUOP, - animIndex, - IsFlipped - ? x - + spriteInfo.UV.Width - - SelectedObject.TranslatedMousePositionByViewport.X - : SelectedObject.TranslatedMousePositionByViewport.X - x, - SelectedObject.TranslatedMousePositionByViewport.Y - y - ) - ) - { - return true; - } - } - } - } - - return false; - } - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/Views/LandView.cs b/src/ClassicUO.Client/Game/GameObjects/Views/LandView.cs deleted file mode 100644 index f1bf5f753..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/Views/LandView.cs +++ /dev/null @@ -1,221 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using System; -using ClassicUO.Game.Managers; - -namespace ClassicUO.Game.GameObjects -{ - internal sealed partial class Land - { - public override bool Draw(UltimaBatcher2D batcher, int posX, int posY, float depth) - { - if (!AllowedToDraw || IsDestroyed) - { - return false; - } - - //Engine.DebugInfo.LandsRendered++; - - ushort hue = Hue; - - if (ProfileManager.CurrentProfile.HighlightGameObjects && SelectedObject.Object == this) - { - hue = Constants.HIGHLIGHT_CURRENT_OBJECT_HUE; - } - else if ( - ProfileManager.CurrentProfile.NoColorObjectsOutOfRange - && Distance > World.ClientViewRange - ) - { - hue = Constants.OUT_RANGE_COLOR; - } - else if (World.Player.IsDead && ProfileManager.CurrentProfile.EnableBlackWhiteEffect) - { - hue = Constants.DEAD_RANGE_COLOR; - } - else - { - if (SelectedObject.Object == this) - { - SpellVisualRangeManager.Instance.LastCursorTileLoc = new Vector2(X, Y); - } - if (SpellVisualRangeManager.Instance.IsTargetingAfterCasting()) - { - hue = SpellVisualRangeManager.Instance.ProcessHueForTile(hue, this); - } - - if (TileMarkerManager.Instance.IsTileMarked(X, Y, World.Map.Index, out var nhue)) - hue = nhue; - - if (ProfileManager.CurrentProfile.DisplayRadius && Distance == ProfileManager.CurrentProfile.DisplayRadiusDistance) - hue = ProfileManager.CurrentProfile.DisplayRadiusHue; - } - - Vector3 hueVec; - if (hue != 0) - { - hueVec.X = hue - 1; - hueVec.Y = IsStretched - ? ShaderHueTranslator.SHADER_LAND_HUED - : ShaderHueTranslator.SHADER_HUED; - } - else - { - hueVec.X = 0; - hueVec.Y = IsStretched - ? ShaderHueTranslator.SHADER_LAND - : ShaderHueTranslator.SHADER_NONE; - } - hueVec.Z = 1f; - - if (IsStretched) - { - posY += Z << 2; - - ref readonly var texmapInfo = ref Client.Game.Texmaps.GetTexmap( - TileDataLoader.Instance.LandData[Graphic].TexID - ); - - if (texmapInfo.Texture != null) - { - batcher.DrawStretchedLand( - texmapInfo.Texture, - new Vector2(posX, posY), - texmapInfo.UV, - ref YOffsets, - ref NormalTop, - ref NormalRight, - ref NormalLeft, - ref NormalBottom, - hueVec, - depth + 0.5f - ); - } - else - { - DrawStatic( - batcher, - Graphic, - posX, - posY, - hueVec, - depth, - ProfileManager.CurrentProfile.AnimatedWaterEffect && TileData.IsWet - ); - } - } - else - { - ref readonly var artInfo = ref Client.Game.Arts.GetLand(Graphic); - - ref readonly var texmapInfo = ref Client.Game.Texmaps.GetTexmap( - TileDataLoader.Instance.LandData[Graphic].TexID - ); - - if (artInfo.Texture != null) - { - var pos = new Vector2(posX, posY); - var scale = Vector2.One; - - if (ProfileManager.CurrentProfile.AnimatedWaterEffect && TileData.IsWet) - { - batcher.Draw( - artInfo.Texture, - pos, - artInfo.UV, - hueVec, - 0f, - Vector2.Zero, - scale, - SpriteEffects.None, - depth + 0.5f - ); - - var sin = (float)Math.Sin(Time.Ticks / 1000f); - var cos = (float)Math.Cos(Time.Ticks / 1000f); - scale = new Vector2(1.1f + sin * 0.1f, 1.1f + cos * 0.5f * 0.1f); - } - - if (texmapInfo.Texture != null && ProfileManager.CurrentProfile.UseLandTextures) - { - batcher.Draw( - texmapInfo.Texture, - new Rectangle(posX, posY, artInfo.UV.Width, artInfo.UV.Height), - texmapInfo.UV, - hueVec, - 0f, - Vector2.Zero, - SpriteEffects.None, - depth + 0.5f - ); - } - else - { - batcher.Draw( - artInfo.Texture, - pos, - artInfo.UV, - hueVec, - 0f, - Vector2.Zero, - scale, - SpriteEffects.None, - depth + 0.5f - ); - } - } - } - - return true; - } - - public override bool CheckMouseSelection() - { - if (IsStretched) - { - return SelectedObject.IsPointInStretchedLand( - ref YOffsets, - RealScreenPosition.X, - RealScreenPosition.Y + (Z << 2) - ); - } - - return SelectedObject.IsPointInLand(RealScreenPosition.X, RealScreenPosition.Y); - } - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/Views/LightningEffectView.cs b/src/ClassicUO.Client/Game/GameObjects/Views/LightningEffectView.cs deleted file mode 100644 index 5bc4f3f0f..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/Views/LightningEffectView.cs +++ /dev/null @@ -1,84 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.IO; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.GameObjects -{ - internal sealed partial class LightningEffect - { - public override bool Draw(UltimaBatcher2D batcher, int posX, int posY, float depth) - { - ushort hue = Hue; - - if (ProfileManager.CurrentProfile.NoColorObjectsOutOfRange && Distance > World.ClientViewRange) - { - hue = Constants.OUT_RANGE_COLOR; - } - else if (World.Player.IsDead && ProfileManager.CurrentProfile.EnableBlackWhiteEffect) - { - hue = Constants.DEAD_RANGE_COLOR; - } - - Vector3 hueVec = ShaderHueTranslator.GetHueVector(hue, false, 1); - hueVec.Y = hueVec.X > 1.0f ? ShaderHueTranslator.SHADER_LIGHTS : ShaderHueTranslator.SHADER_NONE; - - //Engine.DebugInfo.EffectsRendered++; - - ref UOFileIndex index = ref GumpsLoader.Instance.GetValidRefEntry(AnimationGraphic); - - posX -= index.Width >> 1; - posY -= index.Height; - - batcher.SetBlendState(BlendState.Additive); - - DrawGump - ( - batcher, - AnimationGraphic, - posX, - posY, - hueVec, - depth - ); - - batcher.SetBlendState(null); - - return true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/GameObjects/Views/MobileView.cs b/src/ClassicUO.Client/Game/GameObjects/Views/MobileView.cs deleted file mode 100644 index abf092477..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/Views/MobileView.cs +++ /dev/null @@ -1,1381 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using System; -using System.Collections.Generic; - -namespace ClassicUO.Game.GameObjects -{ - public partial class Mobile - { - private const int SIT_OFFSET_Y = 4; - private static EquipConvData? _equipConvData; - private static int _characterFrameStartY; - private static int _startCharacterWaistY; - private static int _startCharacterKneesY; - private static int _startCharacterFeetY; - private static int _characterFrameHeight; - - public override bool Draw(UltimaBatcher2D batcher, int posX, int posY, float depth) - { - if (IsDestroyed || !AllowedToDraw) - { - return false; - } - - bool charSitting = false; - ushort overridedHue = 0; - - AnimationsLoader.SittingInfoData seatData = AnimationsLoader.SittingInfoData.Empty; - _equipConvData = null; - FrameInfo.X = 0; - FrameInfo.Y = 0; - FrameInfo.Width = 0; - FrameInfo.Height = 0; - - posY -= 3; - int drawX = posX + (int)Offset.X; - int drawY = posY + (int)(Offset.Y - Offset.Z); - - drawX += 22; - drawY += 22; - - bool hasShadow = !IsDead && !IsHidden && ProfileManager.CurrentProfile.ShadowsEnabled; - bool inParty = World.Party.Contains(this); - - if (AuraManager.IsEnabled) - { - AuraManager.Draw( - batcher, - drawX, - drawY, - ProfileManager.CurrentProfile.PartyAura && inParty - ? ProfileManager.CurrentProfile.PartyAuraHue - : Notoriety.GetHue(NotorietyFlag), - depth + 1f - ); - } - - bool isHuman = IsHuman; - - bool isGargoyle = - Client.Version >= ClientVersion.CV_7000 - && (Graphic == 666 || Graphic == 667 || Graphic == 0x02B7 || Graphic == 0x02B6); - - Vector3 hueVec = ShaderHueTranslator.GetHueVector(0, false, AlphaHue / 255f); - - if (World.Player == this && ProfileManager.CurrentProfile.PlayerConstantAlpha != 100) - { - hueVec = ShaderHueTranslator.GetHueVector(0, false, (float)ProfileManager.CurrentProfile.PlayerConstantAlpha / 100f); - } - - if (ProfileManager.CurrentProfile.HighlightGameObjects && ReferenceEquals(SelectedObject.Object, this)) - { - overridedHue = Constants.HIGHLIGHT_CURRENT_OBJECT_HUE; - hueVec.Y = 1; - } - else if (SelectedObject.HealthbarObject == this) - { - overridedHue = Notoriety.GetHue(NotorietyFlag); - } - else if ( - ProfileManager.CurrentProfile.NoColorObjectsOutOfRange - && Distance > World.ClientViewRange - ) - { - overridedHue = Constants.OUT_RANGE_COLOR; - hueVec.Y = 1; - } - else if (World.Player.IsDead && ProfileManager.CurrentProfile.EnableBlackWhiteEffect) - { - overridedHue = Constants.DEAD_RANGE_COLOR; - hueVec.Y = 1; - } - else if (IsHidden) - { - overridedHue = ProfileManager.CurrentProfile.HiddenBodyHue; - hueVec = ShaderHueTranslator.GetHueVector(0, false, ((float)ProfileManager.CurrentProfile.HiddenBodyAlpha / 100)); - } - else - { - overridedHue = 0; - - if (IsDead) - { - if (!isHuman) - { - overridedHue = 0x0386; - } - } - else - { - if (ProfileManager.CurrentProfile.HighlightMobilesByPoisoned) - { - if (IsPoisoned) - { - overridedHue = ProfileManager.CurrentProfile.PoisonHue; - } - } - if (ProfileManager.CurrentProfile.HighlightMobilesByParalize) - { - if (IsParalyzed && NotorietyFlag != NotorietyFlag.Invulnerable) - { - overridedHue = ProfileManager.CurrentProfile.ParalyzedHue; - } - } - if (ProfileManager.CurrentProfile.HighlightMobilesByInvul) - { - if (NotorietyFlag != NotorietyFlag.Invulnerable && IsYellowHits) - { - overridedHue = ProfileManager.CurrentProfile.InvulnerableHue; - } - } - } - } - - bool isAttack = Serial == TargetManager.LastAttack; - bool isUnderMouse = - TargetManager.IsTargeting && ReferenceEquals(SelectedObject.Object, this); - - if (Serial != World.Player.Serial) - { - if (isAttack || isUnderMouse) - { - overridedHue = Notoriety.GetHue(NotorietyFlag); - } - else if (inParty && ProfileManager.CurrentProfile != null && ProfileManager.CurrentProfile.OverridePartyAndGuildHue) - { - overridedHue = ProfileManager.CurrentProfile.FriendHue; - } - } - - ProcessSteps(out byte dir); - byte layerDir = dir; - - AnimationsLoader.Instance.GetAnimDirection(ref dir, ref IsFlipped); - - ushort graphic = GetGraphicForAnimation(); - byte animGroup = GetGroupForAnimation(this, graphic, true); - byte animIndex = AnimIndex; - - Item mount = FindItemByLayer(Layer.Mount); - sbyte mountOffsetY = 0; - - if (isHuman && mount != null && mount.Graphic != 0x3E96) - { - ushort mountGraphic = mount.GetGraphicForAnimation(); - byte animGroupMount = 0; - - if ( - mountGraphic != 0xFFFF - && mountGraphic < Client.Game.Animations.MaxAnimationCount - ) - { - mountOffsetY = Client.Game.Animations.GetMountedHeightOffset(mountGraphic); - - if (hasShadow) - { - DrawInternal( - batcher, - this, - null, - drawX, - drawY + 10, - hueVec, - IsFlipped, - animIndex, - true, - graphic, - animGroup, - dir, - isHuman, - false, - false, - false, - depth, - mountOffsetY, - overridedHue, - charSitting - ); - - animGroupMount = GetGroupForAnimation(this, mountGraphic); - - DrawInternal( - batcher, - this, - mount, - drawX, - drawY, - hueVec, - IsFlipped, - animIndex, - true, - mountGraphic, - animGroupMount, - dir, - isHuman, - false, - false, - false, - depth, - mountOffsetY, - overridedHue, - charSitting - ); - } - else - { - animGroupMount = GetGroupForAnimation(this, mountGraphic); - } - - DrawInternal( - batcher, - this, - mount, - drawX, - drawY, - hueVec, - IsFlipped, - animIndex, - false, - mountGraphic, - animGroupMount, - dir, - isHuman, - false, - true, - false, - depth, - mountOffsetY, - overridedHue, - charSitting - ); - - drawY += mountOffsetY; - } - } - else - { - if (TryGetSittingInfo(out seatData)) - { - animGroup = (byte)PeopleAnimationGroup.Stand; - animIndex = 0; - - ProcessSteps(out dir); - - AnimationsLoader.Instance.FixSittingDirection( - ref dir, - ref IsFlipped, - ref drawX, - ref drawY, - ref seatData - ); - - drawY += SIT_OFFSET_Y; - - if (dir == 3) - { - if (IsGargoyle) - { - drawY -= 30 - SIT_OFFSET_Y; - animGroup = 42; - } - else - { - animGroup = 25; - } - } - else if (IsGargoyle) - { - animGroup = 42; - } - else - { - charSitting = true; - } - } - else if (hasShadow) - { - DrawInternal( - batcher, - this, - null, - drawX, - drawY, - hueVec, - IsFlipped, - animIndex, - true, - graphic, - animGroup, - dir, - isHuman, - false, - false, - false, - depth, - mountOffsetY, - overridedHue, - charSitting - ); - } - } - - DrawInternal( - batcher, - this, - null, - drawX, - drawY, - hueVec, - IsFlipped, - animIndex, - false, - graphic, - animGroup, - dir, - isHuman, - false, - false, - isGargoyle, - depth, - mountOffsetY, - overridedHue, - charSitting - ); - - if (!IsEmpty) - { - for (int i = 0; i < Constants.USED_LAYER_COUNT; i++) - { - Layer layer = LayerOrder.UsedLayers[layerDir, i]; - - Item item = FindItemByLayer(layer); - - if (item == null) - { - continue; - } - - if (IsDead && (layer == Layer.Hair || layer == Layer.Beard)) - { - continue; - } - - if (isHuman) - { - if (ProfileManager.CurrentProfile.HiddenLayers.Contains((int)layer) && ((ProfileManager.CurrentProfile.HideLayersForSelf && Serial == World.Player.Serial) || !ProfileManager.CurrentProfile.HideLayersForSelf)) - { - continue; - } - - if (IsCovered(this, layer)) - { - continue; - } - - if (item.ItemData.AnimID != 0) - { - graphic = item.ItemData.AnimID; - - if (isGargoyle) - { - FixGargoyleEquipments(ref graphic); - } - - if ( - AnimationsLoader.Instance.EquipConversions.TryGetValue( - Graphic, - out Dictionary map - ) - ) - { - if (map.TryGetValue(item.ItemData.AnimID, out EquipConvData data)) - { - _equipConvData = data; - graphic = data.Graphic; - } - } - - DrawInternal( - batcher, - this, - item, - drawX, - drawY, - hueVec, - IsFlipped, - animIndex, - false, - graphic, - isGargoyle /*&& item.ItemData.IsWeapon*/ - && seatData.Graphic == 0 - ? GetGroupForAnimation(this, graphic, true) - : animGroup, - dir, - isHuman, - true, - false, - isGargoyle, - depth, - mountOffsetY, - overridedHue, - charSitting - ); - } - else - { - if (item.ItemData.IsLight) - { - Client.Game - .GetScene() - .AddLight(this, item, drawX, drawY); - } - } - - _equipConvData = null; - } - else - { - if (item.ItemData.IsLight) - { - Client.Game.GetScene().AddLight(this, item, drawX, drawY); - - /*DrawInternal - ( - batcher, - this, - item, - drawX, - drawY, - IsFlipped, - animIndex, - false, - graphic, - animGroup, - dir, - isHuman, - false, - alpha: HueVector.Z - ); - */ - //break; - } - } - } - } - - //if (FileManager.Animations.SittingValue != 0) - //{ - // ref var sittingData = ref FileManager.Animations.SittingInfos[FileManager.Animations.SittingValue - 1]; - - // if (FileManager.Animations.Direction == 3 && sittingData.DrawBack && - // HasEquipment && Equipment[(int) Layer.Cloak] == null) - // { - - // } - //} - // - - FrameInfo.X = Math.Abs(FrameInfo.X); - FrameInfo.Y = Math.Abs(FrameInfo.Y); - FrameInfo.Width = FrameInfo.X + FrameInfo.Width; - FrameInfo.Height = FrameInfo.Y + FrameInfo.Height; - - return true; - } - - private static ushort GetAnimationInfo(Mobile owner, Item item, bool isGargoyle) - { - if (item.ItemData.AnimID != 0) - { - var graphic = item.ItemData.AnimID; - - if (isGargoyle) - { - FixGargoyleEquipments(ref graphic); - } - - if ( - AnimationsLoader.Instance.EquipConversions.TryGetValue( - owner.Graphic, - out Dictionary map - ) - ) - { - if (map.TryGetValue(item.ItemData.AnimID, out EquipConvData data)) - { - _equipConvData = data; - graphic = data.Graphic; - } - } - - return graphic; - } - - return 0xFFFF; - } - - private static void FixGargoyleEquipments(ref ushort graphic) - { - switch (graphic) - { - // gargoyle robe - case 0x01D5: - graphic = 0x0156; - - break; - - // gargoyle dead shroud - case 0x03CA: - graphic = 0x0223; - - break; - - // gargoyle spellbook - case 0x03D8: - graphic = 329; - - break; - - // gargoyle necrobook - case 0x0372: - graphic = 330; - - break; - - // gargoyle chivalry book - case 0x0374: - graphic = 328; - - break; - - // gargoyle bushido book - case 0x036F: - graphic = 327; - - break; - - // gargoyle ninjitsu book - case 0x036E: - graphic = 328; - - break; - - // gargoyle masteries book - case 0x0426: - graphic = 0x042B; - - break; - //NOTE: gargoyle mysticism book seems ok. Mha! - - - /* into the mobtypes.txt file of 7.0.90+ client version we have: - * - * 1529 EQUIPMENT 0 # EQUIP_Shield_Pirate_Male_H - * 1530 EQUIPMENT 0 # EQUIP_Shield_Pirate_Female_H - * 1531 EQUIPMENT 10000 # Equip_Shield_Pirate_Male_G - * 1532 EQUIPMENT 10000 # Equip_Shield_Pirate_Female_G - * - * This means that graphic 0xA649 [pirate shield] has 4 tiledata infos. - * Standard client handles it automatically without any issue. - * Maybe it's hardcoded into the client - */ - - // EQUIP_Shield_Pirate_Male_H - case 1529: - graphic = 1531; - - break; - - // EQUIP_Shield_Pirate_Female_H - case 1530: - graphic = 1532; - - break; - } - } - - private static bool GetTexture( - ushort graphic, - byte animGroup, - ref byte animIndex, - byte direction, - out SpriteInfo spriteInfo, - out bool isUOP - ) - { - spriteInfo = default; - - var frames = Client.Game.Animations.GetAnimationFrames( - graphic, - animGroup, - direction, - out _, - out isUOP - ); - - if (frames.Length == 0) - { - return false; - } - - if (animIndex < 0) - { - animIndex = 0; - } - - animIndex = (byte)(animIndex % frames.Length); - - spriteInfo = frames[animIndex]; - - if (spriteInfo.Texture == null) - { - return false; - } - - return true; - } - - private static void DrawInternal( - UltimaBatcher2D batcher, - Mobile owner, - Item entity, - int x, - int y, - Vector3 hueVec, - bool mirror, - byte frameIndex, - bool hasShadow, - ushort id, - byte animGroup, - byte dir, - bool isHuman, - bool isEquip, - bool isMount, - bool forceUOP, - float depth, - sbyte mountOffset, - ushort overridedHue, - bool charIsSitting - ) - { - if (id >= Client.Game.Animations.MaxAnimationCount || owner == null) - { - return; - } - - var frames = Client.Game.Animations.GetAnimationFrames( - id, - animGroup, - dir, - out var hueFromFile, - out _, - isEquip, - false, - forceUOP - ); - - if (hueFromFile == 0) - { - hueFromFile = overridedHue; - } - - if (frames.Length == 0) - { - return; - } - - if (frameIndex >= frames.Length) - { - frameIndex = (byte)(frames.Length - 1); - } - else if (frameIndex < 0) - { - frameIndex = 0; - } - - ref var spriteInfo = ref frames[frameIndex % frames.Length]; - - if (spriteInfo.Texture == null) - { - if (!(charIsSitting && entity == null && !hasShadow)) - { - return; - } - - goto SKIP; - } - - if (mirror) - { - x -= spriteInfo.UV.Width - spriteInfo.Center.X; - } - else - { - x -= spriteInfo.Center.X; - } - - y -= spriteInfo.UV.Height + spriteInfo.Center.Y; - - SKIP: - - if (hasShadow) - { - batcher.DrawShadow( - spriteInfo.Texture, - new Vector2(x, y), - spriteInfo.UV, - mirror, - depth - ); - } - else - { - ushort hue = overridedHue; - bool partialHue = false; - - if (hue == 0) - { - hue = entity?.Hue ?? owner.Hue; - partialHue = !isMount && entity != null && entity.ItemData.IsPartialHue; - - if ((hue & 0x8000) != 0) - { - partialHue = true; - hue &= 0x7FFF; - } - - if (hue == 0) - { - hue = hueFromFile; - - if (hue == 0 && _equipConvData.HasValue) - { - hue = _equipConvData.Value.Color; - } - - partialHue = false; - } - } - - hueVec = ShaderHueTranslator.GetHueVector(hue, partialHue, hueVec.Z); - - if (spriteInfo.Texture != null) - { - Vector2 pos = new Vector2(x, y); - Rectangle rect = spriteInfo.UV; - - if (charIsSitting) - { - Vector3 mod = CalculateSitAnimation(y, entity, isHuman, ref spriteInfo); - - batcher.DrawCharacterSitted( - spriteInfo.Texture, - pos, - rect, - mod, - hueVec, - mirror, - depth + 1f - ); - } - else - { - int diffY = (spriteInfo.UV.Height + spriteInfo.Center.Y) - mountOffset; - - int value = Math.Max(1, diffY); - int count = Math.Max((spriteInfo.UV.Height / value) + 1, 2); - - rect.Height = Math.Min(value, rect.Height); - int remains = spriteInfo.UV.Height - rect.Height; - - int tiles = (byte)owner.Direction % 2 == 0 ? 2 : 2; - - for (int i = 0; i < count; ++i) - { - batcher.Draw( - spriteInfo.Texture, - pos, - rect, - hueVec, - 0f, - Vector2.Zero, - 1f, - mirror ? SpriteEffects.FlipHorizontally : SpriteEffects.None, - depth + 1f + (i * tiles) - ); - - pos.Y += rect.Height; - rect.Y += rect.Height; - rect.Height = remains; - remains -= rect.Height; - } - } - - int xx = -spriteInfo.Center.X; - int yy = -(spriteInfo.UV.Height + spriteInfo.Center.Y + 3); - - if (mirror) - { - xx = -(spriteInfo.UV.Width - spriteInfo.Center.X); - } - - if (xx < owner.FrameInfo.X) - { - owner.FrameInfo.X = xx; - } - - if (yy < owner.FrameInfo.Y) - { - owner.FrameInfo.Y = yy; - } - - if (owner.FrameInfo.Width < xx + spriteInfo.UV.Width) - { - owner.FrameInfo.Width = xx + spriteInfo.UV.Width; - } - - if (owner.FrameInfo.Height < yy + spriteInfo.UV.Height) - { - owner.FrameInfo.Height = yy + spriteInfo.UV.Height; - } - } - - if (entity != null && entity.ItemData.IsLight) - { - Client.Game - .GetScene() - .AddLight(owner, entity, mirror ? x + spriteInfo.UV.Width : x, y); - } - } - } - - private static Vector3 CalculateSitAnimation( - int y, - Item entity, - bool isHuman, - ref SpriteInfo spriteInfo - ) - { - Vector3 mod = new Vector3(); - - const float UPPER_BODY_RATIO = 0.35f; - const float MID_BODY_RATIO = 0.60f; - const float LOWER_BODY_RATIO = 0.94f; - - if (entity == null && isHuman) - { - int frameHeight = spriteInfo.UV.Height; - if (frameHeight == 0) - { - frameHeight = 61; - } - - _characterFrameStartY = - y - (spriteInfo.Texture != null ? 0 : frameHeight - SIT_OFFSET_Y); - _characterFrameHeight = frameHeight; - _startCharacterWaistY = - (int)(frameHeight * UPPER_BODY_RATIO) + _characterFrameStartY; - _startCharacterKneesY = (int)(frameHeight * MID_BODY_RATIO) + _characterFrameStartY; - _startCharacterFeetY = - (int)(frameHeight * LOWER_BODY_RATIO) + _characterFrameStartY; - - if (spriteInfo.Texture == null) - { - return mod; - } - } - - mod.X = UPPER_BODY_RATIO; - mod.Y = MID_BODY_RATIO; - mod.Z = LOWER_BODY_RATIO; - - if (entity != null) - { - float itemsEndY = y + spriteInfo.UV.Height; - - if (y >= _startCharacterWaistY) - { - mod.X = 0; - } - else if (itemsEndY <= _startCharacterWaistY) - { - mod.X = 1.0f; - } - else - { - float upperBodyDiff = _startCharacterWaistY - y; - mod.X = upperBodyDiff / spriteInfo.UV.Height; - - if (mod.X < 0) - { - mod.X = 0; - } - } - - if (_startCharacterWaistY >= itemsEndY || y >= _startCharacterKneesY) - { - mod.Y = 0; - } - else if (_startCharacterWaistY <= y && itemsEndY <= _startCharacterKneesY) - { - mod.Y = 1.0f; - } - else - { - float midBodyDiff; - - if (y >= _startCharacterWaistY) - { - midBodyDiff = _startCharacterKneesY - y; - } - else if (itemsEndY <= _startCharacterKneesY) - { - midBodyDiff = itemsEndY - _startCharacterWaistY; - } - else - { - midBodyDiff = _startCharacterKneesY - _startCharacterWaistY; - } - - mod.Y = mod.X + midBodyDiff / spriteInfo.UV.Height; - - if (mod.Y < 0) - { - mod.Y = 0; - } - } - - if (itemsEndY <= _startCharacterKneesY) - { - mod.Z = 0; - } - else if (y >= _startCharacterKneesY) - { - mod.Z = 1.0f; - } - else - { - float lowerBodyDiff = itemsEndY - _startCharacterKneesY; - mod.Z = mod.Y + lowerBodyDiff / spriteInfo.UV.Height; - - if (mod.Z < 0) - { - mod.Z = 0; - } - } - } - - return mod; - } - - public override bool CheckMouseSelection() - { - Point position = RealScreenPosition; - position.Y -= 3; - position.X += (int)Offset.X + 22; - position.Y += (int)(Offset.Y - Offset.Z) + 22; - - Rectangle r = FrameInfo; - r.X = position.X - r.X; - r.Y = position.Y - r.Y; - - if (!r.Contains(SelectedObject.TranslatedMousePositionByViewport)) - { - return false; - } - - bool isHuman = IsHuman; - bool isGargoyle = - Client.Version >= ClientVersion.CV_7000 - && (Graphic == 666 || Graphic == 667 || Graphic == 0x02B7 || Graphic == 0x02B6); - - ProcessSteps(out byte dir); - bool isFlipped = IsFlipped; - AnimationsLoader.Instance.GetAnimDirection(ref dir, ref isFlipped); - - ushort graphic = GetGraphicForAnimation(); - byte animGroup = GetGroupForAnimation(this, graphic, true); - byte animIndex = AnimIndex; - - byte animGroupBackup = animGroup; - byte animIndexBackup = animIndex; - - SpriteInfo spriteInfo; - bool isUop; - - if (isHuman) - { - Item mount = FindItemByLayer(Layer.Mount); - if (mount != null) - { - var mountGraphic = mount.GetGraphicForAnimation(); - - if (mountGraphic != 0xFFFF) - { - var animGroupMount = GetGroupForAnimation(this, mountGraphic); - - if ( - GetTexture( - mountGraphic, - animGroupMount, - ref animIndex, - dir, - out spriteInfo, - out isUop - ) - ) - { - int x = - position.X - - ( - isFlipped - ? spriteInfo.UV.Width - spriteInfo.Center.X - : spriteInfo.Center.X - ); - int y = position.Y - (spriteInfo.UV.Height + spriteInfo.Center.Y); - - if ( - Client.Game.Animations.PixelCheck( - mountGraphic, - animGroupMount, - dir, - isUop, - animIndex, - isFlipped - ? x - + spriteInfo.UV.Width - - SelectedObject.TranslatedMousePositionByViewport.X - : SelectedObject.TranslatedMousePositionByViewport.X - x, - SelectedObject.TranslatedMousePositionByViewport.Y - y - ) - ) - { - return true; - } - - position.Y += Client.Game.Animations.GetMountedHeightOffset( - mountGraphic - ); - } - } - } - } - - if (GetTexture(graphic, animGroup, ref animIndex, dir, out spriteInfo, out isUop)) - { - int x = - position.X - - (isFlipped ? spriteInfo.UV.Width - spriteInfo.Center.X : spriteInfo.Center.X); - int y = position.Y - (spriteInfo.UV.Height + spriteInfo.Center.Y); - - if ( - Client.Game.Animations.PixelCheck( - graphic, - animGroup, - dir, - isUop, - animIndex, - isFlipped - ? x - + spriteInfo.UV.Width - - SelectedObject.TranslatedMousePositionByViewport.X - : SelectedObject.TranslatedMousePositionByViewport.X - x, - SelectedObject.TranslatedMousePositionByViewport.Y - y - ) - ) - { - return true; - } - } - - if (!IsEmpty && isHuman) - { - for (Layer layer = Layer.Invalid + 1; layer < Layer.Mount; ++layer) - { - Item item = FindItemByLayer(layer); - - if ( - item == null - || (IsDead && (layer == Layer.Hair || layer == Layer.Beard)) - || IsCovered(this, layer) - ) - { - continue; - } - - graphic = GetAnimationInfo(this, item, isGargoyle); - - if (graphic != 0xFFFF) - { - animGroup = animGroupBackup; - animIndex = animIndexBackup; - - if ( - GetTexture( - graphic, - animGroup, - ref animIndex, - dir, - out spriteInfo, - out isUop - ) - ) - { - int x = - position.X - - ( - isFlipped - ? spriteInfo.UV.Width - spriteInfo.Center.X - : spriteInfo.Center.X - ); - int y = position.Y - (spriteInfo.UV.Height + spriteInfo.Center.Y); - - if ( - Client.Game.Animations.PixelCheck( - graphic, - animGroup, - dir, - isUop, - animIndex, - isFlipped - ? x - + spriteInfo.UV.Width - - SelectedObject.TranslatedMousePositionByViewport.X - : SelectedObject.TranslatedMousePositionByViewport.X - x, - SelectedObject.TranslatedMousePositionByViewport.Y - y - ) - ) - { - return true; - } - } - } - } - } - - return false; - } - - internal static bool IsCovered(Mobile mobile, Layer layer) - { - if (mobile.IsEmpty) - { - return false; - } - - switch (layer) - { - case Layer.Shoes: - Item pants = mobile.FindItemByLayer(Layer.Pants); - Item robe; - - if ( - mobile.FindItemByLayer(Layer.Legs) != null - || pants != null - && ( - pants.Graphic == 0x1411 /*|| pants.Graphic == 0x141A*/ - ) - ) - { - return true; - } - else - { - robe = mobile.FindItemByLayer(Layer.Robe); - - if ( - pants != null && (pants.Graphic == 0x0513 || pants.Graphic == 0x0514) - || robe != null && robe.Graphic == 0x0504 - ) - { - return true; - } - } - - break; - - case Layer.Pants: - - robe = mobile.FindItemByLayer(Layer.Robe); - pants = mobile.FindItemByLayer(Layer.Pants); - - if ( - mobile.FindItemByLayer(Layer.Legs) != null - || robe != null && robe.Graphic == 0x0504 - ) - { - return true; - } - - if ( - pants != null - && ( - pants.Graphic == 0x01EB - || pants.Graphic == 0x03E5 - || pants.Graphic == 0x03eB - ) - ) - { - Item skirt = mobile.FindItemByLayer(Layer.Skirt); - - if (skirt != null && skirt.Graphic != 0x01C7 && skirt.Graphic != 0x01E4) - { - return true; - } - - if ( - robe != null - && robe.Graphic != 0x0229 - && (robe.Graphic <= 0x04E7 || robe.Graphic > 0x04EB) - ) - { - return true; - } - } - - break; - - case Layer.Tunic: - robe = mobile.FindItemByLayer(Layer.Robe); - Item tunic = mobile.FindItemByLayer(Layer.Tunic); - - /*if (robe != null && robe.Graphic != 0) - return true; - else*/ - if (tunic != null && tunic.Graphic == 0x0238) - { - return robe != null - && robe.Graphic != 0x9985 - && robe.Graphic != 0x9986 - && robe.Graphic != 0xA412; - } - - break; - - case Layer.Torso: - robe = mobile.FindItemByLayer(Layer.Robe); - - if ( - robe != null - && robe.Graphic != 0 - && robe.Graphic != 0x9985 - && robe.Graphic != 0x9986 - && robe.Graphic != 0xA412 - && robe.Graphic != 0xA2CA - ) - { - return true; - } - else - { - tunic = mobile.FindItemByLayer(Layer.Tunic); - - if (tunic != null && tunic.Graphic != 0x1541 && tunic.Graphic != 0x1542) - { - Item torso = mobile.FindItemByLayer(Layer.Torso); - - if ( - torso != null - && (torso.Graphic == 0x782A || torso.Graphic == 0x782B) - ) - { - return true; - } - } - } - - break; - - case Layer.Arms: - robe = mobile.FindItemByLayer(Layer.Robe); - - return robe != null - && robe.Graphic != 0 - && robe.Graphic != 0x9985 - && robe.Graphic != 0x9986 - && robe.Graphic != 0xA412; - - case Layer.Helmet: - case Layer.Hair: - robe = mobile.FindItemByLayer(Layer.Robe); - - if (robe != null) - { - if (robe.Graphic > 0x3173) - { - if (robe.Graphic == 0x4B9D || robe.Graphic == 0x7816) - { - return true; - } - } - else - { - if (robe.Graphic <= 0x2687) - { - if (robe.Graphic < 0x2683) - { - return robe.Graphic >= 0x204E && robe.Graphic <= 0x204F; - } - - return true; - } - - if (robe.Graphic == 0x2FB9 || robe.Graphic == 0x3173) - { - return true; - } - } - } - - break; - - /*case Layer.Skirt: - skirt = mobile.FindItemByLayer( Layer.Skirt]; - - break;*/ - } - - return false; - } - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/Views/MultiView.cs b/src/ClassicUO.Client/Game/GameObjects/Views/MultiView.cs deleted file mode 100644 index f1afd8d2a..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/Views/MultiView.cs +++ /dev/null @@ -1,175 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.IO; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.GameObjects -{ - public partial class Multi - { - private int _canBeTransparent; - public bool IsHousePreview; - - public override bool TransparentTest(int z) - { - bool r = true; - - if (Z <= z - ItemData.Height) - { - r = false; - } - else if (z < Z && (_canBeTransparent & 0xFF) == 0) - { - r = false; - } - - return r; - } - - public override bool Draw(UltimaBatcher2D batcher, int posX, int posY, float depth) - { - if (!AllowedToDraw || IsDestroyed) - { - return false; - } - - ushort hue = Hue; - - if (State != 0) - { - if ((State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_IGNORE_IN_RENDER) != 0) - { - return false; - } - - if ((State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_INCORRECT_PLACE) != 0) - { - hue = 0x002B; - } - - if ((State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_TRANSPARENT) != 0) - { - AlphaHue = 192; - } - } - - ushort graphic = Graphic; - bool partial = ItemData.IsPartialHue; - - Profile currentProfile = ProfileManager.CurrentProfile; - - if (currentProfile.HighlightGameObjects && SelectedObject.Object == this) - { - hue = Constants.HIGHLIGHT_CURRENT_OBJECT_HUE; - partial = false; - } - else if (currentProfile.NoColorObjectsOutOfRange && Distance > World.ClientViewRange) - { - hue = Constants.OUT_RANGE_COLOR; - partial = false; - } - else if (World.Player.IsDead && currentProfile.EnableBlackWhiteEffect) - { - hue = Constants.DEAD_RANGE_COLOR; - partial = false; - } - - Vector3 hueVec = ShaderHueTranslator.GetHueVector(hue, partial, AlphaHue / 255f); - - if (IsHousePreview) - { - hueVec.Z *= 0.5f; - } - - posX += (int)Offset.X; - posY += (int)(Offset.Y + Offset.Z); - - DrawStaticAnimated(batcher, graphic, posX, posY, hueVec, false, depth); - - if (ItemData.IsLight) - { - Client.Game.GetScene().AddLight(this, this, posX + 22, posY + 22); - } - - return true; - } - - public override bool CheckMouseSelection() - { - if ( - !( - SelectedObject.Object == this - || IsHousePreview - || FoliageIndex != -1 - && Client.Game.GetScene().FoliageIndex == FoliageIndex - ) - ) - { - if (State != 0) - { - if ( - ( - State - & ( - CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_IGNORE_IN_RENDER - | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_PREVIEW - ) - ) != 0 - ) - { - return false; - } - } - - ref UOFileIndex index = ref ArtLoader.Instance.GetValidRefEntry(Graphic + 0x4000); - - Point position = RealScreenPosition; - position.X -= index.Width; - position.Y -= index.Height; - - return Client.Game.Arts.PixelCheck( - Graphic, - SelectedObject.TranslatedMousePositionByViewport.X - position.X, - SelectedObject.TranslatedMousePositionByViewport.Y - position.Y - ); - } - - return false; - } - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/Views/StaticView.cs b/src/ClassicUO.Client/Game/GameObjects/Views/StaticView.cs deleted file mode 100644 index 8563d19e8..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/Views/StaticView.cs +++ /dev/null @@ -1,177 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.Scenes; -using ClassicUO.IO; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using ClassicUO.Game.Managers; - -namespace ClassicUO.Game.GameObjects -{ - internal sealed partial class Static - { - private int _canBeTransparent; - - public override bool TransparentTest(int z) - { - bool r = true; - - if (Z <= z - ItemData.Height) - { - r = false; - } - else if (z < Z && (_canBeTransparent & 0xFF) == 0) - { - r = false; - } - - return r; - } - - public override bool Draw(UltimaBatcher2D batcher, int posX, int posY, float depth) - { - if (!AllowedToDraw || IsDestroyed) - { - return false; - } - - ushort graphic = Graphic; - ushort hue = Hue; - bool partial = ItemData.IsPartialHue; - - if (ProfileManager.CurrentProfile.HighlightGameObjects && SelectedObject.Object == this) - { - hue = Constants.HIGHLIGHT_CURRENT_OBJECT_HUE; - partial = false; - } - else if ( - ProfileManager.CurrentProfile.NoColorObjectsOutOfRange - && Distance > World.ClientViewRange - ) - { - hue = Constants.OUT_RANGE_COLOR; - partial = false; - } - else if (World.Player.IsDead && ProfileManager.CurrentProfile.EnableBlackWhiteEffect) - { - hue = Constants.DEAD_RANGE_COLOR; - partial = false; - } - else - { - if (SelectedObject.Object == this) - { - SpellVisualRangeManager.Instance.LastCursorTileLoc = new Vector2(X, Y); - } - - if (SpellVisualRangeManager.Instance.IsTargetingAfterCasting()) - { - hue = SpellVisualRangeManager.Instance.ProcessHueForTile(hue, this); - } - - if (TileMarkerManager.Instance.IsTileMarked(X, Y, World.Map.Index, out var nhue)) - hue = nhue; - - if (ProfileManager.CurrentProfile.DisplayRadius && Distance == ProfileManager.CurrentProfile.DisplayRadiusDistance && System.Math.Abs(Z - World.Player.Z) < 11) - hue = ProfileManager.CurrentProfile.DisplayRadiusHue; - } - - Vector3 hueVec = ShaderHueTranslator.GetHueVector(hue, partial, AlphaHue / 255f); - - bool isTree = StaticFilters.IsTree(graphic, out _); - - if (isTree && ProfileManager.CurrentProfile.TreeToStumps) - { - graphic = Constants.TREE_REPLACE_GRAPHIC; - } - - DrawStaticAnimated( - batcher, - graphic, - posX, - posY, - hueVec, - ProfileManager.CurrentProfile.ShadowsEnabled - && ProfileManager.CurrentProfile.ShadowsStatics - && (isTree || ItemData.IsFoliage || StaticFilters.IsRock(graphic)), - depth, - ProfileManager.CurrentProfile.AnimatedWaterEffect && ItemData.IsWet - ); - - if (ItemData.IsLight) - { - Client.Game.GetScene().AddLight(this, this, posX + 22, posY + 22); - } - - return true; - } - - public override bool CheckMouseSelection() - { - if ( - !( - SelectedObject.Object == this - || FoliageIndex != -1 - && Client.Game.GetScene().FoliageIndex == FoliageIndex - ) - ) - { - ushort graphic = Graphic; - - bool isTree = StaticFilters.IsTree(graphic, out _); - - if (isTree && ProfileManager.CurrentProfile.TreeToStumps) - { - graphic = Constants.TREE_REPLACE_GRAPHIC; - } - - ref var index = ref ArtLoader.Instance.GetValidRefEntry(graphic + 0x4000); - - Point position = RealScreenPosition; - position.X -= index.Width; - position.Y -= index.Height; - - return Client.Game.Arts.PixelCheck( - graphic, - SelectedObject.TranslatedMousePositionByViewport.X - position.X, - SelectedObject.TranslatedMousePositionByViewport.Y - position.Y - ); - } - - return false; - } - } -} diff --git a/src/ClassicUO.Client/Game/GameObjects/Views/View.cs b/src/ClassicUO.Client/Game/GameObjects/Views/View.cs deleted file mode 100644 index b25c0440f..000000000 --- a/src/ClassicUO.Client/Game/GameObjects/Views/View.cs +++ /dev/null @@ -1,317 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Runtime.CompilerServices; -using ClassicUO.Configuration; -using ClassicUO.IO; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.GameObjects -{ - public enum ObjectHandlesStatus - { - NONE, - OPEN, - CLOSED, - DISPLAYING - } - - public abstract partial class GameObject - { - public byte AlphaHue; - public bool AllowedToDraw = true; - public ObjectHandlesStatus ObjectHandlesStatus; - public Rectangle FrameInfo; - protected bool IsFlipped; - - public abstract bool Draw(UltimaBatcher2D batcher, int posX, int posY, float depth); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public float CalculateDepthZ() - { - int x = X; - int y = Y; - int z = PriorityZ; - - // Offsets are in SCREEN coordinates - if (Offset.X > 0 && Offset.Y < 0) - { - // North - } - else if (Offset.X > 0 && Offset.Y == 0) - { - // Northeast - x++; - } - else if (Offset.X > 0 && Offset.Y > 0) - { - // East - z += Math.Max(0, (int)Offset.Z); - x++; - } - else if (Offset.X == 0 && Offset.Y > 0) - { - // Southeast - x++; - y++; - } - else if (Offset.X < 0 && Offset.Y > 0) - { - // South - z += Math.Max(0, (int)Offset.Z); - y++; - } - else if (Offset.X < 0 && Offset.Y == 0) - { - // Southwest - y++; - } - else if (Offset.X < 0 && Offset.Y > 0) - { - // West - } - else if (Offset.X == 0 && Offset.Y < 0) - { - // Northwest - } - - return (x + y) + (127 + z) * 0.01f; - } - - public Rectangle GetOnScreenRectangle() - { - Rectangle prect = Rectangle.Empty; - - prect.X = (int)(RealScreenPosition.X - FrameInfo.X + 22 + Offset.X); - prect.Y = (int)(RealScreenPosition.Y - FrameInfo.Y + 22 + (Offset.Y - Offset.Z)); - prect.Width = FrameInfo.Width; - prect.Height = FrameInfo.Height; - - return prect; - } - - public virtual bool TransparentTest(int z) - { - return false; - } - - protected static void DrawStatic( - UltimaBatcher2D batcher, - ushort graphic, - int x, - int y, - Vector3 hue, - float depth, - bool isWet = false - ) - { - ref readonly var artInfo = ref Client.Game.Arts.GetArt(graphic); - - if (artInfo.Texture != null) - { - ref var index = ref ArtLoader.Instance.GetValidRefEntry(graphic + 0x4000); - index.Width = (short)((artInfo.UV.Width >> 1) - 22); - index.Height = (short)(artInfo.UV.Height - 44); - - x -= index.Width; - y -= index.Height; - - var pos = new Vector2(x, y); - var scale = Vector2.One; - if (isWet) - { - batcher.Draw( - artInfo.Texture, - pos, - artInfo.UV, - hue, - 0f, - Vector2.Zero, - scale, - SpriteEffects.None, - depth + 0.5f - ); - - var sin = (float)Math.Sin(Time.Ticks / 1000f); - var cos = (float)Math.Cos(Time.Ticks / 1000f); - scale = new Vector2(1.1f + sin * 0.1f, 1.1f + cos * 0.5f * 0.1f); - } - - batcher.Draw( - artInfo.Texture, - pos, - artInfo.UV, - hue, - 0f, - Vector2.Zero, - scale, - SpriteEffects.None, - depth + 0.5f - ); - } - } - - protected static void DrawGump( - UltimaBatcher2D batcher, - ushort graphic, - int x, - int y, - Vector3 hue, - float depth - ) - { - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(graphic); - - if (gumpInfo.Texture != null) - { - batcher.Draw( - gumpInfo.Texture, - new Vector2(x, y), - gumpInfo.UV, - hue, - 0f, - Vector2.Zero, - 1f, - SpriteEffects.None, - depth + 0.5f - ); - } - } - - protected static void DrawStaticRotated( - UltimaBatcher2D batcher, - ushort graphic, - int x, - int y, - float angle, - Vector3 hue, - float depth - ) - { - ref readonly var artInfo = ref Client.Game.Arts.GetArt(graphic); - - if (artInfo.Texture != null) - { - ref var index = ref ArtLoader.Instance.GetValidRefEntry(graphic + 0x4000); - index.Width = (short)((artInfo.UV.Width >> 1) - 22); - index.Height = (short)(artInfo.UV.Height - 44); - - batcher.Draw( - artInfo.Texture, - new Rectangle( - x - index.Width, - y - index.Height, - artInfo.UV.Width, - artInfo.UV.Height - ), - artInfo.UV, - hue, - angle, - Vector2.Zero, - SpriteEffects.None, - depth + 0.5f - ); - } - } - - protected static void DrawStaticAnimated( - UltimaBatcher2D batcher, - ushort graphic, - int x, - int y, - Vector3 hue, - bool shadow, - float depth, - bool isWet = false - ) - { - ref UOFileIndex index = ref ArtLoader.Instance.GetValidRefEntry(graphic + 0x4000); - - graphic = (ushort)(graphic + index.AnimOffset); - - ref readonly var artInfo = ref Client.Game.Arts.GetArt(graphic); - - if (artInfo.Texture != null) - { - index = ref ArtLoader.Instance.GetValidRefEntry(graphic + 0x4000); - index.Width = (short)((artInfo.UV.Width >> 1) - 22); - index.Height = (short)(artInfo.UV.Height - 44); - - x -= index.Width; - y -= index.Height; - - Vector2 pos = new Vector2(x, y); - - if (shadow) - { - batcher.DrawShadow(artInfo.Texture, pos, artInfo.UV, false, depth + 0.25f); - } - - var scale = Vector2.One; - if (isWet) - { - batcher.Draw( - artInfo.Texture, - pos, - artInfo.UV, - hue, - 0f, - Vector2.Zero, - scale, - SpriteEffects.None, - depth + 0.5f - ); - - var sin = (float)Math.Sin(Time.Ticks / 1000f); - var cos = (float)Math.Cos(Time.Ticks / 1000f); - scale = new Vector2(1.1f + sin * 0.1f, 1.1f + cos * 0.5f * 0.1f); - } - - batcher.Draw( - artInfo.Texture, - pos, - artInfo.UV, - hue, - 0f, - Vector2.Zero, - scale, - SpriteEffects.None, - depth + 0.5f - ); - } - } - } -} diff --git a/src/ClassicUO.Client/Game/ItemHold.cs b/src/ClassicUO.Client/Game/ItemHold.cs deleted file mode 100644 index 7609c9ec3..000000000 --- a/src/ClassicUO.Client/Game/ItemHold.cs +++ /dev/null @@ -1,144 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Assets; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game -{ - sealed class ItemHold - { - private bool _enabled; - - public Point MouseOffset; - - public bool IsFixedPosition; - public bool IgnoreFixedPosition; - public int FixedX, FixedY; - - public bool OnGround { get; private set; } - public ushort X { get; private set; } - public ushort Y { get; private set; } - public sbyte Z { get; private set; } - public uint Container { get; private set; } - public uint Serial { get; private set; } - public ushort Graphic { get; private set; } - public ushort DisplayedGraphic { get; private set; } - public bool IsGumpTexture { get; set; } - public ushort Hue { get; private set; } - public ushort Amount { get; private set; } - public ushort TotalAmount { get; private set; } - public bool IsStackable { get; private set; } - public bool IsPartialHue { get; private set; } - public bool IsWearable { get; private set; } - public bool HasAlpha { get; private set; } - public Layer Layer { get; private set; } - public Flags Flags { get; private set; } - - public bool Enabled - { - get => _enabled; - set - { - _enabled = value; - - if (!value) - { - IsFixedPosition = false; - FixedX = 0; - FixedY = 0; - IgnoreFixedPosition = false; - } - } - } - - public bool Dropped { get; set; } - public bool UpdatedInWorld { get; set; } - public ref StaticTiles ItemData => ref TileDataLoader.Instance.StaticData[Graphic]; - - public void Set(Item item, ushort amount, Point? offset = null) - { - Enabled = true; - Serial = item.Serial; - Graphic = item.Graphic; - DisplayedGraphic = item.IsCoin && amount == 1 ? item.Graphic : item.DisplayedGraphic; - X = item.X; - Y = item.Y; - Z = item.Z; - OnGround = item.OnGround; - Container = item.Container; - Hue = item.Hue; - Amount = amount; - TotalAmount = item.Amount; - IsStackable = item.ItemData.IsStackable; - IsPartialHue = item.ItemData.IsPartialHue; - HasAlpha = item.ItemData.IsTranslucent; - IsWearable = item.ItemData.IsWearable; - Layer = item.Layer; - Flags = item.Flags; - MouseOffset = offset ?? Point.Zero; - IsFixedPosition = false; - FixedX = 0; - FixedY = 0; - IgnoreFixedPosition = false; - IsGumpTexture = false; - } - - public void Clear() - { - Serial = 0; - X = 0xFFFF; - Y = 0xFFFF; - Z = 0; - Container = 0; - DisplayedGraphic = Graphic = 0xFFFF; - Hue = 0xFFFF; - OnGround = false; - Amount = 0; - IsWearable = IsStackable = IsPartialHue = HasAlpha = false; - Layer = Layer.Invalid; - Flags = Flags.None; - MouseOffset = Point.Zero; - - Dropped = false; - Enabled = false; - UpdatedInWorld = false; - IsFixedPosition = false; - FixedX = 0; - FixedY = 0; - IgnoreFixedPosition = false; - IsGumpTexture = false; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/LinkedObject.cs b/src/ClassicUO.Client/Game/LinkedObject.cs deleted file mode 100644 index 7e29cba92..000000000 --- a/src/ClassicUO.Client/Game/LinkedObject.cs +++ /dev/null @@ -1,317 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Diagnostics; - -namespace ClassicUO.Game -{ - public abstract class LinkedObject - { - public bool IsEmpty => Items == null; - public LinkedObject Previous, Next, Items; - - //~LinkedObject() - //{ - // Clear(); - - // LinkedObject item = Next; - - // while (item != null && item != this) - // { - // LinkedObject next = item.Next; - // item.Next = null; - // item = next; - // } - //} - - public void PushToBack(LinkedObject item) - { - if (item == null) - { - return; - } - - Remove(item); - - if (Items == null) - { - Items = item; - } - else - { - LinkedObject last = GetLast(); - last.Next = item; - - Debug.Assert(item.Next == null, "[Append to last-next] item must be unlinked before."); - item.Next = null; - item.Previous = last; - } - } - - public void Remove(LinkedObject item) - { - if (item == null) - { - return; - } - - Unlink(item); - item.Next = null; - item.Previous = null; - } - - public void Unlink(LinkedObject item) - { - if (item == null) - { - return; - } - - if (item == Items) - { - Items = Items.Next; - - if (Items != null) - { - Items.Previous = null; - } - } - else - { - if (item.Previous != null) - { - item.Previous.Next = item.Next; - } - - if (item.Next != null) - { - item.Next.Previous = item.Previous; - } - } - } - - public void Insert(LinkedObject first, LinkedObject item) - { - if (first == null) - { - item.Next = Items; - item.Previous = null; - - if (Items != null) - { - Items.Previous = item; - } - - Items = item; - } - else - { - LinkedObject next = first.Next; - item.Next = next; - item.Previous = first; - first.Next = item; - - if (next != null) - { - next.Previous = item; - } - } - } - - public void MoveToFront(LinkedObject item) - { - if (item != null && item != Items) - { - Unlink(item); - - if (Items != null) - { - Items.Previous = item; - } - - item.Next = Items; - item.Previous = null; - Items = item; - } - } - - public void MoveToBack(LinkedObject item) - { - if (item != null) - { - Unlink(item); - LinkedObject last = GetLast(); - - if (last == null) - { - Items = item; - } - else - { - last.Next = item; - } - - item.Previous = last; - item.Next = null; - } - } - - public LinkedObject GetLast() - { - LinkedObject last = Items; - - while (last != null && last.Next != null) - { - last = last.Next; - } - - return last; - } - - public void Clear() - { - if (Items != null) - { - LinkedObject item = Items; - Items = null; - - while (item != null) - { - LinkedObject next = item.Next; - item.Next = null; - item = next; - } - } - } - - /// - /// Sort the contents of this LinkedObject using merge sort. - /// Adapted from Simon Tatham's C implementation: https://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html - /// - /// Type of the objects being compared. - /// Comparison function to use when sorting. - public LinkedObject SortContents(Comparison comparison) where T : LinkedObject - { - if (Items == null) - { - return null; - } - - int unitsize = 1; //size of the components we are merging; 1 for first iteration, multiplied by 2 after each iteration - - T p = null, q = null, e = null, head = (T) Items, tail = null; - - while (true) - { - p = head; - int nmerges = 0; //number of merges done this pass - int psize, qsize; //lengths of the components we are merging - head = null; - tail = null; - - while (p != null) - { - nmerges++; - q = p; - psize = 0; - - for (int i = 0; i < unitsize; i++) - { - psize++; - q = (T) q.Next; - - if (q == null) - { - break; - } - } - - qsize = unitsize; - - while (psize > 0 || qsize > 0 && q != null) - { - if (psize == 0) - { - e = q; - q = (T) q.Next; - qsize--; - } - else if (qsize == 0 || q == null) - { - e = p; - p = (T) p.Next; - psize--; - } - else if (comparison(p, q) <= 0) - { - e = p; - p = (T) p.Next; - psize--; - } - else - { - e = q; - q = (T) q.Next; - qsize--; - } - - if (tail != null) - { - tail.Next = e; - } - else - { - head = e; - } - - e.Previous = tail; - tail = e; - } - - p = q; - } - - tail.Next = null; - - if (nmerges <= 1) - { - Items = head; - - return head; - } - - unitsize *= 2; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/ActiveIconsManager.cs b/src/ClassicUO.Client/Game/Managers/ActiveIconsManager.cs deleted file mode 100644 index fc262d7c0..000000000 --- a/src/ClassicUO.Client/Game/Managers/ActiveIconsManager.cs +++ /dev/null @@ -1,67 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; - -namespace ClassicUO.Game.Managers -{ - public class ActiveSpellIconsManager - { - private readonly HashSet _activeIcons = new HashSet(); - - public void Add(ushort id) - { - if (!IsActive(id)) - { - _activeIcons.Add(id); - } - } - - public void Remove(ushort id) - { - if (IsActive(id)) - { - _activeIcons.Remove(id); - } - } - - public bool IsActive(ushort id) - { - return _activeIcons.Count != 0 && _activeIcons.Contains(id); - } - - public void Clear() - { - _activeIcons.Clear(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/AnchorManager.cs b/src/ClassicUO.Client/Game/Managers/AnchorManager.cs deleted file mode 100644 index e51592de1..000000000 --- a/src/ClassicUO.Client/Game/Managers/AnchorManager.cs +++ /dev/null @@ -1,543 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Xml; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Game.UI.Gumps; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.Managers -{ - public sealed class AnchorManager - { - private static readonly Vector2[][] _anchorTriangles = - { - new[] { new Vector2(0f, 0f), new Vector2(0.5f, 0.5f), new Vector2(0f, 1f) }, - new[] { new Vector2(0f, 0f), new Vector2(0.5f, 0.5f), new Vector2(1f, 0f) }, - new[] { new Vector2(1f, 0f), new Vector2(0.5f, 0.5f), new Vector2(1f, 1f) }, - new[] { new Vector2(0f, 1f), new Vector2(0.5f, 0.5f), new Vector2(1f, 1f) } - }; - - private static readonly Point[] _anchorDirectionMatrix = - { - new Point(-1, 0), - new Point(0, -1), - new Point(1, 0), - new Point(0, 1) - }; - - private static readonly Point[] _anchorMultiplierMatrix = - { - new Point(0, 0), - new Point(0, 0), - new Point(1, 0), - new Point(0, 1) - }; - - private readonly Dictionary reverseMap = new Dictionary(); - - public AnchorGroup this[AnchorableGump control] - { - get - { - reverseMap.TryGetValue(control, out AnchorGroup group); - - return group; - } - - set - { - if (reverseMap.ContainsKey(control) && value == null) - { - reverseMap.Remove(control); - } - else - { - reverseMap.Add(control, value); - } - } - } - - public void Save(XmlTextWriter writer) - { - foreach (AnchorGroup value in reverseMap.Values.Distinct()) - { - value.Save(writer); - } - } - - /*public void AttachControl(AnchorableGump host, AnchorableGump control) - { - if (host.AnchorType == control.AnchorType && this[control] == null) - { - if (this[host] == null) - this[host] = new AnchorGroup(host); - - this[host].AnchorControlAt(control, host, control.Location); - this[control] = this[host]; - } - }*/ - - public void DropControl(AnchorableGump draggedControl, AnchorableGump host) - { - if (host.AnchorType == draggedControl.AnchorType && this[draggedControl] == null) - { - (Point? relativePosition, _) = GetAnchorDirection(draggedControl, host); - - if (relativePosition.HasValue) - { - if (this[host] == null) - { - this[host] = new AnchorGroup(host); - } - - if (this[host].IsEmptyDirection(draggedControl, host, relativePosition.Value)) - { - this[host].AnchorControlAt(draggedControl, host, relativePosition.Value); - - this[draggedControl] = this[host]; - } - } - } - } - - public Point GetCandidateDropLocation(AnchorableGump draggedControl, AnchorableGump host) - { - if (host.AnchorType == draggedControl.AnchorType && this[draggedControl] == null) - { - (Point? relativePosition, AnchorableGump g) = GetAnchorDirection(draggedControl, host); - - if (relativePosition.HasValue) - { - if (this[host] == null || this[host].IsEmptyDirection(draggedControl, host, relativePosition.Value)) - { - Point offset = relativePosition.Value * new Point(g.GroupMatrixWidth, g.GroupMatrixHeight); - - return new Point(host.X + offset.X, host.Y + offset.Y); - } - } - } - - return draggedControl.Location; - } - - public AnchorableGump GetAnchorableControlUnder(AnchorableGump draggedControl) - { - return ClosestOverlappingControl(draggedControl); - } - - public void DetachControl(AnchorableGump control) - { - if (this[control] != null) - { - List group = reverseMap.Where(o => o.Value == this[control]).Select(o => o.Key).ToList(); - - if (group.Count == 2) // if detach 1+1 - need destroy all group - { - foreach (AnchorableGump ctrl in group) - { - this[ctrl].DetachControl(ctrl); - - this[ctrl] = null; - } - } - else - { - this[control].DetachControl(control); - - this[control] = null; - } - } - } - - public void DisposeAllControls(AnchorableGump control) - { - if (this[control] != null) - { - foreach (AnchorableGump ctrl in reverseMap.Where(o => o.Value == this[control]).Select(o => o.Key).ToList()) - { - this[ctrl] = null; - ctrl.Dispose(); - } - } - } - - private (Point?, AnchorableGump) GetAnchorDirection(AnchorableGump draggedControl, AnchorableGump host) - { - int xdistancescale = Math.Abs(draggedControl.X - host.X) * 100 / host.Width; - int ydistancescale = Math.Abs(draggedControl.Y - host.Y) * 100 / host.Height; - - if (xdistancescale > ydistancescale) - { - if (draggedControl.X > host.X) - { - return (new Point(host.WidthMultiplier, 0), host); - } - - return (new Point(-draggedControl.WidthMultiplier, 0), draggedControl); - } - - if (draggedControl.Y > host.Y) - { - return (new Point(0, host.HeightMultiplier), host); - } - - return (new Point(0, -draggedControl.HeightMultiplier), draggedControl); - } - - private bool IsPointInPolygon(Vector2[] polygon, Vector2 point) - { - bool isInside = false; - - for (int i = 0, j = polygon.Length - 1; i < polygon.Length; j = i++) - { - if (polygon[i].Y > point.Y != polygon[j].Y > point.Y && point.X < (polygon[j].X - polygon[i].X) * (point.Y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) + polygon[i].X) - { - isInside = !isInside; - } - } - - return isInside; - } - - public AnchorableGump ClosestOverlappingControl(AnchorableGump control) - { - if (control == null || control.IsDisposed) - { - return null; - } - - AnchorableGump closestControl = null; - int closestDistance = 99999; - - foreach (Gump c in UIManager.Gumps) - { - if (!c.IsDisposed && c is AnchorableGump host && host.AnchorType == control.AnchorType) - { - if (IsOverlapping(control, host)) - { - int dirtyDistance = Math.Abs(control.X - host.X) + Math.Abs(control.Y - host.Y); - - if (dirtyDistance < closestDistance) - { - closestDistance = dirtyDistance; - closestControl = host; - } - } - } - } - - return closestControl; - } - - private bool IsOverlapping(AnchorableGump control, AnchorableGump host) - { - if (control == host) - { - return false; - } - - if (control.Bounds.Top > host.Bounds.Bottom || control.Bounds.Bottom < host.Bounds.Top) - { - return false; - } - - if (control.Bounds.Right < host.Bounds.Left || control.Bounds.Left > host.Bounds.Right) - { - return false; - } - - return true; - } - - private enum AnchorDirection - { - Left, - Top, - Right, - Bottom - } - - public class AnchorGroup - { - private AnchorableGump[,] controlMatrix; - private int updateCount; - - public AnchorGroup(AnchorableGump initial) - { - controlMatrix = new AnchorableGump[initial.WidthMultiplier, initial.HeightMultiplier]; - AddControlToMatrix(0, 0, initial); - } - - public AnchorGroup() - { - controlMatrix = new AnchorableGump[0, 0]; - } - - public void AddControlToMatrix(int xinit, int yInit, AnchorableGump control) - { - for (int x = 0; x < control.WidthMultiplier; x++) - { - for (int y = 0; y < control.HeightMultiplier; y++) - { - controlMatrix[x + xinit, y + yInit] = control; - } - } - } - - public void Save(XmlTextWriter writer) - { - writer.WriteStartElement("anchored_group_gump"); - - writer.WriteAttributeString("matrix_w", controlMatrix.GetLength(0).ToString()); - - writer.WriteAttributeString("matrix_h", controlMatrix.GetLength(1).ToString()); - - for (int y = 0; y < controlMatrix.GetLength(1); y++) - { - for (int x = 0; x < controlMatrix.GetLength(0); x++) - { - AnchorableGump gump = controlMatrix[x, y]; - - if (gump != null) - { - writer.WriteStartElement("gump"); - gump.Save(writer); - writer.WriteAttributeString("matrix_x", x.ToString()); - writer.WriteAttributeString("matrix_y", y.ToString()); - writer.WriteEndElement(); - } - } - } - - writer.WriteEndElement(); - } - - public void MakeTopMost() - { - for (int x = 0; x < controlMatrix.GetLength(0); x++) - { - for (int y = 0; y < controlMatrix.GetLength(1); y++) - { - if (controlMatrix[x, y] != null) - { - UIManager.MakeTopMostGump(controlMatrix[x, y]); - } - } - } - } - - public void DetachControl(AnchorableGump control) - { - for (int x = 0; x < controlMatrix.GetLength(0); x++) - { - for (int y = 0; y < controlMatrix.GetLength(1); y++) - { - if (controlMatrix[x, y] == control) - { - controlMatrix[x, y] = null; - } - } - } - } - - public void UpdateLocation(Control control, int deltaX, int deltaY) - { - if (updateCount == 0) - { - updateCount++; - - HashSet visited = new HashSet(); - - for (int x = 0; x < controlMatrix.GetLength(0); x++) - { - for (int y = 0; y < controlMatrix.GetLength(1); y++) - { - if (controlMatrix[x, y] != null && controlMatrix[x, y] != control) - { - if (!visited.Contains(controlMatrix[x, y])) - { - controlMatrix[x, y].X += deltaX; - - controlMatrix[x, y].Y += deltaY; - - visited.Add(controlMatrix[x, y]); - } - } - } - } - - updateCount--; - } - } - - public void AnchorControlAt(AnchorableGump control, AnchorableGump host, Point relativePosition) - { - Point? hostPosition = GetControlCoordinates(host); - - if (hostPosition.HasValue) - { - int targetX = hostPosition.Value.X + relativePosition.X; - int targetY = hostPosition.Value.Y + relativePosition.Y; - - if (IsEmptyDirection(targetX, targetY)) - { - if (targetX < 0) // Create new column left - { - ResizeMatrix(controlMatrix.GetLength(0) + control.WidthMultiplier, controlMatrix.GetLength(1), control.WidthMultiplier, 0); - } - else if (targetX > controlMatrix.GetLength(0) - control.WidthMultiplier) // Create new column right - { - ResizeMatrix(controlMatrix.GetLength(0) + control.WidthMultiplier, controlMatrix.GetLength(1), 0, 0); - } - - if (targetY < 0) //Create new row top - { - ResizeMatrix(controlMatrix.GetLength(0), controlMatrix.GetLength(1) + control.HeightMultiplier, 0, control.HeightMultiplier); - } - else if (targetY > controlMatrix.GetLength(1) - 1) // Create new row bottom - { - ResizeMatrix(controlMatrix.GetLength(0), controlMatrix.GetLength(1) + control.HeightMultiplier, 0, 0); - } - - - hostPosition = GetControlCoordinates(host); - - if (hostPosition.HasValue) - { - targetX = hostPosition.Value.X + relativePosition.X; - targetY = hostPosition.Value.Y + relativePosition.Y; - - AddControlToMatrix(targetX, targetY, control); - } - } - } - } - - public bool IsEmptyDirection(AnchorableGump draggedControl, AnchorableGump host, Point relativePosition) - { - Point? hostPosition = GetControlCoordinates(host); - - bool isEmpty = true; - - if (hostPosition.HasValue) - { - Point targetInitPosition = hostPosition.Value + relativePosition; - - for (int xOffset = 0; xOffset < draggedControl.WidthMultiplier; xOffset++) - { - for (int yOffset = 0; yOffset < draggedControl.HeightMultiplier; yOffset++) - { - isEmpty &= IsEmptyDirection(targetInitPosition.X + xOffset, targetInitPosition.Y + yOffset); - } - } - - //// TODO: loop through - //var targetX = hostPosition.Value.X + relativePosition.X; - //var targetY = hostPosition.Value.Y + relativePosition.Y; - - //return IsEmptyDirection(targetX, targetY); - } - - return isEmpty; - } - - public bool IsEmptyDirection(int x, int y) - { - if (x < 0 || x > controlMatrix.GetLength(0) - 1 || y < 0 || y > controlMatrix.GetLength(1) - 1) - { - return true; - } - - return controlMatrix[x, y] == null; - } - - private Point? GetControlCoordinates(AnchorableGump control) - { - for (int x = 0; x < controlMatrix.GetLength(0); x++) - { - for (int y = 0; y < controlMatrix.GetLength(1); y++) - { - if (controlMatrix[x, y] == control) - { - return new Point(x, y); - } - } - } - - return null; - } - - public void ResizeMatrix(int xCount, int yCount, int xInitial, int yInitial) - { - AnchorableGump[,] newMatrix = new AnchorableGump[xCount, yCount]; - - for (int x = 0; x < controlMatrix.GetLength(0); x++) - { - for (int y = 0; y < controlMatrix.GetLength(1); y++) - { - newMatrix[x + xInitial, y + yInitial] = controlMatrix[x, y]; - } - } - - controlMatrix = newMatrix; - } - - private void printMatrix() - { - Console.WriteLine(); - Console.WriteLine(); - Console.WriteLine(); - - for (int y = 0; y < controlMatrix.GetLength(1); y++) - { - for (int x = 0; x < controlMatrix.GetLength(0); x++) - { - if (controlMatrix[x, y] != null) - { - Console.Write(" " + controlMatrix[x, y].LocalSerial + " "); - } - else - { - Console.Write(" ---------- "); - } - } - - Console.WriteLine(); - } - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/AnimatedStaticsManager.cs b/src/ClassicUO.Client/Game/Managers/AnimatedStaticsManager.cs deleted file mode 100644 index a4fe674ec..000000000 --- a/src/ClassicUO.Client/Game/Managers/AnimatedStaticsManager.cs +++ /dev/null @@ -1,160 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.IO; -using ClassicUO.Assets; -using ClassicUO.Utility.Collections; - -namespace ClassicUO.Game.Managers -{ - class AnimatedStaticsManager - { - private readonly FastList _staticInfos = new FastList(); - private uint _processTime; - - - public unsafe void Initialize() - { - UOFile file = AnimDataLoader.Instance.AnimDataFile; - - if (file == null) - { - return; - } - - long startAddr = file.StartAddress.ToInt64(); - uint lastaddr = (uint) (startAddr + file.Length - sizeof(AnimDataFrame)); - - for (int i = 0; i < TileDataLoader.Instance.StaticData.Length; i++) - { - if (TileDataLoader.Instance.StaticData[i].IsAnimated) - { - uint addr = (uint) (i * 68 + 4 * (i / 8 + 1)); - uint offset = (uint) (startAddr + addr); - - if (offset <= lastaddr) - { - _staticInfos.Add - ( - new StaticAnimationInfo - { - Index = (ushort) i, - IsField = StaticFilters.IsField((ushort) i) - } - ); - } - } - } - } - - public unsafe void Process() - { - if (_staticInfos == null || _staticInfos.Length == 0 || _processTime >= Time.Ticks) - { - return; - } - - UOFile file = AnimDataLoader.Instance.AnimDataFile; - - if (file == null) - { - return; - } - - // fix static animations time to reflect the standard client - uint delay = Constants.ITEM_EFFECT_ANIMATION_DELAY * 2; - uint next_time = Time.Ticks + 250; - bool no_animated_field = ProfileManager.CurrentProfile != null && ProfileManager.CurrentProfile.FieldsType != 0; - long startAddr = file.StartAddress.ToInt64(); - UOFileIndex[] static_data = ArtLoader.Instance.Entries; - - for (int i = 0; i < _staticInfos.Length; i++) - { - ref StaticAnimationInfo o = ref _staticInfos.Buffer[i]; - - if (no_animated_field && o.IsField) - { - o.AnimIndex = 0; - - continue; - } - - if (o.Time < Time.Ticks) - { - uint addr = (uint) (o.Index * 68 + 4 * (o.Index / 8 + 1)); - AnimDataFrame* info = (AnimDataFrame*) (startAddr + addr); - - byte offset = o.AnimIndex; - - if (info->FrameInterval > 0) - { - o.Time = Time.Ticks + info->FrameInterval * delay + 1; - } - else - { - o.Time = Time.Ticks + delay; - } - - if (offset < info->FrameCount && o.Index + 0x4000 < static_data.Length) - { - static_data[o.Index + 0x4000].AnimOffset = info->FrameData[offset++]; - } - - if (offset >= info->FrameCount) - { - offset = 0; - } - - o.AnimIndex = offset; - } - - if (o.Time < next_time) - { - next_time = o.Time; - } - } - - _processTime = next_time; - } - - - private struct StaticAnimationInfo - { - public uint Time; - public ushort Index; - public byte AnimIndex; - public bool IsField; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/AudioManager.cs b/src/ClassicUO.Client/Game/Managers/AudioManager.cs deleted file mode 100644 index 6e31d1262..000000000 --- a/src/ClassicUO.Client/Game/Managers/AudioManager.cs +++ /dev/null @@ -1,397 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Utility; -using ClassicUO.Configuration; -using ClassicUO.IO.Audio; -using ClassicUO.Assets; -using ClassicUO.Utility.Logging; -using Microsoft.Xna.Framework.Audio; - -namespace ClassicUO.Game.Managers -{ - internal class AudioManager - { - const float SOUND_DELTA = 250; - - private bool _canReproduceAudio = true; - private readonly LinkedList _currentSounds = new LinkedList(); - private readonly UOMusic[] _currentMusic = { null, null }; - private readonly int[] _currentMusicIndices = { 0, 0 }; - public int LoginMusicIndex { get; private set; } - public int DeathMusicIndex { get; } = 42; - - public void Initialize() - { - try - { - new DynamicSoundEffectInstance(0, AudioChannels.Stereo).Dispose(); - } - catch (NoAudioHardwareException ex) - { - Log.Warn(ex.ToString()); - _canReproduceAudio = false; - } - - LoginMusicIndex = Client.Version >= ClientVersion.CV_7000 ? 78 : Client.Version > ClientVersion.CV_308Z ? 0 : 8; - - Client.Game.Activated += OnWindowActivated; - Client.Game.Deactivated += OnWindowDeactivated; - } - - private void OnWindowDeactivated(object sender, EventArgs e) - { - if (!_canReproduceAudio || ProfileManager.CurrentProfile == null || ProfileManager.CurrentProfile.ReproduceSoundsInBackground) - { - return; - } - - SoundEffect.MasterVolume = 0; - } - - private void OnWindowActivated(object sender, EventArgs e) - { - if (!_canReproduceAudio || ProfileManager.CurrentProfile == null || ProfileManager.CurrentProfile.ReproduceSoundsInBackground) - { - return; - } - - SoundEffect.MasterVolume = 1; - } - - public void PlaySound(int index) - { - Profile currentProfile = ProfileManager.CurrentProfile; - - if (!_canReproduceAudio || currentProfile == null) - { - return; - } - - float volume = currentProfile.SoundVolume / SOUND_DELTA; - - if (Client.Game.IsActive) - { - if (!currentProfile.ReproduceSoundsInBackground) - { - volume = currentProfile.SoundVolume / SOUND_DELTA; - } - } - else if (!currentProfile.ReproduceSoundsInBackground) - { - volume = 0; - } - - if (volume < -1 || volume > 1f) - { - return; - } - - if (!currentProfile.EnableSound || !Client.Game.IsActive && !currentProfile.ReproduceSoundsInBackground) - { - volume = 0; - } - - UOSound sound = (UOSound) Client.Game.Sounds.GetSound(index); - - if (sound != null && sound.Play(Time.Ticks, volume)) - { - sound.X = -1; - sound.Y = -1; - sound.CalculateByDistance = false; - - _currentSounds.AddLast(sound); - } - } - - public void PlaySoundWithDistance(int index, int x, int y) - { - if (!_canReproduceAudio || !World.InGame) - { - return; - } - - int distX = Math.Abs(x - World.Player.X); - int distY = Math.Abs(y - World.Player.Y); - int distance = Math.Max(distX, distY); - - Profile currentProfile = ProfileManager.CurrentProfile; - float volume = currentProfile.SoundVolume / SOUND_DELTA; - float distanceFactor = 0.0f; - - if (distance >= 1) - { - float volumeByDist = volume / (World.ClientViewRange + 1); - distanceFactor = volumeByDist * distance; - } - - if (distance > World.ClientViewRange) - { - volume = 0; - } - - if (volume < -1 || volume > 1f) - { - return; - } - - if (currentProfile == null || !currentProfile.EnableSound || !Client.Game.IsActive && !currentProfile.ReproduceSoundsInBackground) - { - volume = 0; - } - - UOSound sound = (UOSound)Client.Game.Sounds.GetSound(index); - - if (sound != null && sound.Play(Time.Ticks, volume, distanceFactor)) - { - sound.X = x; - sound.Y = y; - sound.CalculateByDistance = true; - - _currentSounds.AddLast(sound); - } - } - - public void PlayMusic(int music, bool iswarmode = false, bool is_login = false) - { - if (!_canReproduceAudio) - { - return; - } - - if (music >= Constants.MAX_MUSIC_DATA_INDEX_COUNT) - { - return; - } - - float volume; - - if (is_login) - { - volume = Settings.GlobalSettings.LoginMusic ? Settings.GlobalSettings.LoginMusicVolume / SOUND_DELTA : 0; - } - else - { - Profile currentProfile = ProfileManager.CurrentProfile; - - if (currentProfile == null || !currentProfile.EnableMusic) - { - volume = 0; - } - else - { - volume = currentProfile.MusicVolume / SOUND_DELTA; - } - - if (currentProfile != null && !currentProfile.EnableCombatMusic && iswarmode) - { - return; - } - } - - - if (volume < -1 || volume > 1f) - { - return; - } - - Sound m = Client.Game.Sounds.GetMusic(music); - - if (m == null && _currentMusic[0] != null) - { - StopMusic(); - } - else if (m != null && (m != _currentMusic[0] || iswarmode)) - { - StopMusic(); - - int idx = iswarmode ? 1 : 0; - _currentMusicIndices[idx] = music; - _currentMusic[idx] = (UOMusic) m; - - _currentMusic[idx].Play(Time.Ticks, volume); - } - } - - public void UpdateCurrentMusicVolume(bool isLogin = false) - { - if (!_canReproduceAudio) - { - return; - } - - for (int i = 0; i < 2; i++) - { - if (_currentMusic[i] != null) - { - float volume; - - if (isLogin) - { - volume = Settings.GlobalSettings.LoginMusic ? Settings.GlobalSettings.LoginMusicVolume / SOUND_DELTA : 0; - } - else - { - Profile currentProfile = ProfileManager.CurrentProfile; - - volume = currentProfile == null || !currentProfile.EnableMusic ? 0 : currentProfile.MusicVolume / SOUND_DELTA; - } - - - if (volume < -1 || volume > 1f) - { - return; - } - - _currentMusic[i].Volume = i == 0 && _currentMusic[1] != null ? 0 : volume; - } - } - } - - public void UpdateCurrentSoundsVolume() - { - if (!_canReproduceAudio) - { - return; - } - - Profile currentProfile = ProfileManager.CurrentProfile; - - float volume = currentProfile == null || !currentProfile.EnableSound ? 0 : currentProfile.SoundVolume / SOUND_DELTA; - - if (volume < -1 || volume > 1f) - { - return; - } - - for (LinkedListNode soundNode = _currentSounds.First; soundNode != null; soundNode = soundNode.Next) - { - soundNode.Value.Volume = volume; - } - } - - public void StopMusic() - { - for (int i = 0; i < 2; i++) - { - if (_currentMusic[i] != null) - { - _currentMusic[i].Stop(); - _currentMusic[i].Dispose(); - _currentMusic[i] = null; - } - } - } - - public void StopWarMusic() - { - PlayMusic(_currentMusicIndices[0]); - } - - public void StopSounds() - { - LinkedListNode first = _currentSounds.First; - - while (first != null) - { - LinkedListNode next = first.Next; - - first.Value.Stop(); - - _currentSounds.Remove(first); - - first = next; - } - } - - public void Update() - { - if (!_canReproduceAudio) - { - return; - } - - bool runninWarMusic = _currentMusic[1] != null; - Profile currentProfile = ProfileManager.CurrentProfile; - - for (int i = 0; i < 2; i++) - { - if (_currentMusic[i] != null && currentProfile != null) - { - if (Client.Game.IsActive) - { - if (!currentProfile.ReproduceSoundsInBackground) - { - _currentMusic[i].Volume = i == 0 && runninWarMusic || !currentProfile.EnableMusic ? 0 : currentProfile.MusicVolume / SOUND_DELTA; - } - } - else if (!currentProfile.ReproduceSoundsInBackground && _currentMusic[i].Volume != 0.0f) - { - _currentMusic[i].Volume = 0; - } - } - - _currentMusic[i]?.Update(); - } - - - LinkedListNode first = _currentSounds.First; - - while (first != null) - { - LinkedListNode next = first.Next; - - if (!first.Value.IsPlaying(Time.Ticks)) - { - first.Value.Stop(); - _currentSounds.Remove(first); - } - - first = next; - } - } - - public UOMusic GetCurrentMusic() - { - for (int i = 0; i < 2; i++) - { - if (_currentMusic[i] != null && _currentMusic[i].IsPlaying(Time.Ticks)) - { - return _currentMusic[i]; - } - } - return null; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/AuraManager.cs b/src/ClassicUO.Client/Game/Managers/AuraManager.cs deleted file mode 100644 index 9d78da712..000000000 --- a/src/ClassicUO.Client/Game/Managers/AuraManager.cs +++ /dev/null @@ -1,153 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Configuration; -using ClassicUO.Input; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.Managers -{ - class Aura : IDisposable - { - private static readonly Lazy _blend = new Lazy - ( - () => new BlendState - { - ColorSourceBlend = Blend.SourceAlpha, - ColorDestinationBlend = Blend.InverseSourceAlpha - } - ); - - private readonly Texture2D _texture; - - public Aura(int radius) - { - short w = 0; - short h = 0; - uint[] data = CircleOfTransparency.CreateCircleTexture(radius, ref w, ref h); - - for (int i = 0; i < data.Length; i++) - { - ref uint pixel = ref data[i]; - - if (pixel != 0) - { - ushort value = (ushort)(pixel << 3); - - if (value > 0xFF) - { - value = 0xFF; - } - - pixel = (uint)((value << 24) | (value << 16) | (value << 8) | value); - } - } - - _texture = new Texture2D(Client.Game.GraphicsDevice, w, h); - _texture.SetData(data); - } - - - - public void Draw(UltimaBatcher2D batcher, int x, int y, ushort hue, float depth) - { - x -= (_texture.Width >> 1); - y -= (_texture.Height >> 1); - - Vector3 hueVec = ShaderHueTranslator.GetHueVector(hue, false, 1); - - batcher.SetBlendState(_blend.Value); - batcher.Draw(_texture, new Vector2(x, y), null, hueVec, 0f, Vector2.Zero, 1f, SpriteEffects.None, depth); - batcher.SetBlendState(null); - } - - - public void Dispose() - { - if (_texture != null && !_texture.IsDisposed) - { - _texture.Dispose(); - } - } - } - - internal static class AuraManager - { - private static readonly Aura _aura = new Aura(30); - - private static int _saveAuraUnderFeetType; - - public static bool IsEnabled - { - get - { - if (ProfileManager.CurrentProfile == null) - { - return false; - } - - switch (ProfileManager.CurrentProfile.AuraUnderFeetType) - { - default: - case 0: return false; - - case 1 when World.Player != null && World.Player.InWarMode: return true; - case 2 when Keyboard.Ctrl && Keyboard.Shift: return true; - case 3: return true; - } - } - } - - public static void ToggleVisibility() - { - Profile currentProfile = ProfileManager.CurrentProfile; - - if (!IsEnabled) - { - _saveAuraUnderFeetType = currentProfile.AuraUnderFeetType; - currentProfile.AuraUnderFeetType = 3; - } - else - { - currentProfile.AuraUnderFeetType = _saveAuraUnderFeetType; - } - } - - public static void Draw(UltimaBatcher2D batcher, int x, int y, ushort hue, float depth) - { - _aura.Draw(batcher, x, y, hue, depth); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/AutoLootManager.cs b/src/ClassicUO.Client/Game/Managers/AutoLootManager.cs deleted file mode 100644 index 34755a205..000000000 --- a/src/ClassicUO.Client/Game/Managers/AutoLootManager.cs +++ /dev/null @@ -1,243 +0,0 @@ -using ClassicUO.Configuration; -using ClassicUO.Game.GameObjects; -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text.Json; -using System.Threading.Tasks; - -namespace ClassicUO.Game.Managers -{ - internal class AutoLootManager - { - public static AutoLootManager Instance { get; private set; } = new AutoLootManager(); - public bool IsLoaded { get { return loaded; } } - public List AutoLootList { get => autoLootItems; set => autoLootItems = value; } - - private static ConcurrentQueue lootItems = new ConcurrentQueue(); - - private List autoLootItems = new List(); - private bool loaded = false; - private string savePath = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Profiles", "AutoLoot.json"); - private bool lootTaskRunning = false; - - private AutoLootManager() { Load(); } - - /// - /// This method will, in another thread, start looting the items on the loot list. - /// This is called after adding items via CheckAndLoot method. - /// - public void StartLooting() - { - if (loaded && !lootTaskRunning) - { - int delay = ProfileManager.CurrentProfile == null ? 1000 : ProfileManager.CurrentProfile.MoveMultiObjectDelay; - Task.Factory.StartNew(() => - { - Task.Delay(delay).Wait(); - try - { - lootTaskRunning = true; - if (lootItems != null && !lootItems.IsEmpty) - { - while (lootItems.TryDequeue(out uint moveItem)) - { - Item m = World.Items.Get(moveItem); - if (m != null) - { - GameActions.GrabItem(m, m.Amount); - Task.Delay(delay).Wait(); - } - } - } - lootTaskRunning = false; - } - catch - { - lootTaskRunning = false; - } - }); - } - } - - /// - /// Check an item against the loot list, if it needs to be auto looted it will be. - /// I reccomend running this method in a seperate thread if it's a lot of items. - /// - public void CheckAndLoot(Item i) - { - if (!loaded) return; - - if (IsOnLootList(i)) - { - GameActions.Print($"SAL Looting: {i.Name} {i.Graphic} x {i.Amount}"); - lootItems.Enqueue(i); - } - } - - /// - /// Check if an item is on the auto loot list. - /// - /// The item to check the loot list against - /// - public bool IsOnLootList(Item i) - { - if (!loaded) return false; - - foreach (var entry in autoLootItems) - { - if (entry.Match(i)) - { - return true; - } - } - return false; - } - - public AutoLootItem GetLootItem(string ID) - { - foreach (var item in autoLootItems) - { - if (item.UID == ID) - { - return item; - } - } - - return null; - } - - public AutoLootItem AddLootItem(ushort graphic = 0, ushort hue = ushort.MaxValue, string name = "") - { - foreach(AutoLootItem entry in autoLootItems) - { - if(entry.Graphic == graphic && entry.Hue == hue) - { - return entry; - } - } - - AutoLootItem item = new AutoLootItem() { Graphic = graphic, Hue = hue, Name = name }; - - autoLootItems.Add(item); - - return item; - } - - public void HandleCorpse(Item corpse) - { - if (corpse != null && ProfileManager.CurrentProfile.EnableAutoLoot && corpse.IsCorpse) - { - for (LinkedObject i = corpse.Items; i != null; i = i.Next) - { - CheckAndLoot((Item)i); - } - StartLooting(); - } - } - - public void TryRemoveLootItem(string UID) - { - int removeAt = -1; - - for (int i = 0; i < autoLootItems.Count; i++) - { - if (autoLootItems[i].UID == UID) - { - removeAt = i; - } - } - - if (removeAt > -1) - { - autoLootItems.RemoveAt(removeAt); - } - } - - public void OnSceneLoad() - { - - } - - private void Load() - { - Task.Factory.StartNew(() => - { - if (!File.Exists(savePath)) - { - autoLootItems = new List(); - loaded = true; - } - else - { - try - { - string data = File.ReadAllText(savePath); - AutoLootItem[] tItem = JsonSerializer.Deserialize(data); - autoLootItems = tItem.ToList(); - loaded = true; - } - catch - { - GameActions.Print("There was an error loading your auto loot config file, please check it with a json validator.", 32); - loaded = false; - } - - } - }); - } - - public void Save() - { - if (loaded) - { - try - { - var options = new JsonSerializerOptions() { WriteIndented = true }; - string fileData = JsonSerializer.Serialize(autoLootItems, options); - - File.WriteAllText(savePath, fileData); - } - catch (Exception e) { Console.WriteLine(e.ToString()); } - } - } - - public class AutoLootItem - { - public string Name { get; set; } = ""; - public ushort Graphic { get; set; } = 0; - public ushort Hue { get; set; } = ushort.MaxValue; - /// - /// Do not set this manually. - /// - public string UID { get; set; } = Guid.NewGuid().ToString(); - - public bool Match(Item compareTo) - { - if (Graphic == compareTo.Graphic) //Graphic matches - { - return HueCheck(compareTo.Hue); - } - return false; - } - - private bool HueCheck(ushort value) - { - if (Hue == ushort.MaxValue) //Ignore hue, only check graphic. - { - return true; - } - else if (Hue == value) //Hue must match, and it does - { - return true; - } - else //Hue is not ignored, and does not match - { - return false; - } - } - } - } -} diff --git a/src/ClassicUO.Client/Game/Managers/BoatMovingManager.cs b/src/ClassicUO.Client/Game/Managers/BoatMovingManager.cs deleted file mode 100644 index 9dc1cbeb3..000000000 --- a/src/ClassicUO.Client/Game/Managers/BoatMovingManager.cs +++ /dev/null @@ -1,461 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Network; -using ClassicUO.Utility.Collections; - -namespace ClassicUO.Game.Managers -{ - internal static class BoatMovingManager - { - private const int SLOW_INTERVAL = 1000; - private const int NORMAL_INTERVAL = 500; - private const int FAST_INTERVAL = 250; - - - private static readonly Dictionary> _steps = new Dictionary>(); - private static readonly List _toRemove = new List(); - private static readonly Dictionary> _items = new Dictionary>(); - - private static uint _timePacket; - - - private static int GetVelocity(byte speed) - { - switch (speed) - { - case 0x02: return SLOW_INTERVAL; - - default: - case 0x03: return NORMAL_INTERVAL; - - case 0x04: return FAST_INTERVAL; - - case > 0x04: return speed * 10; - } - } - - public static void MoveRequest(Direction direciton, byte speed) - { - NetClient.Socket.Send_MultiBoatMoveRequest(World.Player, direciton, speed); - _timePacket = Time.Ticks; - } - - - public static void AddStep - ( - uint serial, - byte speed, - Direction movingDir, - Direction facingDir, - ushort x, - ushort y, - sbyte z - ) - { - Item item = World.Items.Get(serial); - - if (item == null || item.IsDestroyed) - { - return; - } - - if (!_steps.TryGetValue(serial, out Deque deque)) - { - deque = new Deque(); - _steps[serial] = deque; - } - - bool empty = deque.Count == 0; - - while (deque.Count > 5) - { - deque.RemoveFromFront(); - } - - //deque.Clear(); - - - //GetEndPosition( - // item, - // deque, - // out ushort currX, - // out ushort currY, - // out sbyte currZ, - // out Direction endDir); - - //if (currX == x && currY == y && currZ == z && endDir == movingDir) - //{ - // return; - //} - - if (empty) - { - item.LastStepTime = Time.Ticks; - } - - //Direction moveDir = DirectionHelper.CalculateDirection(currX, currY, x, y); - - BoatStep step = new BoatStep(); - step.Serial = serial; - step.TimeDiff = _timePacket == 0 || empty ? GetVelocity(speed) : (int) (Time.Ticks - _timePacket); - - step.Speed = speed; - step.X = x; - step.Y = y; - step.Z = z; - step.MovingDir = movingDir; - deque.AddToBack(step); - - ClearEntities(serial); - _timePacket = Time.Ticks; - Console.WriteLine("CURRENT PACKET TIME: {0}", _timePacket); - } - - public static void ClearSteps(uint serial) - { - if (_steps.TryGetValue(serial, out Deque deque) && deque.Count != 0) - { - Item multiItem = World.Items.Get(serial); - - if (multiItem != null) - { - multiItem.Offset.X = 0; - multiItem.Offset.Y = 0; - multiItem.Offset.Z = 0; - } - - if (_items.TryGetValue(serial, out var list)) - { - for (int i = 0; i < list.Length; i++) - { - ref var it = ref list.Buffer[i]; - - Entity ent = World.Get(it.Serial); - - if (ent == null) - { - continue; - } - - ent.Offset.X = 0; - ent.Offset.Y = 0; - ent.Offset.Z = 0; - } - - list.Clear(); - } - - deque.Clear(); - } - } - - public static void ClearEntities(uint serial) - { - _items.Remove(serial); - - //if (_items.TryGetValue(serial, out var list)) - //{ - // list.Clear(); - //} - } - - - public static void PushItemToList(uint serial, uint objSerial, int x, int y, int z) - { - if (!_items.TryGetValue(serial, out var list)) - { - list = new FastList(); - - _items[serial] = list; - } - - for (int i = 0; i < list.Length; i++) - { - ref var item = ref list.Buffer[i]; - - if (!SerialHelper.IsValid(item.Serial)) - { - break; - } - - if (item.Serial == objSerial) - { - item.X = x; - item.Y = y; - item.Z = z; - - return; - } - } - - list.Add - ( - new ItemInside - { - Serial = objSerial, - X = x, - Y = y, - Z = z - } - ); - } - - public static void Update() - { - foreach (Deque deques in _steps.Values) - { - while (deques.Count != 0) - { - ref BoatStep step = ref deques.Front(); - - Item item = World.Items.Get(step.Serial); - - if (item == null || item.IsDestroyed) - { - _toRemove.Add(step.Serial); - - break; - } - - bool drift = step.MovingDir != step.FacingDir; - int maxDelay = step.TimeDiff /*- (int) Client.Game.FrameDelay[1]*/; - - int delay = (int) Time.Ticks - (int) item.LastStepTime; - bool removeStep = delay >= maxDelay; - bool directionChange = false; - - - if ( /*step.FacingDir == step.MovingDir &&*/ - item.X != step.X || item.Y != step.Y) - { - if (maxDelay != 0) - { - float steps = maxDelay / (float) Constants.CHARACTER_ANIMATION_DELAY; - float x = delay / (float) Constants.CHARACTER_ANIMATION_DELAY; - float y = x; - item.Offset.Z = (sbyte) ((step.Z - item.Z) * x * (4.0f / steps)); - MovementSpeed.GetPixelOffset((byte) step.MovingDir, ref x, ref y, steps); - item.Offset.X = (sbyte) x; - item.Offset.Y = (sbyte) y; - } - } - else - { - directionChange = true; - removeStep = true; - } - - //item.BoatDirection = step.MovingDir; - - World.HouseManager.TryGetHouse(item, out House house); - - if (removeStep) - { - item.X = step.X; - item.Y = step.Y; - item.Z = step.Z; - item.UpdateScreenPosition(); - - item.Offset.X = 0; - item.Offset.Y = 0; - item.Offset.Z = 0; - - deques.RemoveFromFront(); - - - if (item.TNext != null || item.TPrevious != null) - { - item.AddToTile(); - } - - house?.Generate(true, true, true); - - UpdateEntitiesInside - ( - item, - removeStep, - step.X, - step.Y, - step.Z, - step.MovingDir - ); - - item.LastStepTime = Time.Ticks; - } - else - { - if (house != null) - { - foreach (Multi c in house.Components) - { - c.Offset = item.Offset; - } - } - - UpdateEntitiesInside - ( - item, - removeStep, - item.X, - item.Y, - item.Z, - step.MovingDir - ); - } - - if (!directionChange) - { - break; - } - } - } - - - if (_toRemove.Count != 0) - { - for (int i = 0; i < _toRemove.Count; i++) - { - _steps.Remove(_toRemove[i]); - _items.Remove(_toRemove[i]); - } - - _toRemove.Clear(); - } - } - - private static void UpdateEntitiesInside - ( - uint serial, - bool removeStep, - int x, - int y, - int z, - Direction direction - ) - { - if (_items.TryGetValue(serial, out var list)) - { - Item item = World.Items.Get(serial); - - for (int i = 0; i < list.Length; i++) - { - ref var it = ref list.Buffer[i]; - - //if (!SerialHelper.IsValid(it.Serial)) - // break; - - Entity entity = World.Get(it.Serial); - - if (entity == null || entity.IsDestroyed) - { - continue; - } - - //entity.BoatDirection = direction; - - if (removeStep) - { - entity.X = (ushort) (x - it.X); - entity.Y = (ushort) (y - it.Y); - entity.Z = (sbyte) (z - it.Z); - entity.UpdateScreenPosition(); - - entity.Offset.X = 0; - entity.Offset.Y = 0; - entity.Offset.Z = 0; - - if (entity.TPrevious != null || entity.TNext != null) - { - entity.AddToTile(); - } - } - else - { - if (item != null) - { - entity.Offset = item.Offset; - } - } - } - } - } - - private static void GetEndPosition - ( - Item item, - Deque deque, - out ushort x, - out ushort y, - out sbyte z, - out Direction dir - ) - { - if (deque.Count == 0) - { - x = item.X; - y = item.Y; - z = item.Z; - dir = item.Direction & Direction.Up; - dir &= Direction.Running; - } - else - { - ref BoatStep s = ref deque.Back(); - x = s.X; - y = s.Y; - z = s.Z; - dir = s.MovingDir; - } - } - - private struct BoatStep - { - public uint Serial; - public int TimeDiff; - public ushort X, Y; - public sbyte Z; - public byte Speed; - public Direction MovingDir, FacingDir; - } - - private struct ItemInside - { - public uint Serial; - public int X, Y, Z; - } - } -} diff --git a/src/ClassicUO.Client/Game/Managers/ChatChannel.cs b/src/ClassicUO.Client/Game/Managers/ChatChannel.cs deleted file mode 100644 index 2987b7ae2..000000000 --- a/src/ClassicUO.Client/Game/Managers/ChatChannel.cs +++ /dev/null @@ -1,47 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Managers -{ - internal sealed class ChatChannel - { - public ChatChannel(string name, bool hasPassword) - { - Name = name; - HasPassword = hasPassword; - } - - public readonly bool HasPassword; - - public readonly string Name; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/ChatManager.cs b/src/ClassicUO.Client/Game/Managers/ChatManager.cs deleted file mode 100644 index c2c3056e7..000000000 --- a/src/ClassicUO.Client/Game/Managers/ChatManager.cs +++ /dev/null @@ -1,128 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Resources; - -namespace ClassicUO.Game.Managers -{ - internal static class ChatManager - { - public static readonly Dictionary Channels = new Dictionary(); - public static ChatStatus ChatIsEnabled; - public static string CurrentChannelName = string.Empty; - - private static readonly string[] _messages = - { - ResGeneral.YouAreAlreadyIgnoringMaximum, - ResGeneral.YouAreAlreadyIgnoring1, - ResGeneral.YouAreNowIgnoring1, - ResGeneral.YouAreNoLongerIgnoring1, - ResGeneral.YouAreNotIgnoring1, - ResGeneral.YouAreNoLongerIgnoringAnyone, - ResGeneral.ThatIsNotAValidConferenceName, - ResGeneral.ThereIsAlreadyAConference, - ResGeneral.YouMustHaveOperatorStatus, - ResGeneral.Conference1RenamedTo2, - ResGeneral.YouMustBeInAConference, - ResGeneral.ThereIsNoPlayerNamed1, - ResGeneral.ThereIsNoConferenceNamed1, - ResGeneral.ThatIsNotTheCorrectPassword, - ResGeneral.HasChosenToIgnoreYou, - ResGeneral.NotGivenYouSpeakingPrivileges, - ResGeneral.YouCanNowReceivePM, - ResGeneral.YouWillNoLongerReceivePM, - ResGeneral.YouAreShowingYourCharName, - ResGeneral.YouAreNotShowingYourCharName, - ResGeneral.IsRemainingAnonymous, - ResGeneral.HasChosenToNotReceivePM, - ResGeneral.IsKnownInTheLandsOfBritanniaAs2, - ResGeneral.HasBeenKickedOutOfTheConference, - ResGeneral.AConferenceModeratorKickedYou, - ResGeneral.YouAreAlreadyInTheConference1, - ResGeneral.IsNoLongerAConferenceModerator, - ResGeneral.IsNowAConferenceModerator, - ResGeneral.HasRemovedYouFromModerators, - ResGeneral.HasMadeYouAConferenceModerator, - ResGeneral.NoLongerHasSpeakingPrivileges, - ResGeneral.NowHasSpeakingPrivileges, - ResGeneral.RemovedYourSpeakingPrivileges, - ResGeneral.GrantedYouSpeakingPrivileges, - ResGeneral.EveryoneWillHaveSpeakingPrivs, - ResGeneral.ModeratorsWillHaveSpeakingPrivs, - ResGeneral.PasswordToTheConferenceChanged, - ResGeneral.TheConferenceNamed1IsFull, - ResGeneral.YouAreBanning1FromThisConference, - ResGeneral.BannedYouFromTheConference, - ResGeneral.YouHaveBeenBanned - }; - - - public static string GetMessage(int index) - { - return index < _messages.Length ? _messages[index] : string.Empty; - } - - public static void AddChannel(string text, bool hasPassword) - { - if (!Channels.TryGetValue(text, out ChatChannel channel)) - { - channel = new ChatChannel(text, hasPassword); - Channels[text] = channel; - } - } - - public static void RemoveChannel(string name) - { - if (Channels.ContainsKey(name)) - { - Channels.Remove(name); - } - } - - public static void Clear() - { - Channels.Clear(); - } - - //static ChatManager() - //{ - // using (StreamReader reader = new StreamReader(File.OpenRead(UOFileManager.GetUOFilePath("Chat.enu")))) - // { - // while (!reader.EndOfStream) - // { - // string line = reader.ReadLine(); - // } - // } - //} - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/ChatStatus.cs b/src/ClassicUO.Client/Game/Managers/ChatStatus.cs deleted file mode 100644 index 22a79c99d..000000000 --- a/src/ClassicUO.Client/Game/Managers/ChatStatus.cs +++ /dev/null @@ -1,41 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Managers -{ - internal enum ChatStatus : byte - { - Disabled, - Enabled, - EnabledUserRequest - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/CommandManager.cs b/src/ClassicUO.Client/Game/Managers/CommandManager.cs deleted file mode 100644 index 02ca9b41c..000000000 --- a/src/ClassicUO.Client/Game/Managers/CommandManager.cs +++ /dev/null @@ -1,318 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Resources; -using ClassicUO.Utility.Logging; -using System; -using System.Collections.Generic; - -namespace ClassicUO.Game.Managers -{ - public static class CommandManager - { - private static readonly Dictionary> _commands = new Dictionary>(); - - public static void Initialize() - { - Register - ( - "info", - s => - { - if (TargetManager.IsTargeting) - { - TargetManager.CancelTarget(); - } - - TargetManager.SetTargeting(CursorTarget.SetTargetClientSide, CursorType.Target, TargetType.Neutral); - } - ); - - Register - ( - "datetime", - s => - { - if (World.Player != null) - { - GameActions.Print(string.Format(ResGeneral.CurrentDateTimeNowIs0, DateTime.Now)); - } - } - ); - - Register - ( - "hue", - s => - { - if (TargetManager.IsTargeting) - { - TargetManager.CancelTarget(); - } - - TargetManager.SetTargeting(CursorTarget.HueCommandTarget, CursorType.Target, TargetType.Neutral); - } - ); - - - Register - ( - "debug", - s => - { - CUOEnviroment.Debug = !CUOEnviroment.Debug; - - } - ); - - Register - ( - "colorpicker", - s => - { - UIManager.Add(new UI.Gumps.ModernColorPicker(null, 8787)); - - } - ); - - Register("cast", s => - { - string spell = ""; - for (int i = 1; i < s.Length; i++) - { - spell += s[i] + " "; - } - spell = spell.Trim(); - - if (SpellDefinition.TryGetSpellFromName(spell, out var spellDef)) - GameActions.CastSpell(spellDef.ID); - }); - - List sortSkills = new List(World.Player.Skills); - - Register("skill", s => - { - string skill = ""; - for (int i = 1; i < s.Length; i++) - { - skill += s[i] + " "; - } - skill = skill.Trim().ToLower(); - - if (skill.Length > 0) - { - for (int i = 0; i < World.Player.Skills.Length; i++) - { - if (World.Player.Skills[i].Name.ToLower().Contains(skill)) - { - GameActions.UseSkill(World.Player.Skills[i].Index); - break; - } - } - } - }); - - Register("version", s => { UIManager.Add(new VersionHistory()); }); - Register("rain", s => { Client.Game.GetScene()?.Weather.Generate(WeatherType.WT_RAIN, 30, 75); }); - - Register("marktile", s => - { - if (s.Length > 1 && s[1] == "-r") - { - if (s.Length == 2) - { - TileMarkerManager.Instance.RemoveTile(World.Player.X, World.Player.Y, World.Map.Index); - } - else if (s.Length == 4) - { - if (int.TryParse(s[2], out var x)) - if (int.TryParse(s[3], out var y)) - TileMarkerManager.Instance.RemoveTile(x, y, World.Map.Index); - } - else if (s.Length == 5) - { - if (int.TryParse(s[2], out var x)) - if (int.TryParse(s[3], out var y)) - if (int.TryParse(s[4], out var m)) - TileMarkerManager.Instance.RemoveTile(x, y, m); - } - } - else - { - if (s.Length == 1) - { - TileMarkerManager.Instance.AddTile(World.Player.X, World.Player.Y, World.Map.Index, 32); - } - else if (s.Length == 2) - { - if (ushort.TryParse(s[1], out ushort h)) - TileMarkerManager.Instance.AddTile(World.Player.X, World.Player.Y, World.Map.Index, h); - } - else if (s.Length == 4) - { - if (int.TryParse(s[1], out var x)) - if (int.TryParse(s[2], out var y)) - if (ushort.TryParse(s[3], out var h)) - TileMarkerManager.Instance.AddTile(x, y, World.Map.Index, h); - } - else if (s.Length == 5) - { - if (int.TryParse(s[1], out var x)) - if (int.TryParse(s[2], out var y)) - if (int.TryParse(s[3], out var m)) - if (ushort.TryParse(s[4], out var h)) - TileMarkerManager.Instance.AddTile(x, y, m, h); - } - } - }); - - Register("radius", s => - { - ///-radius distance hue - if (s.Length == 1) - ProfileManager.CurrentProfile.DisplayRadius ^= true; - if (s.Length > 1) - { - if (int.TryParse(s[1], out var dist)) - ProfileManager.CurrentProfile.DisplayRadiusDistance = dist; - ProfileManager.CurrentProfile.DisplayRadius = true; - } - if (s.Length > 2) - if (ushort.TryParse(s[2], out var h)) - ProfileManager.CurrentProfile.DisplayRadiusHue = h; - }); - - Register("options", (s) => - { - UIManager.Add(new OptionsGump()); - }); - - Register("paperdoll", (s) => - { - if (ProfileManager.CurrentProfile.UseModernPaperdoll) - { - UIManager.Add(new PaperDollGump(World.Player, true)); - } - else - { - UIManager.Add(new ModernPaperdoll(World.Player)); - } - - }); - - Register("optlink", (s) => - { - ModernOptionsGump g = UIManager.GetGump(); - if (s.Length > 1) - { - if (g != null) - { - g.GoToPage(s[1]); - } - else - { - UIManager.Add(g = new ModernOptionsGump()); - g.GoToPage(s[1]); - } - } - else - { - if (g != null) - { - GameActions.Print(g.GetPageString()); - } - } - }); - } - - - public static void Register(string name, Action callback) - { - name = name.ToLower(); - - if (!_commands.ContainsKey(name)) - { - _commands.Add(name, callback); - } - else - { - Log.Error($"Attempted to register command: '{name}' twice."); - } - } - - public static void UnRegister(string name) - { - name = name.ToLower(); - - if (_commands.ContainsKey(name)) - { - _commands.Remove(name); - } - } - - public static void UnRegisterAll() - { - _commands.Clear(); - } - - public static void Execute(string name, params string[] args) - { - name = name.ToLower(); - - if (_commands.TryGetValue(name, out Action action)) - { - action.Invoke(args); - } - else - { - GameActions.Print(string.Format(Language.Instance.ErrorsLanguage.CommandNotFound, name)); - Log.Warn($"Command: '{name}' not exists"); - } - } - - public static void OnHueTarget(Entity entity) - { - if (entity != null) - { - TargetManager.Target(entity); - } - - Mouse.LastLeftButtonClickTime = 0; - GameActions.Print(string.Format(ResGeneral.ItemID0Hue1, entity.Graphic, entity.Hue)); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/ContainerManager.cs b/src/ClassicUO.Client/Game/Managers/ContainerManager.cs deleted file mode 100644 index c689ad639..000000000 --- a/src/ClassicUO.Client/Game/Managers/ContainerManager.cs +++ /dev/null @@ -1,543 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using System.IO; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.Managers -{ - internal static class ContainerManager - { - private static readonly Dictionary _data = - new Dictionary(); - - static ContainerManager() - { - BuildContainerFile(false); - } - - public static int DefaultX { get; } = 40; - public static int DefaultY { get; } = 40; - - public static int X { get; private set; } = 40; - public static int Y { get; private set; } = 40; - - public static ContainerData Get(ushort graphic) - { - //if the server requests for a non present gump in container data dictionary, create it, but without any particular sound. - if (!_data.TryGetValue(graphic, out ContainerData value)) - { - _data[graphic] = value = new ContainerData(graphic, 0, 0, 44, 65, 186, 159); - } - - return value; - } - - public static void CalculateContainerPosition(uint serial, ushort g) - { - if (UIManager.GetGumpCachePosition(serial, out Point location)) - { - X = location.X; - Y = location.Y; - } - else - { - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(g); - - if (gumpInfo.Texture != null) - { - float scale = UIManager.ContainerScale; - - int width = (int)(gumpInfo.UV.Width * scale); - int height = (int)(gumpInfo.UV.Height * scale); - - if (ProfileManager.CurrentProfile.OverrideContainerLocation) - { - switch (ProfileManager.CurrentProfile.OverrideContainerLocationSetting) - { - case 0: - SetPositionNearGameObject(g, serial, width, height); - - break; - - case 1: - X = Client.Game.Window.ClientBounds.Width - width; - Y = 0; - - break; - - case 2: - case 3: - X = - ProfileManager - .CurrentProfile - .OverrideContainerLocationPosition - .X - (width >> 1); - Y = - ProfileManager - .CurrentProfile - .OverrideContainerLocationPosition - .Y - (height >> 1); - - break; - } - - if (X + width > Client.Game.Window.ClientBounds.Width) - { - X -= width; - } - - if (Y + height > Client.Game.Window.ClientBounds.Height) - { - Y -= height; - } - } - else - { - int passed = 0; - - for (int i = 0; i < 4 && passed == 0; i++) - { - if ( - X + width + Constants.CONTAINER_RECT_STEP - > Client.Game.Window.ClientBounds.Width - ) - { - X = Constants.CONTAINER_RECT_DEFAULT_POSITION; - - if ( - Y + height + Constants.CONTAINER_RECT_LINESTEP - > Client.Game.Window.ClientBounds.Height - ) - { - Y = Constants.CONTAINER_RECT_DEFAULT_POSITION; - } - else - { - Y += Constants.CONTAINER_RECT_LINESTEP; - } - } - else if ( - Y + height + Constants.CONTAINER_RECT_STEP - > Client.Game.Window.ClientBounds.Height - ) - { - if ( - X + width + Constants.CONTAINER_RECT_LINESTEP - > Client.Game.Window.ClientBounds.Width - ) - { - X = Constants.CONTAINER_RECT_DEFAULT_POSITION; - } - else - { - X += Constants.CONTAINER_RECT_LINESTEP; - } - - Y = Constants.CONTAINER_RECT_DEFAULT_POSITION; - } - else - { - passed = i + 1; - } - } - - if (passed == 0) - { - X = DefaultX; - Y = DefaultY; - } - else if (passed == 1) - { - X += Constants.CONTAINER_RECT_STEP; - Y += Constants.CONTAINER_RECT_STEP; - } - } - } - } - } - - private static void SetPositionNearGameObject(ushort g, uint serial, int width, int height) - { - Item item = World.Items.Get(serial); - - if (item == null) - { - return; - } - - Item bank = World.Player.FindItemByLayer(Layer.Bank); - var camera = Client.Game.Scene.Camera; - - if (bank != null && serial == bank) - { - // open bank near player - X = World.Player.RealScreenPosition.X + camera.Bounds.X + 40; - Y = World.Player.RealScreenPosition.Y + camera.Bounds.Y - (height >> 1); - } - else if (item.OnGround) - { - // item is in world - X = item.RealScreenPosition.X + camera.Bounds.X + 40; - Y = item.RealScreenPosition.Y + camera.Bounds.Y - (height >> 1); - } - else if (SerialHelper.IsMobile(item.Container)) - { - // pack animal, snooped player, npc vendor - Mobile mobile = World.Mobiles.Get(item.Container); - - if (mobile != null) - { - X = mobile.RealScreenPosition.X + camera.Bounds.X + 40; - Y = mobile.RealScreenPosition.Y + camera.Bounds.Y - (height >> 1); - } - } - else - { - // in a container, open near the container - ContainerGump parentContainer = UIManager.GetGump(item.Container); - - if (parentContainer != null) - { - X = parentContainer.X + (width >> 1); - Y = parentContainer.Y; - } - } - } - - public static void BuildContainerFile(bool force) - { - string path = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Client"); - - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - path = Path.Combine(path, "containers.txt"); - - if (!File.Exists(path) || force) - { - MakeDefault(); - - using (StreamWriter writer = new StreamWriter(File.Create(path))) - { - writer.WriteLine("# FORMAT"); - - writer.WriteLine( - "# GRAPHIC OPEN_SOUND_ID CLOSE_SOUND_ID LEFT TOP RIGHT BOTTOM ICONIZED_GRAPHIC [0 if not exists] MINIMIZER_AREA_X [0 if not exists] MINIMIZER_AREA_Y [0 if not exists]" - ); - - writer.WriteLine( - "# LEFT = X, TOP = Y, RIGHT = X + WIDTH, BOTTOM = Y + HEIGHT" - ); - writer.WriteLine(); - writer.WriteLine(); - - foreach (KeyValuePair e in _data) - { - writer.WriteLine( - $"{e.Value.Graphic} {e.Value.OpenSound} {e.Value.ClosedSound} {e.Value.Bounds.X} {e.Value.Bounds.Y} {e.Value.Bounds.Width} {e.Value.Bounds.Height} {e.Value.IconizedGraphic} {e.Value.MinimizerArea.X} {e.Value.MinimizerArea.Y}" - ); - } - } - } - - _data.Clear(); - - TextFileParser containersParser = new TextFileParser( - File.ReadAllText(path), - new[] { ' ', '\t', ',' }, - new[] { '#', ';' }, - new[] { '"', '"' } - ); - - while (!containersParser.IsEOF()) - { - List ss = containersParser.ReadTokens(); - - if (ss != null && ss.Count != 0) - { - if ( - ushort.TryParse(ss[0], out ushort graphic) - && ushort.TryParse(ss[1], out ushort open_sound_id) - && ushort.TryParse(ss[2], out ushort close_sound_id) - && int.TryParse(ss[3], out int x) - && int.TryParse(ss[4], out int y) - && int.TryParse(ss[5], out int w) - && int.TryParse(ss[6], out int h) - ) - { - ushort iconized_graphic = 0; - int minimizer_x = 0, - minimizer_y = 0; - - if (ss.Count >= 8 && ushort.TryParse(ss[7], out iconized_graphic)) - { - if (ss.Count >= 9 && int.TryParse(ss[8], out minimizer_x)) - { - if (ss.Count >= 10 && int.TryParse(ss[9], out minimizer_y)) - { - // nice! - } - } - } - - _data[graphic] = new ContainerData( - graphic, - open_sound_id, - close_sound_id, - x, - y, - w, - h, - iconized_graphic, - minimizer_x, - minimizer_y - ); - } - } - } - } - - private static void MakeDefault() - { - _data.Clear(); - - _data[0x0007] = new ContainerData(0x0007, 0x0000, 0x0000, 30, 30, 270, 170); - - _data[0x0009] = new ContainerData(0x0009, 0x0000, 0x0000, 20, 85, 124, 196); - - _data[0x003C] = new ContainerData( - 0x003C, - 0x0048, - 0x0058, - 44, - 65, - 186, - 159, - 0x0050, - 105, - 162 - ); - - _data[0x003D] = new ContainerData(0x003D, 0x0048, 0x0058, 29, 34, 137, 128); - - _data[0x003E] = new ContainerData(0x003E, 0x002F, 0x002E, 33, 36, 142, 148); - - _data[0x003F] = new ContainerData(0x003F, 0x004F, 0x0058, 19, 47, 182, 123); - - _data[0x0040] = new ContainerData(0x0040, 0x002D, 0x002C, 16, 38, 152, 125); - - _data[0x0041] = new ContainerData(0x0041, 0x004F, 0x0058, 40, 30, 139, 123); - - _data[0x0042] = new ContainerData(0x0042, 0x002D, 0x002C, 18, 105, 162, 178); - - _data[0x0043] = new ContainerData(0x0043, 0x002D, 0x002C, 16, 51, 184, 124); - - _data[0x0044] = new ContainerData(0x0044, 0x002D, 0x002C, 20, 10, 170, 100); - - _data[0x0047] = new ContainerData(0x0047, 0x0000, 0x0000, 16, 10, 148, 138); - - _data[0x0048] = new ContainerData(0x0048, 0x002F, 0x002E, 16, 10, 154, 94); - - _data[0x0049] = new ContainerData(0x0049, 0x002D, 0x002C, 18, 105, 162, 178); - - _data[0x004A] = new ContainerData(0x004A, 0x002D, 0x002C, 18, 105, 162, 178); - - _data[0x004B] = new ContainerData(0x004B, 0x002D, 0x002C, 16, 51, 184, 124); - - _data[0x004C] = new ContainerData(0x004C, 0x002D, 0x002C, 46, 74, 196, 184); - - _data[0x004D] = new ContainerData(0x004D, 0x002F, 0x002E, 76, 12, 140, 68); - - _data[0x004E] = new ContainerData(0x004E, 0x002D, 0x002C, 24, 18, 100, 152); - - _data[0x004F] = new ContainerData(0x004F, 0x002D, 0x002C, 24, 18, 100, 152); - - _data[0x0051] = new ContainerData(0x0051, 0x002F, 0x002E, 16, 10, 154, 94); - - _data[0x0052] = new ContainerData(0x0052, 0x0000, 0x0000, 0, 0, 110, 62); - - _data[0x0102] = new ContainerData(0x0102, 0x004F, 0x0058, 35, 10, 190, 95); - - _data[0x0103] = new ContainerData(0x0103, 0x0048, 0x0058, 41, 21, 173, 104); - - _data[0x0104] = new ContainerData(0x0104, 0x002F, 0x002E, 10, 10, 160, 105); - - _data[0x0105] = new ContainerData(0x0105, 0x002F, 0x002E, 10, 10, 160, 105); - - _data[0x0106] = new ContainerData(0x0106, 0x002F, 0x002E, 10, 10, 160, 105); - - _data[0x0107] = new ContainerData(0x0107, 0x002F, 0x002E, 10, 10, 160, 105); - - _data[0x0108] = new ContainerData(0x0108, 0x004F, 0x0058, 10, 10, 160, 105); - - _data[0x0109] = new ContainerData(0x0109, 0x002D, 0x002C, 10, 10, 160, 105); - - _data[0x010A] = new ContainerData(0x010A, 0x002D, 0x002C, 10, 10, 160, 105); - - _data[0x010B] = new ContainerData(0x010B, 0x002D, 0x002C, 10, 10, 160, 105); - - _data[0x010C] = new ContainerData(0x010C, 0x002F, 0x002E, 10, 10, 160, 105); - - _data[0x010D] = new ContainerData(0x010D, 0x002F, 0x002E, 10, 10, 160, 105); - - _data[0x010E] = new ContainerData(0x010E, 0x002F, 0x002E, 10, 10, 160, 105); - - _data[0x0116] = new ContainerData(0x0116, 0x0000, 0x0000, 40, 25, 140, 110); - - _data[0x011A] = new ContainerData(0x011A, 0x0000, 0x0000, 10, 65, 125, 160); - - _data[0x011B] = new ContainerData(0x011B, 0x0000, 0x0000, 45, 10, 175, 95); - - _data[0x011C] = new ContainerData(0x011C, 0x0000, 0x0000, 37, 10, 175, 105); - - _data[0x011D] = new ContainerData(0x011D, 0x0000, 0x0000, 43, 10, 165, 110); - - _data[0x011E] = new ContainerData(0x011E, 0x0000, 0x0000, 30, 22, 263, 106); - - _data[0x011F] = new ContainerData(0x011F, 0x0000, 0x0000, 45, 10, 175, 95); - - _data[0x0120] = new ContainerData(0x0120, 0x0000, 0x0000, 56, 30, 160, 107); - - _data[0x0121] = new ContainerData(0x0121, 0x0000, 0x0000, 77, 32, 162, 107); - - _data[0x0123] = new ContainerData(0x0123, 0x0000, 0x0000, 36, 19, 111, 157); - - _data[0x0484] = new ContainerData(0x0484, 0x0000, 0x0000, 0, 45, 175, 125); - - _data[0x058E] = new ContainerData(0x058E, 0x0000, 0x0000, 50, 150, 348, 250); - - _data[0x06D3] = new ContainerData(0x06D3, 0x0000, 0x0000, 10, 65, 125, 160); - - _data[0x06D4] = new ContainerData(0x06D4, 0x0000, 0x0000, 10, 65, 125, 160); - - _data[0x06D5] = new ContainerData(0x06D5, 0x0000, 0x0000, 10, 65, 125, 160); - - _data[0x06D6] = new ContainerData(0x06D6, 0x0000, 0x0000, 10, 65, 125, 160); - - _data[0x06E5] = new ContainerData(0x06E5, 0x0000, 0x0000, 66, 74, 306, 520); - - _data[0x06E6] = new ContainerData(0x06E6, 0x0000, 0x0000, 66, 74, 306, 520); - - _data[0x06E7] = new ContainerData(0x06E7, 0x0000, 0x0000, 50, 60, 548, 308); - - _data[0x06E8] = new ContainerData(0x06E8, 0x0000, 0x0000, 50, 60, 548, 308); - - _data[0x06E9] = new ContainerData(0x06E9, 0x0000, 0x0000, 60, 80, 318, 324); - - _data[0x06EA] = new ContainerData(0x06EA, 0x0000, 0x0000, 50, 60, 548, 308); - - _data[0x091A] = new ContainerData(0x091A, 0x0000, 0x0000, 0, 0, 282, 230); - - _data[0x092E] = new ContainerData(0x092E, 0x0000, 0x0000, 0, 0, 282, 210); - - _data[0x266A] = new ContainerData(0x266A, 0x0000, 0x0000, 16, 51, 184, 124); - - _data[0x266B] = new ContainerData(0x266B, 0x0000, 0x0000, 16, 51, 184, 124); - - _data[0x2A63] = new ContainerData(0x2A63, 0x0187, 0x01C9, 60, 33, 460, 348); - - _data[0x4D0C] = new ContainerData(0x4D0C, 0x0000, 0x0000, 25, 65, 220, 155); - - _data[0x775E] = new ContainerData( - 0x775E, - 0x0048, - 0x0058, - 44, - 65, - 186, - 159, - 0x775F, - 105, - 178 - ); - - _data[0x7760] = new ContainerData( - 0x7760, - 0x0048, - 0x0058, - 44, - 65, - 186, - 159, - 0x7761, - 105, - 178 - ); - - _data[0x7762] = new ContainerData( - 0x7762, - 0x0048, - 0x0058, - 44, - 65, - 186, - 159, - 0x7763, - 105, - 178 - ); - - _data[0x777A] = new ContainerData(0x777A, 0x0000, 0x0000, 32, 40, 184, 116); - - _data[0x9CD9] = new ContainerData(0x9CD9, 0x0000, 0x0000, 10, 10, 160, 105); - - _data[0x9CDB] = new ContainerData(0x9CDB, 0x0000, 0x0000, 50, 60, 548, 308); - - _data[0x9CDD] = new ContainerData(0x9CDD, 0x0000, 0x0000, 50, 60, 548, 308); - - _data[0x9CDF] = new ContainerData(0x9CDF, 0x0000, 0x0000, 50, 60, 548, 308); - - _data[0x9CE3] = new ContainerData(0x9CE3, 0x0000, 0x0000, 50, 60, 548, 308); - - _data[0x9CE4] = new ContainerData(0x9CE4, 0x0000, 0x0000, 44, 65, 186, 159); - - _data[0x9CE5] = new ContainerData(0x9CE5, 0x0000, 0x0000, 44, 65, 186, 159); - - _data[0x9CE7] = new ContainerData(0x9CE7, 0x0000, 0x0000, 44, 65, 186, 159); - - // - // 0x2A63= new ContainerData(0x2A63, 0x0187, 0x01c9, 29, 34, 137, 128)//for this particular gump area is bugged also in original client, as it is similar to the bag, probably this is an unfinished one - //} - } - } -} diff --git a/src/ClassicUO.Client/Game/Managers/CoolDownBarManager.cs b/src/ClassicUO.Client/Game/Managers/CoolDownBarManager.cs deleted file mode 100644 index 95f22f702..000000000 --- a/src/ClassicUO.Client/Game/Managers/CoolDownBarManager.cs +++ /dev/null @@ -1,78 +0,0 @@ -using ClassicUO.Configuration; -using ClassicUO.Game.UI.Gumps; -using System; -using System.Threading.Tasks; - -namespace ClassicUO.Game.Managers -{ - public class CoolDownBarManager - { - private const int MAX_COOLDOWN_BARS = 15; - private static CoolDownBar[] coolDownBars = new CoolDownBar[MAX_COOLDOWN_BARS]; - - public CoolDownBarManager() - { - EventSink.MessageReceived += MessageManager_MessageReceived; - } - - private void MessageManager_MessageReceived(object sender, MessageEventArgs e) - { - Task.Factory.StartNew(() => - { - int count = ProfileManager.CurrentProfile.CoolDownConditionCount; - for (int i = 0; i < count; i++) - { - switch (ProfileManager.CurrentProfile.Condition_Type[i]) - { - default: - case 0: - break; - case 1: //self - if (e.Parent != null && e.Parent.Serial != World.Player.Serial) - return; - break; - case 2: - if (e.Parent != null && e.Parent.Serial == World.Player.Serial) - return; - break; - - } - if (e.Text.Contains(ProfileManager.CurrentProfile.Condition_Trigger[i])) - { - AddCoolDownBar( - TimeSpan.FromSeconds(ProfileManager.CurrentProfile.Condition_Duration[i]), - ProfileManager.CurrentProfile.Condition_Label[i], - ProfileManager.CurrentProfile.Condition_Hue[i], - ProfileManager.CurrentProfile.Condition_ReplaceIfExists.Count > i ? ProfileManager.CurrentProfile.Condition_ReplaceIfExists[i] : false - ); - } - } - }); - - } - - public static void AddCoolDownBar(TimeSpan _duration, string _name, ushort _hue, bool replace) - { - if (replace) - for (int i = 0; i < coolDownBars.Length; i++) - { - if (coolDownBars[i] != null && !coolDownBars[i].IsDisposed && coolDownBars[i].textLabel.Text == _name) - { - coolDownBars[i].Dispose(); - coolDownBars[i] = new CoolDownBar(_duration, _name, _hue, CoolDownBar.DEFAULT_X, CoolDownBar.DEFAULT_Y + (i * (CoolDownBar.COOL_DOWN_HEIGHT + 5))); - UIManager.Add(coolDownBars[i]); - return; - } - } - for (int i = 0; i < coolDownBars.Length; i++) - { - if (coolDownBars[i] == null || coolDownBars[i].IsDisposed) - { - coolDownBars[i] = new CoolDownBar(_duration, _name, _hue, CoolDownBar.DEFAULT_X, CoolDownBar.DEFAULT_Y + (i * (CoolDownBar.COOL_DOWN_HEIGHT + 5))); - UIManager.Add(coolDownBars[i]); - return; - } - } - } - } -} diff --git a/src/ClassicUO.Client/Game/Managers/CorpseManager.cs b/src/ClassicUO.Client/Game/Managers/CorpseManager.cs deleted file mode 100644 index a96b61e59..000000000 --- a/src/ClassicUO.Client/Game/Managers/CorpseManager.cs +++ /dev/null @@ -1,135 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Utility.Collections; - -namespace ClassicUO.Game.Managers -{ - public class CorpseManager - { - private readonly Deque _corpses = new Deque(); - - public void Add(uint corpse, uint obj, Direction dir, bool run) - { - for (int i = 0; i < _corpses.Count; i++) - { - ref CorpseInfo c = ref _corpses.GetAt(i); - - if (c.CorpseSerial == corpse) - { - return; - } - } - - _corpses.AddToBack(new CorpseInfo(corpse, obj, dir, run)); - } - - public void Remove(uint corpse, uint obj) - { - for (int i = 0; i < _corpses.Count;) - { - ref CorpseInfo c = ref _corpses.GetAt(i); - - if (c.CorpseSerial == corpse || c.ObjectSerial == obj) - { - if (corpse != 0) - { - Item item = World.Items.Get(corpse); - - if (item != null) - { - item.Layer = (Layer) ((c.Direction & Direction.Mask) | (c.IsRunning ? Direction.Running : 0)); - } - } - - _corpses.RemoveAt(i); - } - else - { - i++; - } - } - } - - public bool Exists(uint corpse, uint obj) - { - for (int i = 0; i < _corpses.Count; i++) - { - ref CorpseInfo c = ref _corpses.GetAt(i); - - if (c.CorpseSerial == corpse || c.ObjectSerial == obj) - { - return true; - } - } - - return false; - } - - public Item GetCorpseObject(uint serial) - { - for (int i = 0; i < _corpses.Count; i++) - { - ref CorpseInfo c = ref _corpses.GetAt(i); - - if (c.ObjectSerial == serial) - { - return World.Items.Get(c.CorpseSerial); - } - } - - return null; - } - - public void Clear() - { - _corpses.Clear(); - } - } - - public struct CorpseInfo - { - public CorpseInfo(uint corpseSerial, uint objectSerial, Direction direction, bool isRunning) - { - CorpseSerial = corpseSerial; - ObjectSerial = objectSerial; - Direction = direction; - IsRunning = isRunning; - } - - public uint CorpseSerial, ObjectSerial; - public Direction Direction; - public bool IsRunning; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/CrashReportWebhook.cs b/src/ClassicUO.Client/Game/Managers/CrashReportWebhook.cs deleted file mode 100644 index 1a04050cd..000000000 --- a/src/ClassicUO.Client/Game/Managers/CrashReportWebhook.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Collections.Specialized; -using System.Net.Http; - -namespace ClassicUO.Game.Managers -{ - public class CrashReportWebhook - { - private static NameValueCollection discordValues = new NameValueCollection(); - public string WebHook { get; set; } = ""; - public string UserName { get; set; } = ""; - public string ProfilePicture { get; set; } = "https://static.giantbomb.com/uploads/original/4/42381/1196379-gas_mask_respirator.jpg"; - - public CrashReportWebhook() - { - } - - public CrashReportWebhook SendMessage(string msgSend) - { - if (String.IsNullOrEmpty(WebHook)) - return null; - - using (HttpClient httpClient = new HttpClient()) - { - MultipartFormDataContent form = new MultipartFormDataContent(); - var file_bytes = System.Text.Encoding.Unicode.GetBytes(msgSend); - form.Add(new ByteArrayContent(file_bytes, 0, file_bytes.Length), "Document", "log.txt"); - httpClient.PostAsync(WebHook, form).Wait(); - httpClient.Dispose(); - } - - return this; - } - - public static string Obf(string source, Int16 shift) - { - var maxChar = Convert.ToInt32(char.MaxValue); - var minChar = Convert.ToInt32(char.MinValue); - - var buffer = source.ToCharArray(); - - for (var i = 0; i < buffer.Length; i++) - { - var shifted = Convert.ToInt32(buffer[i]) + shift; - - if (shifted > maxChar) - { - shifted -= maxChar; - } - else if (shifted < minChar) - { - shifted += maxChar; - } - - buffer[i] = Convert.ToChar(shifted); - } - - return new string(buffer); - } - } -} diff --git a/src/ClassicUO.Client/Game/Managers/DelayedObjectClickManager.cs b/src/ClassicUO.Client/Game/Managers/DelayedObjectClickManager.cs deleted file mode 100644 index d5458caca..000000000 --- a/src/ClassicUO.Client/Game/Managers/DelayedObjectClickManager.cs +++ /dev/null @@ -1,106 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.GameObjects; -using ClassicUO.Input; - -namespace ClassicUO.Game.Managers -{ - internal static class DelayedObjectClickManager - { - public static uint Serial { get; private set; } - public static bool IsEnabled { get; private set; } - public static uint Timer { get; private set; } - public static int X { get; set; } - public static int Y { get; set; } - public static int LastMouseX { get; set; } - public static int LastMouseY { get; set; } - - - public static void Update() - { - if (!IsEnabled || Timer > Time.Ticks) - { - return; - } - - Entity entity = World.Get(Serial); - - if (entity != null) - { - if (!World.ClientFeatures.TooltipsEnabled || SerialHelper.IsItem(Serial) && ((Item) entity).IsLocked && ((Item) entity).ItemData.Weight == 255 && !((Item) entity).ItemData.IsContainer) - { - GameActions.SingleClick(Serial); - } - - if (World.ClientFeatures.PopupEnabled) - { - GameActions.OpenPopupMenu(Serial); - } - } - - Clear(); - } - - public static void Set(uint serial, int x, int y, uint timer) - { - Serial = serial; - LastMouseX = Mouse.Position.X; - LastMouseY = Mouse.Position.Y; - X = x; - Y = y; - Timer = timer; - IsEnabled = true; - } - - public static void Clear() - { - IsEnabled = false; - Serial = 0xFFFF_FFFF; - Timer = 0; - } - - public static void Clear(uint serial) - { - if (Serial == serial) - { - Timer = 0; - Serial = 0; - IsEnabled = false; - X = 0; - Y = 0; - LastMouseX = 0; - LastMouseY = 0; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/DurabilityManager.cs b/src/ClassicUO.Client/Game/Managers/DurabilityManager.cs deleted file mode 100644 index 35305596b..000000000 --- a/src/ClassicUO.Client/Game/Managers/DurabilityManager.cs +++ /dev/null @@ -1,132 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Concurrent; -using ClassicUO.Game.Data; -using ClassicUO.Game.UI.Gumps; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using System; - -namespace ClassicUO.Game.Managers -{ - public class DurabilityManager : IDisposable - { - private readonly ConcurrentDictionary _itemLayerSlots = new ConcurrentDictionary(); - - private static readonly Layer[] _equipLayers = - { - Layer.Cloak, Layer.Shirt, Layer.Pants, Layer.Shoes, Layer.Legs, Layer.Arms, Layer.Torso, Layer.Tunic, - Layer.Ring, Layer.Bracelet, Layer.Gloves, Layer.Skirt, Layer.Robe, Layer.Waist, Layer.Necklace, - Layer.Beard, Layer.Earrings, Layer.Helmet, Layer.OneHanded, Layer.TwoHanded, Layer.Talisman - }; - - public List Durabilities => _itemLayerSlots.Values.ToList(); - - public DurabilityManager() - { - EventSink.OPLOnReceive += OnOPLReceive; - } - - public bool TryGetDurability(uint serial, out DurabiltyProp durability) - { - return _itemLayerSlots.TryGetValue(serial, out durability); - } - - private void OnOPLReceive(object s, OPLEventArgs e) - { - Task.Factory.StartNew(() => - { - var isItem = SerialHelper.IsValid(e.Serial) && SerialHelper.IsItem(e.Serial); - if (isItem) - { - if (World.Items.TryGetValue(e.Serial, out var item)) - { - if (!item.IsDestroyed) - { - if (item.Container == World.Player.Serial && _equipLayers.Contains(item.Layer)) - { - var durability = ParseDurability((int)item.Serial, e.Data); - _itemLayerSlots.AddOrUpdate(item.Serial, durability, (_, _) => durability); - } - else - { - _itemLayerSlots.TryRemove(item.Serial, out DurabiltyProp _); - } - - UIManager.GetGump()?.RequestUpdateContents(); - UIManager.GetGump()?.RequestUpdateContents(); - } - } - } - }); - } - - private static DurabiltyProp ParseDurability(int serial, string data) - { - MatchCollection matches = Regex.Matches(data, @"(?<=Durability )(\d*) / (\d*)"); //This should match 45 / 255 for example - if (matches.Count == 0) - { - return new DurabiltyProp(); - } - - string[] parts = data.Substring(matches[0].Index, matches[0].Length).Split('/'); - - return int.TryParse(parts[0].Trim(), out int min) && int.TryParse(parts[1].Trim(), out int max) ? - new DurabiltyProp(serial, min, max) : new DurabiltyProp(); - } - - public void Dispose() - { - EventSink.OPLOnReceive -= OnOPLReceive; - } - } - - public class DurabiltyProp - { - public int Serial { get; set; } - public int Durabilty { get; set; } - public int MaxDurabilty { get; set; } - - public float Percentage => MaxDurabilty > 0 ? ((float)Durabilty / (float)MaxDurabilty) : 0; - - public DurabiltyProp(int serial, int current, int max) - { - Serial = serial; - Durabilty = current; - MaxDurabilty = max; - } - public DurabiltyProp() : this(0, 0, 0) { } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/EffectManager.cs b/src/ClassicUO.Client/Game/Managers/EffectManager.cs deleted file mode 100644 index 6929bebea..000000000 --- a/src/ClassicUO.Client/Game/Managers/EffectManager.cs +++ /dev/null @@ -1,261 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Utility.Logging; - -namespace ClassicUO.Game.Managers -{ - internal class EffectManager : LinkedObject - { - public void Update() - { - for (GameEffect f = (GameEffect) Items; f != null;) - { - GameEffect next = (GameEffect) f.Next; - - f.Update(); - - if (!f.IsDestroyed && f.Distance > World.ClientViewRange) - { - f.Destroy(); - } - - f = next; - } - } - - - public void CreateEffect - ( - GraphicEffectType type, - uint source, - uint target, - ushort graphic, - ushort hue, - ushort srcX, - ushort srcY, - sbyte srcZ, - ushort targetX, - ushort targetY, - sbyte targetZ, - byte speed, - int duration, - bool fixedDir, - bool doesExplode, - bool hasparticles, - GraphicEffectBlendMode blendmode - ) - { - if (hasparticles) - { - Log.Warn("Unhandled particles in an effects packet."); - } - - GameEffect effect; - - if (hue != 0) - { - hue++; - } - - duration *= Constants.ITEM_EFFECT_ANIMATION_DELAY; - - switch (type) - { - case GraphicEffectType.Moving: - if (graphic <= 0) - { - return; - } - - // TODO: speed == 0 means run at standard frameInterval got from anim.mul? - if (speed == 0) - { - speed++; - } - - effect = new MovingEffect - ( - this, - source, - target, - srcX, - srcY, - srcZ, - targetX, - targetY, - targetZ, - graphic, - hue, - fixedDir, - duration, - speed - ) - { - Blend = blendmode, - CanCreateExplosionEffect = doesExplode - }; - - break; - - case GraphicEffectType.DragEffect: - - if (graphic <= 0) - { - return; - } - - if (speed == 0) - { - speed++; - } - - effect = new DragEffect - ( - this, - source, - target, - srcX, - srcY, - srcZ, - targetX, - targetY, - targetZ, - graphic, - hue, - duration, - speed - ) - { - Blend = blendmode, - CanCreateExplosionEffect = doesExplode - }; - - break; - - case GraphicEffectType.Lightning: - effect = new LightningEffect - ( - this, - source, - srcX, - srcY, - srcZ, - hue - ); - - break; - - case GraphicEffectType.FixedXYZ: - - if (graphic <= 0) - { - return; - } - - effect = new FixedEffect - ( - this, - srcX, - srcY, - srcZ, - graphic, - hue, - duration, - 0 //speed [use 50ms] - ) - { - Blend = blendmode - }; - - break; - - case GraphicEffectType.FixedFrom: - - if (graphic <= 0) - { - return; - } - - effect = new FixedEffect - ( - this, - source, - srcX, - srcY, - srcZ, - graphic, - hue, - duration, - 0 //speed [use 50ms] - ) - { - Blend = blendmode - }; - - break; - - case GraphicEffectType.ScreenFade: - Log.Warn("Unhandled 'Screen Fade' effect."); - - return; - - default: - Log.Warn("Unhandled effect."); - - return; - } - - - PushToBack(effect); - } - - public new void Clear() - { - GameEffect first = (GameEffect) Items; - - while (first != null) - { - LinkedObject n = first.Next; - - first.Destroy(); - - first = (GameEffect) n; - } - - Items = null; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/EventSink.cs b/src/ClassicUO.Client/Game/Managers/EventSink.cs deleted file mode 100644 index 2bcada2a5..000000000 --- a/src/ClassicUO.Client/Game/Managers/EventSink.cs +++ /dev/null @@ -1,196 +0,0 @@ -using ClassicUO.Game.Data; -using Microsoft.Xna.Framework; -using System; - -namespace ClassicUO.Game.Managers -{ - public class EventSink - { - /// - /// Invoked when the player is connected to a server - /// - public static event EventHandler OnConnected; - public static void InvokeOnConnected(object sender) => OnConnected?.Invoke(sender, EventArgs.Empty); - - /// - /// Invoked when the player is connected to a server - /// - public static event EventHandler OnDisconnected; - public static void InvokeOnDisconnected(object sender) => OnDisconnected?.Invoke(sender, EventArgs.Empty); - - /// - /// Invoked when any message is received from the server after client processing - /// - public static event EventHandler MessageReceived; - public static void InvokeMessageReceived(object sender, MessageEventArgs e) => MessageReceived?.Invoke(sender, e); - - /// - /// Invoked when any message is received from the server *before* client processing - /// - public static event EventHandler RawMessageReceived; - public static void InvokeRawMessageReceived(object sender, MessageEventArgs e) => RawMessageReceived?.Invoke(sender, e); - - /// - /// Not currently used. May be removed later or put into use, not sure right now - /// - public static event EventHandler ClilocMessageReceived; - public static void InvokeClilocMessageReceived(object sender, MessageEventArgs e) => ClilocMessageReceived?.Invoke(sender, e); - - /// - /// Invoked anytime a message is added to the journal - /// - public static event EventHandler JournalEntryAdded; - public static void InvokeJournalEntryAdded(object sender, JournalEntry e) => JournalEntryAdded?.Invoke(sender, e); - - /// - /// Invoked anytime we receive object property list data (Tooltip text for items) - /// - public static event EventHandler OPLOnReceive; - public static void InvokeOPLOnReceive(object sender, OPLEventArgs e) => OPLOnReceive?.Invoke(sender, e); - - /// - /// Invoked when a buff is "added" to a player - /// - public static event EventHandler OnBuffAdded; - public static void InvokeOnBuffAdded(object sender, BuffEventArgs e) => OnBuffAdded?.Invoke(sender, e); - - /// - /// Invoked when a buff is "removed" to a player (Called before removal) - /// - public static event EventHandler OnBuffRemoved; - public static void InvokeOnBuffRemoved(object sender, BuffEventArgs e) => OnBuffRemoved?.Invoke(sender, e); - - /// - /// Invoked when the players position is changed - /// - public static event EventHandler OnPositionChanged; - public static void InvokeOnPositionChanged(object sender, PositionChangedArgs e) => OnPositionChanged?.Invoke(sender, e); - - /// - /// Invoked when any entity in game receives damage, not neccesarily the player. - /// - public static event EventHandler OnEntityDamage; - public static void InvokeOnEntityDamage(object sender, int e) => OnEntityDamage?.Invoke(sender, e); - - /// - /// Invoked when a container is opened. Sender is the Item, serial is the item serial. - /// - public static event EventHandler OnOpenContainer; - public static void InvokeOnOpenContainer(object sender, uint serial) => OnOpenContainer?.Invoke(sender, serial); - - /// - /// Invoked when the player receives a death packet from the server - /// - public static event EventHandler OnPlayerDeath; - public static void InvokeOnPlayerDeath(object sender, uint serial) => OnPlayerDeath?.Invoke(sender, serial); - - /// - /// Invoked when the player or server tells the client to path find - /// Vector is X, Y, Z and Distance - /// - public static event EventHandler OnPathFinding; - public static void InvokeOnPathFinding(object sender, Vector4 e) => OnPathFinding?.Invoke(sender, e); - - /// - /// Invoked when the server asks the client to generate some weather - /// - public static event EventHandler OnSetWeather; - public static void InvokeOnSetWeather(object sender, WeatherEventArgs e) => OnSetWeather?.Invoke(sender, e); - - /// - /// Invoked when a stat of the player is changed(min or max). Currently only Hits is set up. - /// - public static event EventHandler OnPlayerStatChange; - public static void InvokeOnPlayerStatChange(object sender, PlayerStatChangedArgs e) => OnPlayerStatChange?.Invoke(sender, e); - - /// - /// This occurs *before* any TazUO tooltip processing occurs allowing you to modify it before processing happens - /// - public static PreProcessTooltipDelegate PreProcessTooltip; - public delegate void PreProcessTooltipDelegate(ref ItemPropertiesData e); - - /// - /// This event occurs *after* TazUO tooltip processing, this is the final string before being rendered into a tooltip window - /// - public static PostProcessTooltipDelegate PostProcessTooltip; - public delegate void PostProcessTooltipDelegate(ref string e); - - /// - /// This event occurs every game update, essentially the game tick. Be careful with this, it happens many many times per second. - /// - public static GameUpdateDelegate GameUpdate; - public delegate void GameUpdateDelegate(); - } - - public class OPLEventArgs : EventArgs - { - public readonly uint Serial; - public readonly string Name; - public readonly string Data; - - public OPLEventArgs(uint serial, string name, string data) - { - Serial = serial; - Name = name; - Data = data; - } - } - - public class BuffEventArgs : EventArgs - { - public BuffEventArgs(BuffIcon buff) - { - Buff = buff; - } - - public BuffIcon Buff { get; } - } - - public class PositionChangedArgs : EventArgs - { - public PositionChangedArgs(Vector3 newlocation) - { - Newlocation = newlocation; - } - - public Vector3 Newlocation { get; } - } - - public class WeatherEventArgs : EventArgs - { - public WeatherEventArgs(WeatherType type, byte count, byte temp) - { - Type = type; - Count = count; - Temp = temp; - } - - public WeatherType Type { get; } - public byte Count { get; } - public byte Temp { get; } - } - - public class PlayerStatChangedArgs : EventArgs - { - public PlayerStatChangedArgs(PlayerStat stat, int oldValue, int newValue) - { - Stat = stat; - OldValue = oldValue; - NewValue = newValue; - } - - public PlayerStat Stat { get; } - public int OldValue { get; } - public int NewValue { get; } - - public enum PlayerStat - { - Hits, - HitsMax, - Mana, - ManaMax, - Stamina, - StaminaMax - } - } -} diff --git a/src/ClassicUO.Client/Game/Managers/HealthLinesManager.cs b/src/ClassicUO.Client/Game/Managers/HealthLinesManager.cs deleted file mode 100644 index 916954cd3..000000000 --- a/src/ClassicUO.Client/Game/Managers/HealthLinesManager.cs +++ /dev/null @@ -1,333 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using FontStashSharp; - -namespace ClassicUO.Game.Managers -{ - internal class HealthLinesManager - { - private const int BAR_WIDTH = 34; //28; - private const int BAR_HEIGHT = 8; - private const int BAR_WIDTH_HALF = BAR_WIDTH >> 1; - private const int BAR_HEIGHT_HALF = BAR_HEIGHT >> 1; - - const ushort BACKGROUND_GRAPHIC = 0x1068; - const ushort HP_GRAPHIC = 0x1069; - - public bool IsEnabled => - ProfileManager.CurrentProfile != null && ProfileManager.CurrentProfile.ShowMobilesHP; - - public void Draw(UltimaBatcher2D batcher) - { - var camera = Client.Game.Scene.Camera; - - if (SerialHelper.IsMobile(TargetManager.LastTargetInfo.Serial)) - { - DrawHealthLineWithMath( - batcher, - TargetManager.LastTargetInfo.Serial, - camera.Bounds.Width, - camera.Bounds.Height - ); - } - - if (SerialHelper.IsMobile(TargetManager.SelectedTarget)) - { - DrawHealthLineWithMath( - batcher, - TargetManager.SelectedTarget, - camera.Bounds.Width, - camera.Bounds.Height - ); - } - - if (SerialHelper.IsMobile(TargetManager.LastAttack)) - { - DrawHealthLineWithMath( - batcher, - TargetManager.LastAttack, - camera.Bounds.Width, - camera.Bounds.Height - ); - } - - if (!IsEnabled) - { - return; - } - - int mode = ProfileManager.CurrentProfile.MobileHPType; - - if (mode < 0) - { - return; - } - - int showWhen = ProfileManager.CurrentProfile.MobileHPShowWhen; - - foreach (Mobile mobile in World.Mobiles.Values) - { - if (mobile.IsDestroyed) - { - continue; - } - - int current = mobile.Hits; - int max = mobile.HitsMax; - - if (max == 0) - { - continue; - } - - if (showWhen == 1 && current == max) - { - continue; - } - - Point p = mobile.RealScreenPosition; - p.X += (int)mobile.Offset.X + 22 + 5; - p.Y += (int)(mobile.Offset.Y - mobile.Offset.Z) + 22 + 5; - - if (mode != 1 && !mobile.IsDead) - { - if (showWhen == 2 && current != max || showWhen <= 1) - { - if (mobile.HitsPercentage != 0) - { - Client.Game.Animations.GetAnimationDimensions( - mobile.AnimIndex, - mobile.GetGraphicForAnimation(), - /*(byte) m.GetDirectionForAnimation()*/ - 0, - /*Mobile.GetGroupForAnimation(m, isParent:true)*/ - 0, - mobile.IsMounted, - /*(byte) m.AnimIndex*/ - 0, - out int centerX, - out int centerY, - out int width, - out int height - ); - - Point p1 = p; - p1.Y -= height + centerY + 8 + 22; - - if (mobile.IsGargoyle && mobile.IsFlying) - { - p1.Y -= 22; - } - else if (!mobile.IsMounted) - { - p1.Y += 22; - } - - p1 = Client.Game.Scene.Camera.WorldToScreen(p1); - p1.X -= (mobile.HitsTexture.Width >> 1) + 5; - p1.Y -= mobile.HitsTexture.Height; - - if (mobile.ObjectHandlesStatus == ObjectHandlesStatus.DISPLAYING) - { - p1.Y -= Constants.OBJECT_HANDLES_GUMP_HEIGHT + 5; - } - - if ( - !( - p1.X < 0 - || p1.X > camera.Bounds.Width - mobile.HitsTexture.Width - || p1.Y < 0 - || p1.Y > camera.Bounds.Height - ) - ) - { - mobile.HitsTexture.Draw(batcher, p1.X, p1.Y); - } - } - } - } - - if ( - mobile.Serial == TargetManager.LastTargetInfo.Serial - || mobile.Serial == TargetManager.SelectedTarget - || mobile.Serial == TargetManager.LastAttack - ) - { - continue; - } - - p.X -= 5; - p = Client.Game.Scene.Camera.WorldToScreen(p); - p.X -= BAR_WIDTH_HALF; - p.Y -= BAR_HEIGHT_HALF; - - if (p.X < 0 || p.X > camera.Bounds.Width - BAR_WIDTH) - { - continue; - } - - if (p.Y < 0 || p.Y > camera.Bounds.Height - BAR_HEIGHT) - { - continue; - } - - if (mode >= 1) - { - DrawHealthLine(batcher, mobile, p.X, p.Y, mobile.Serial != World.Player.Serial); - } - } - } - - private void DrawHealthLineWithMath( - UltimaBatcher2D batcher, - uint serial, - int screenW, - int screenH - ) - { - Entity entity = World.Get(serial); - - if (entity == null) - { - return; - } - - Point p = entity.RealScreenPosition; - p.X += (int)entity.Offset.X + 22; - p.Y += (int)(entity.Offset.Y - entity.Offset.Z) + 22 + 5; - - p = Client.Game.Scene.Camera.WorldToScreen(p); - p.X -= BAR_WIDTH_HALF; - p.Y -= BAR_HEIGHT_HALF; - - if (p.X < 0 || p.X > screenW - BAR_WIDTH) - { - return; - } - - if (p.Y < 0 || p.Y > screenH - BAR_HEIGHT) - { - return; - } - - DrawHealthLine(batcher, entity, p.X, p.Y, false); - } - - private void DrawHealthLine( - UltimaBatcher2D batcher, - Entity entity, - int x, - int y, - bool passive - ) - { - if (entity == null) - { - return; - } - - int multiplier = 1; - if (ProfileManager.CurrentProfile != null) - multiplier = ProfileManager.CurrentProfile.HealthLineSizeMultiplier; - - int per = (BAR_WIDTH * multiplier) * entity.HitsPercentage / 100; - int offset = 2; - - if (per >> 2 == 0) - { - offset = per; - } - - Mobile mobile = entity as Mobile; - - float alpha = passive ? 0.5f : 1.0f; - ushort hue = - mobile != null - ? Notoriety.GetHue(mobile.NotorietyFlag) - : Notoriety.GetHue(NotorietyFlag.Gray); - - Vector3 hueVec = ShaderHueTranslator.GetHueVector(hue, false, alpha); - - if (mobile == null) - { - y += 22; - } - - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(BACKGROUND_GRAPHIC); - Rectangle bounds = gumpInfo.UV; - - if (multiplier > 1) - x -= (int)(((BAR_WIDTH * multiplier) / 2) - (BAR_WIDTH / 2)); - - batcher.Draw( - gumpInfo.Texture, - new Rectangle(x, y, gumpInfo.UV.Width * multiplier, gumpInfo.UV.Height * multiplier), - gumpInfo.UV, - hueVec - ); - - hueVec.X = 90; - - if (mobile != null) - { - if (mobile.IsPoisoned) - { - hueVec.X = 63; - } - else if (mobile.IsYellowHits) - { - hueVec.X = 53; - } - } - - float hitPerecentage = (float)entity.Hits / (float)entity.HitsMax; - - if (entity.HitsMax == 0) - hitPerecentage = 1; - - batcher.Draw( - SolidColorTextureCache.GetTexture(Color.White), - new Vector2(x + (3 * multiplier), y + (4 * multiplier)), - new Rectangle(0, 0, (int)(((BAR_WIDTH * multiplier) - (6 * multiplier)) * hitPerecentage), (bounds.Height * multiplier) - (6 * multiplier)), - hueVec - ); - } - } -} diff --git a/src/ClassicUO.Client/Game/Managers/HotkeysManager.cs b/src/ClassicUO.Client/Game/Managers/HotkeysManager.cs deleted file mode 100644 index 2a8a738b8..000000000 --- a/src/ClassicUO.Client/Game/Managers/HotkeysManager.cs +++ /dev/null @@ -1,693 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using SDL2; - -namespace ClassicUO.Game.Managers -{ - internal class HotKeyCombination - { - public SDL.SDL_Keycode Key { get; set; } - public SDL.SDL_Keymod Mod { get; set; } - public HotkeyAction KeyAction { get; set; } - } - - internal class HotkeysManager - { - private readonly Dictionary _actions = new Dictionary(); - - private readonly List _hotkeys = new List(); - - public HotkeysManager() - { - Add(HotkeyAction.CastClumsy, () => GameActions.CastSpell(1)); - Add(HotkeyAction.CastCreateFood, () => GameActions.CastSpell(2)); - Add(HotkeyAction.CastFeeblemind, () => GameActions.CastSpell(3)); - Add(HotkeyAction.CastHeal, () => GameActions.CastSpell(4)); - Add(HotkeyAction.CastMagicArrow, () => GameActions.CastSpell(5)); - Add(HotkeyAction.CastNightSight, () => GameActions.CastSpell(6)); - Add(HotkeyAction.CastReactiveArmor, () => GameActions.CastSpell(7)); - Add(HotkeyAction.CastWeaken, () => GameActions.CastSpell(8)); - Add(HotkeyAction.CastAgility, () => GameActions.CastSpell(9)); - Add(HotkeyAction.CastCunning, () => GameActions.CastSpell(10)); - Add(HotkeyAction.CastCure, () => GameActions.CastSpell(11)); - Add(HotkeyAction.CastHarm, () => GameActions.CastSpell(12)); - Add(HotkeyAction.CastMagicTrap, () => GameActions.CastSpell(13)); - Add(HotkeyAction.CastMagicUntrap, () => GameActions.CastSpell(14)); - Add(HotkeyAction.CastProtection, () => GameActions.CastSpell(15)); - Add(HotkeyAction.CastStrength, () => GameActions.CastSpell(16)); - Add(HotkeyAction.CastBless, () => GameActions.CastSpell(17)); - Add(HotkeyAction.CastFireball, () => GameActions.CastSpell(18)); - Add(HotkeyAction.CastMagicLock, () => GameActions.CastSpell(19)); - Add(HotkeyAction.CastPosion, () => GameActions.CastSpell(20)); - Add(HotkeyAction.CastTelekinesis, () => GameActions.CastSpell(21)); - Add(HotkeyAction.CastTeleport, () => GameActions.CastSpell(22)); - Add(HotkeyAction.CastUnlock, () => GameActions.CastSpell(23)); - Add(HotkeyAction.CastWallOfStone, () => GameActions.CastSpell(24)); - Add(HotkeyAction.CastArchCure, () => GameActions.CastSpell(25)); - Add(HotkeyAction.CastArchProtection, () => GameActions.CastSpell(26)); - Add(HotkeyAction.CastCurse, () => GameActions.CastSpell(27)); - Add(HotkeyAction.CastFireField, () => GameActions.CastSpell(28)); - Add(HotkeyAction.CastGreaterHeal, () => GameActions.CastSpell(29)); - Add(HotkeyAction.CastLightning, () => GameActions.CastSpell(30)); - Add(HotkeyAction.CastManaDrain, () => GameActions.CastSpell(31)); - Add(HotkeyAction.CastRecall, () => GameActions.CastSpell(32)); - Add(HotkeyAction.CastBladeSpirits, () => GameActions.CastSpell(33)); - Add(HotkeyAction.CastDispelField, () => GameActions.CastSpell(34)); - Add(HotkeyAction.CastIncognito, () => GameActions.CastSpell(35)); - Add(HotkeyAction.CastMagicReflection, () => GameActions.CastSpell(36)); - Add(HotkeyAction.CastMindBlast, () => GameActions.CastSpell(37)); - Add(HotkeyAction.CastParalyze, () => GameActions.CastSpell(38)); - Add(HotkeyAction.CastPoisonField, () => GameActions.CastSpell(39)); - Add(HotkeyAction.CastSummonCreature, () => GameActions.CastSpell(40)); - Add(HotkeyAction.CastDispel, () => GameActions.CastSpell(41)); - Add(HotkeyAction.CastEnergyBolt, () => GameActions.CastSpell(42)); - Add(HotkeyAction.CastExplosion, () => GameActions.CastSpell(43)); - Add(HotkeyAction.CastInvisibility, () => GameActions.CastSpell(44)); - Add(HotkeyAction.CastMark, () => GameActions.CastSpell(45)); - Add(HotkeyAction.CastMassCurse, () => GameActions.CastSpell(46)); - Add(HotkeyAction.CastParalyzeField, () => GameActions.CastSpell(47)); - Add(HotkeyAction.CastReveal, () => GameActions.CastSpell(48)); - Add(HotkeyAction.CastChainLightning, () => GameActions.CastSpell(49)); - Add(HotkeyAction.CastEnergyField, () => GameActions.CastSpell(50)); - Add(HotkeyAction.CastFlamestrike, () => GameActions.CastSpell(51)); - Add(HotkeyAction.CastGateTravel, () => GameActions.CastSpell(52)); - Add(HotkeyAction.CastManaVampire, () => GameActions.CastSpell(53)); - Add(HotkeyAction.CastMassDispel, () => GameActions.CastSpell(54)); - Add(HotkeyAction.CastMeteorSwam, () => GameActions.CastSpell(55)); - Add(HotkeyAction.CastPolymorph, () => GameActions.CastSpell(56)); - Add(HotkeyAction.CastEarthquake, () => GameActions.CastSpell(57)); - Add(HotkeyAction.CastEnergyVortex, () => GameActions.CastSpell(58)); - Add(HotkeyAction.CastResurrection, () => GameActions.CastSpell(59)); - Add(HotkeyAction.CastAirElemental, () => GameActions.CastSpell(60)); - Add(HotkeyAction.CastSummonDaemon, () => GameActions.CastSpell(61)); - Add(HotkeyAction.CastEarthElemental, () => GameActions.CastSpell(62)); - Add(HotkeyAction.CastFireElemental, () => GameActions.CastSpell(63)); - Add(HotkeyAction.CastWaterElemental, () => GameActions.CastSpell(64)); - - - Add(HotkeyAction.CastAnimatedDead, () => GameActions.CastSpell(101)); - Add(HotkeyAction.CastBloodOath, () => GameActions.CastSpell(102)); - Add(HotkeyAction.CastCorpseSkin, () => GameActions.CastSpell(103)); - Add(HotkeyAction.CastCurseWeapon, () => GameActions.CastSpell(104)); - Add(HotkeyAction.CastEvilOmen, () => GameActions.CastSpell(105)); - Add(HotkeyAction.CastHorrificBeast, () => GameActions.CastSpell(106)); - Add(HotkeyAction.CastLichForm, () => GameActions.CastSpell(107)); - Add(HotkeyAction.CastMindRot, () => GameActions.CastSpell(108)); - Add(HotkeyAction.CastPainSpike, () => GameActions.CastSpell(109)); - Add(HotkeyAction.CastPoisonStrike, () => GameActions.CastSpell(110)); - Add(HotkeyAction.CastStrangle, () => GameActions.CastSpell(111)); - Add(HotkeyAction.CastSummonFamiliar, () => GameActions.CastSpell(112)); - Add(HotkeyAction.CastVampiricEmbrace, () => GameActions.CastSpell(113)); - Add(HotkeyAction.CastVangefulSpririt, () => GameActions.CastSpell(114)); - Add(HotkeyAction.CastWither, () => GameActions.CastSpell(115)); - Add(HotkeyAction.CastWraithForm, () => GameActions.CastSpell(116)); - Add(HotkeyAction.CastExorcism, () => GameActions.CastSpell(117)); - - - Add(HotkeyAction.CastCleanseByFire, () => GameActions.CastSpell(201)); - Add(HotkeyAction.CastCloseWounds, () => GameActions.CastSpell(202)); - Add(HotkeyAction.CastConsecrateWeapon, () => GameActions.CastSpell(203)); - Add(HotkeyAction.CastDispelEvil, () => GameActions.CastSpell(204)); - Add(HotkeyAction.CastDivineFury, () => GameActions.CastSpell(205)); - Add(HotkeyAction.CastEnemyOfOne, () => GameActions.CastSpell(206)); - Add(HotkeyAction.CastHolyLight, () => GameActions.CastSpell(207)); - Add(HotkeyAction.CastNobleSacrifice, () => GameActions.CastSpell(208)); - Add(HotkeyAction.CastRemoveCurse, () => GameActions.CastSpell(209)); - Add(HotkeyAction.CastSacredJourney, () => GameActions.CastSpell(210)); - - - Add(HotkeyAction.CastHonorableExecution, () => GameActions.CastSpell(401)); - Add(HotkeyAction.CastConfidence, () => GameActions.CastSpell(402)); - Add(HotkeyAction.CastEvasion, () => GameActions.CastSpell(403)); - Add(HotkeyAction.CastCounterAttack, () => GameActions.CastSpell(404)); - Add(HotkeyAction.CastLightningStrike, () => GameActions.CastSpell(405)); - Add(HotkeyAction.CastMomentumStrike, () => GameActions.CastSpell(406)); - - - Add(HotkeyAction.CastFocusAttack, () => GameActions.CastSpell(501)); - Add(HotkeyAction.CastDeathStrike, () => GameActions.CastSpell(502)); - Add(HotkeyAction.CastAnimalForm, () => GameActions.CastSpell(503)); - Add(HotkeyAction.CastKiAttack, () => GameActions.CastSpell(504)); - Add(HotkeyAction.CastSurpriseAttack, () => GameActions.CastSpell(505)); - Add(HotkeyAction.CastBackstab, () => GameActions.CastSpell(506)); - Add(HotkeyAction.CastShadowjump, () => GameActions.CastSpell(507)); - Add(HotkeyAction.CastMirrorImage, () => GameActions.CastSpell(508)); - - - Add(HotkeyAction.CastArcaneCircle, () => GameActions.CastSpell(601)); - Add(HotkeyAction.CastGiftOfRenewal, () => GameActions.CastSpell(602)); - Add(HotkeyAction.CastImmolatingWeapon, () => GameActions.CastSpell(603)); - Add(HotkeyAction.CastAttuneWeapon, () => GameActions.CastSpell(604)); - Add(HotkeyAction.CastThinderstorm, () => GameActions.CastSpell(605)); - Add(HotkeyAction.CastNaturesFury, () => GameActions.CastSpell(606)); - Add(HotkeyAction.CastSummonFey, () => GameActions.CastSpell(607)); - Add(HotkeyAction.CastSummonFiend, () => GameActions.CastSpell(608)); - Add(HotkeyAction.CastReaperForm, () => GameActions.CastSpell(609)); - Add(HotkeyAction.CastWildFire, () => GameActions.CastSpell(610)); - Add(HotkeyAction.CastEssenceOfWind, () => GameActions.CastSpell(611)); - Add(HotkeyAction.CastDryadAllure, () => GameActions.CastSpell(612)); - Add(HotkeyAction.CastEtherealVoyage, () => GameActions.CastSpell(613)); - Add(HotkeyAction.CastWordOfDeath, () => GameActions.CastSpell(614)); - Add(HotkeyAction.CastGiftOfLife, () => GameActions.CastSpell(615)); - - - Add(HotkeyAction.CastNetherBolt, () => GameActions.CastSpell(678)); - Add(HotkeyAction.CastHealingStone, () => GameActions.CastSpell(679)); - Add(HotkeyAction.CastPurgeMagic, () => GameActions.CastSpell(680)); - Add(HotkeyAction.CastEnchant, () => GameActions.CastSpell(681)); - Add(HotkeyAction.CastSleep, () => GameActions.CastSpell(682)); - Add(HotkeyAction.CastEagleStrike, () => GameActions.CastSpell(683)); - Add(HotkeyAction.CastAnimatedWeapon, () => GameActions.CastSpell(684)); - Add(HotkeyAction.CastStoneForm, () => GameActions.CastSpell(685)); - Add(HotkeyAction.CastSpellTrigger, () => GameActions.CastSpell(686)); - Add(HotkeyAction.CastMassSleep, () => GameActions.CastSpell(687)); - Add(HotkeyAction.CastCleansingWinds, () => GameActions.CastSpell(688)); - Add(HotkeyAction.CastBombard, () => GameActions.CastSpell(689)); - Add(HotkeyAction.CastSpellPlague, () => GameActions.CastSpell(690)); - Add(HotkeyAction.CastHailStorm, () => GameActions.CastSpell(691)); - Add(HotkeyAction.CastNetherCyclone, () => GameActions.CastSpell(692)); - Add(HotkeyAction.CastRisingColossus, () => GameActions.CastSpell(693)); - - - Add(HotkeyAction.CastInspire, () => GameActions.CastSpell(701)); - Add(HotkeyAction.CastInvigorate, () => GameActions.CastSpell(702)); - Add(HotkeyAction.CastResilience, () => GameActions.CastSpell(703)); - Add(HotkeyAction.CastPerseverance, () => GameActions.CastSpell(704)); - Add(HotkeyAction.CastTribulation, () => GameActions.CastSpell(705)); - Add(HotkeyAction.CastDespair, () => GameActions.CastSpell(706)); - - - Add(HotkeyAction.CastDeathRay, () => GameActions.CastSpell(707)); - Add(HotkeyAction.CastEtherealBurst, () => GameActions.CastSpell(708)); - Add(HotkeyAction.CastNetherBlast, () => GameActions.CastSpell(709)); - Add(HotkeyAction.CastMysticWeapon, () => GameActions.CastSpell(710)); - Add(HotkeyAction.CastCommandUndead, () => GameActions.CastSpell(711)); - Add(HotkeyAction.CastConduit, () => GameActions.CastSpell(712)); - Add(HotkeyAction.CastManaShield, () => GameActions.CastSpell(713)); - Add(HotkeyAction.CastSummonReaper, () => GameActions.CastSpell(714)); - Add(HotkeyAction.CastEnchantedSummoning, () => GameActions.CastSpell(715)); - Add(HotkeyAction.CastAnticipateHit, () => GameActions.CastSpell(716)); - Add(HotkeyAction.CastWarcry, () => GameActions.CastSpell(717)); - Add(HotkeyAction.CastIntuition, () => GameActions.CastSpell(718)); - Add(HotkeyAction.CastRejuvenate, () => GameActions.CastSpell(719)); - Add(HotkeyAction.CastHolyFist, () => GameActions.CastSpell(720)); - Add(HotkeyAction.CastShadow, () => GameActions.CastSpell(721)); - Add(HotkeyAction.CastWhiteTigerForm, () => GameActions.CastSpell(722)); - Add(HotkeyAction.CastFlamingShot, () => GameActions.CastSpell(723)); - Add(HotkeyAction.CastPlayingTheOdds, () => GameActions.CastSpell(724)); - Add(HotkeyAction.CastThrust, () => GameActions.CastSpell(725)); - Add(HotkeyAction.CastPierce, () => GameActions.CastSpell(726)); - Add(HotkeyAction.CastStagger, () => GameActions.CastSpell(727)); - Add(HotkeyAction.CastToughness, () => GameActions.CastSpell(728)); - Add(HotkeyAction.CastOnslaught, () => GameActions.CastSpell(729)); - Add(HotkeyAction.CastFocusedEye, () => GameActions.CastSpell(730)); - Add(HotkeyAction.CastElementalFury, () => GameActions.CastSpell(731)); - Add(HotkeyAction.CastCalledShot, () => GameActions.CastSpell(732)); - Add(HotkeyAction.CastWarriorsGifts, () => GameActions.CastSpell(733)); - Add(HotkeyAction.CastShieldBash, () => GameActions.CastSpell(734)); - Add(HotkeyAction.CastBodyguard, () => GameActions.CastSpell(735)); - Add(HotkeyAction.CastHeightenSenses, () => GameActions.CastSpell(736)); - Add(HotkeyAction.CastTolerance, () => GameActions.CastSpell(737)); - Add(HotkeyAction.CastInjectedStrike, () => GameActions.CastSpell(738)); - Add(HotkeyAction.CastPotency, () => GameActions.CastSpell(739)); - Add(HotkeyAction.CastRampage, () => GameActions.CastSpell(740)); - Add(HotkeyAction.CastFistsofFury, () => GameActions.CastSpell(741)); - Add(HotkeyAction.CastKnockout, () => GameActions.CastSpell(742)); - Add(HotkeyAction.CastWhispering, () => GameActions.CastSpell(743)); - Add(HotkeyAction.CastCombatTraining, () => GameActions.CastSpell(744)); - Add(HotkeyAction.CastBoarding, () => GameActions.CastSpell(745)); - } - - - public bool Bind(HotkeyAction action, SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - foreach (HotKeyCombination h in _hotkeys) - { - if (h.Key == key && h.Mod == mod) - { - return false; - } - } - - _hotkeys.Add - ( - new HotKeyCombination - { - Key = key, - Mod = mod, - KeyAction = action - } - ); - - return true; - } - - public void UnBind(HotkeyAction action) - { - for (int i = 0; i < _hotkeys.Count; i++) - { - HotKeyCombination h = _hotkeys[i]; - - if (h.KeyAction == action) - { - _hotkeys.RemoveAt(i); - - break; - } - } - } - - public bool TryExecuteIfBinded(SDL.SDL_Keycode key, SDL.SDL_Keymod mod, out Action action) - { - for (int i = 0; i < _hotkeys.Count; i++) - { - HotKeyCombination h = _hotkeys[i]; - - if (h.Key == key && h.Mod == mod) - { - if (_actions.TryGetValue(h.KeyAction, out action)) - { - return true; - } - - break; - } - } - - action = null; - - return false; - } - - public Dictionary GetValues() - { - return _actions; - } - - private void Add(HotkeyAction action, Action handler) - { - _actions.Add(action, handler); - } - } - - internal enum HotkeyAction - { - None, - - #region Magery - - CastClumsy, - CastCreateFood, - CastFeeblemind, - CastHeal, - CastMagicArrow, - CastNightSight, - CastReactiveArmor, - CastWeaken, - CastAgility, - CastCunning, - CastCure, - CastHarm, - CastMagicTrap, - CastMagicUntrap, - CastProtection, - CastStrength, - CastBless, - CastFireball, - CastMagicLock, - CastPosion, - CastTelekinesis, - CastTeleport, - CastUnlock, - CastWallOfStone, - CastArchCure, - CastArchProtection, - CastCurse, - CastFireField, - CastGreaterHeal, - CastLightning, - CastManaDrain, - CastRecall, - CastBladeSpirits, - CastDispelField, - CastIncognito, - CastMagicReflection, - CastMindBlast, - CastParalyze, - CastPoisonField, - CastSummonCreature, - CastDispel, - CastEnergyBolt, - CastExplosion, - CastInvisibility, - CastMark, - CastMassCurse, - CastParalyzeField, - CastReveal, - CastChainLightning, - CastEnergyField, - CastFlamestrike, - CastGateTravel, - CastManaVampire, - CastMassDispel, - CastMeteorSwam, - CastPolymorph, - CastEarthquake, - CastEnergyVortex, - CastResurrection, - CastAirElemental, - CastSummonDaemon, - CastEarthElemental, - CastFireElemental, - CastWaterElemental, - - #endregion - - #region Necro - - CastAnimatedDead, - CastBloodOath, - CastCorpseSkin, - CastCurseWeapon, - CastEvilOmen, - CastHorrificBeast, - CastLichForm, - CastMindRot, - CastPainSpike, - CastPoisonStrike, - CastStrangle, - CastSummonFamiliar, - CastVampiricEmbrace, - CastVangefulSpririt, - CastWither, - CastWraithForm, - CastExorcism, - - #endregion - - #region Chivalry - - CastCleanseByFire, - CastCloseWounds, - CastConsecrateWeapon, - CastDispelEvil, - CastDivineFury, - CastEnemyOfOne, - CastHolyLight, - CastNobleSacrifice, - CastRemoveCurse, - CastSacredJourney, - - #endregion - - #region Bushido - - CastHonorableExecution, - CastConfidence, - CastEvasion, - CastCounterAttack, - CastLightningStrike, - CastMomentumStrike, - - #endregion - - #region Ninja - - CastFocusAttack, - CastDeathStrike, - CastAnimalForm, - CastKiAttack, - CastSurpriseAttack, - CastBackstab, - CastShadowjump, - CastMirrorImage, - - #endregion - - #region Spellweaving - - CastArcaneCircle, - CastGiftOfRenewal, - CastImmolatingWeapon, - CastAttuneWeapon, - CastThinderstorm, - CastNaturesFury, - CastSummonFey, - CastSummonFiend, - CastReaperForm, - CastWildFire, - CastEssenceOfWind, - CastDryadAllure, - CastEtherealVoyage, - CastWordOfDeath, - CastGiftOfLife, - CastArcaneEmpowerment, - - #endregion - - #region Mysticism - - CastNetherBolt, - CastHealingStone, - CastPurgeMagic, - CastEnchant, - CastSleep, - CastEagleStrike, - CastAnimatedWeapon, - CastStoneForm, - CastSpellTrigger, - CastMassSleep, - CastCleansingWinds, - CastBombard, - CastSpellPlague, - CastHailStorm, - CastNetherCyclone, - CastRisingColossus, - - #endregion - - #region Bardic - - CastInspire, - CastInvigorate, - CastResilience, - CastPerseverance, - CastTribulation, - CastDespair, - - #endregion - - #region Other mastery spells - CastDeathRay, - CastEtherealBurst, - CastNetherBlast, - CastMysticWeapon, - CastCommandUndead, - CastConduit, - CastManaShield, - CastSummonReaper, - CastEnchantedSummoning, - CastAnticipateHit, - CastWarcry, - CastIntuition, - CastRejuvenate, - CastHolyFist, - CastShadow, - CastWhiteTigerForm, - CastFlamingShot, - CastPlayingTheOdds, - CastThrust, - CastPierce, - CastStagger, - CastToughness, - CastOnslaught, - CastFocusedEye, - CastElementalFury, - CastCalledShot, - CastWarriorsGifts, - CastShieldBash, - CastBodyguard, - CastHeightenSenses, - CastTolerance, - CastInjectedStrike, - CastPotency, - CastRampage, - CastFistsofFury, - CastKnockout, - CastWhispering, - CastCombatTraining, - CastBoarding, - #endregion - - #region Skills - - UseSkillAnatomy, - UseSkillAnimalLore, - UseSkillAnimalTaming, - UseSkillArmsLore, - UseSkillBegging, - UseSkillCartography, - UseSkillDetectingHidden, - UseSkillEnticement, - UseSkillEvaluatingIntelligence, - UseSkillForensicEvaluation, - UseSkillHiding, - UseSkillImbuing, - UseSkillInscription, - UseSkillItemIdentificator, - UseSkillMeditation, - UseSkillPeacemaking, - UseSkillPoisoning, - UseSkillProvocation, - UseSkillRemoveTrap, - UseSkillSpiritSpeak, - UseSkillStealing, - UseSkillStealth, - UseSkillTasteIdentification, - UseSkillTracking, - - #endregion - - #region Virtues - - UseVirtueHonor, - UseVirtueSacrifice, - UseVirtueValor, - - #endregion - - #region WalkDir - - WalkToNW, - WalkToN, - WalkToNE, - WalkToE, - WalkToSE, - WalkToS, - WalkToSW, - WalkToW, - - #endregion - - #region GumpAction - - OpenSettings, - OpenPaperdoll, - OpenStatus, - OpenJournal, - OpenSkills, - OpenMageSpellbook, - OpenNecroSpellbook, - OpenChivaSpellbook, - OpenBushidoSpellbook, - OpenNinjaSpellbook, - OpenSpellweaverSpellbook, - OpenMysticSpellbook, - OpenRacialAbilitiesBook, - OpenChat, - OpenBackpack, - OpenMinimap, - OpenParty, - OpenPartyChat, - OpenGuild, - OpenQuestLog, - ToggleBuffGump, - QuitGame, - SaveGumps, - - #endregion - - #region Abilities - - UsePrimaryAbility, - UseSecondaryAbility, - ClearCurrentAbility, - ToggleGargoyleFly, - - #endregion - - #region UseItems - - UseSelectedItem, - UseCurrentTarget, - BandageSelf, - BandageTarget, - - #endregion - - #region Speech - - Say, - Emote, - Whisper, - Yell, - - #endregion - - #region Targetting - - TargetNext, - TargetClosest, - TargetSelf, - - #endregion - - #region Attack - - AttackLast, - AttackSelected, - - #endregion - - #region SelectTarget - - SelectNext, - SelectPrevious, - SelectNearest, - - #endregion - - #region Misc - - ArmDisarm, - AllNames, - Bow, - Salute, - AlwaysRun, - EquipLastWeapon, - - #endregion - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/HouseCustomizationManager.cs b/src/ClassicUO.Client/Game/Managers/HouseCustomizationManager.cs deleted file mode 100644 index 48117b981..000000000 --- a/src/ClassicUO.Client/Game/Managers/HouseCustomizationManager.cs +++ /dev/null @@ -1,2148 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using ClassicUO.Assets; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Network; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.Managers -{ - public struct CustomBuildObject - { - public CustomBuildObject(ushort graphic) - { - Graphic = graphic; - X = Y = Z = 0; - } - - public ushort Graphic; - public int X, Y, Z; - } - - public class HouseCustomizationManager - { - public static readonly List Walls = new List(); - public static readonly List Floors = new List(); - public static readonly List Doors = new List(); - public static readonly List Miscs = new List(); - public static readonly List Stairs = new List(); - public static readonly List Teleports = new List(); - public static readonly List Roofs = new List(); - public static readonly List ObjectsInfo = new List(); - - static HouseCustomizationManager() - { - ParseFileWithCategory(Walls, UOFileManager.GetUOFilePath("walls.txt")); - - ParseFile(Floors, UOFileManager.GetUOFilePath("floors.txt")); - ParseFile(Doors, UOFileManager.GetUOFilePath("doors.txt")); - - ParseFileWithCategory(Miscs, UOFileManager.GetUOFilePath("misc.txt")); - - ParseFile(Stairs, UOFileManager.GetUOFilePath("stairs.txt")); - ParseFile(Teleports, UOFileManager.GetUOFilePath("teleprts.txt")); - - ParseFileWithCategory(Roofs, UOFileManager.GetUOFilePath("roof.txt")); - - ParseFile(ObjectsInfo, UOFileManager.GetUOFilePath("suppinfo.txt")); - } - - public HouseCustomizationManager(uint serial) - { - Serial = serial; - - InitializeHouse(); - } - - public int Category = -1, MaxPage = 1, CurrentFloor = 1, FloorCount = 4, RoofZ = 1, MinHouseZ = -120, Components, Fixtures, MaxComponets, MaxFixtures; - public bool Erasing, SeekTile, ShowWindow, CombinedStair; - - - public readonly int[] FloorVisionState = new int[4]; - - - public ushort SelectedGraphic; - - public readonly uint Serial; - public Point StartPos, EndPos; - public CUSTOM_HOUSE_GUMP_STATE State = CUSTOM_HOUSE_GUMP_STATE.CHGS_WALL; - - private void InitializeHouse() - { - Item foundation = World.Items.Get(Serial); - - if (foundation != null) - { - MinHouseZ = foundation.Z + 7; - - Rectangle? multi = foundation.MultiInfo; - - if (multi != null) - { - StartPos.X = foundation.X + multi.Value.X; - StartPos.Y = foundation.Y + multi.Value.Y; - EndPos.X = foundation.X + multi.Value.Width + 1; - EndPos.Y = foundation.Y + multi.Value.Height + 1; - } - - int width = Math.Abs(EndPos.X - StartPos.X); - int height = Math.Abs(EndPos.Y - StartPos.Y); - - if (width > 13 || height > 13) - { - FloorCount = 4; - } - else - { - FloorCount = 3; - } - - int componentsOnFloor = (width - 1) * (height - 1); - - MaxComponets = FloorCount * (componentsOnFloor + 2 * (width + height) - 4) - (int) (FloorCount * componentsOnFloor * -0.25) + 2 * width + 3 * height - 5; - - MaxFixtures = MaxComponets / 20; - } - } - - public void GenerateFloorPlace() - { - Item foundationItem = World.Items.Get(Serial); - - if (foundationItem != null && World.HouseManager.TryGetHouse(Serial, out House house)) - { - house.ClearCustomHouseComponents(CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_GENERIC_INTERNAL); - - foreach (Multi item in house.Components) - { - if (!item.IsCustom) - { - continue; - } - - int currentFloor = -1; - int floorZ = foundationItem.Z + 7; - int itemZ = item.Z; - - bool ignore = false; - - for (int i = 0; i < 4; i++) - { - int offset = 0 /*i != 0 ? 0 : 7*/; - - if (itemZ >= floorZ - offset && itemZ < floorZ + 20) - { - currentFloor = i; - - break; - } - - floorZ += 20; - } - - if (currentFloor == -1) - { - ignore = true; - currentFloor = 0; - //continue; - } - - (int floorCheck1, int floorCheck2) = SeekGraphicInCustomHouseObjectList(Floors, item.Graphic); - - CUSTOM_HOUSE_MULTI_OBJECT_FLAGS state = item.State; - - if (floorCheck1 != -1 && floorCheck2 != -1) - { - state |= CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR; - - if (FloorVisionState[currentFloor] == (int) CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_HIDE_FLOOR) - { - state |= CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_IGNORE_IN_RENDER; - } - else if (FloorVisionState[currentFloor] == (int) CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_TRANSPARENT_FLOOR || FloorVisionState[currentFloor] == (int) CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_TRANSLUCENT_FLOOR) - { - state |= CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_TRANSPARENT; - } - } - else - { - (int stairCheck1, int stairCheck2) = SeekGraphicInCustomHouseObjectList(Stairs, item.Graphic); - - if (stairCheck1 != -1 && stairCheck2 != -1) - { - state |= CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_STAIR; - } - else - { - (int roofCheck1, int roofCheck2) = SeekGraphicInCustomHouseObjectListWithCategory(Roofs, item.Graphic); - - if (roofCheck1 != -1 && roofCheck2 != -1) - { - state |= CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_ROOF; - } - else - { - (int fixtureCheck1, int fixtureCheck2) = SeekGraphicInCustomHouseObjectList(Doors, item.Graphic); - - if (fixtureCheck1 == -1 || fixtureCheck2 == -1) - { - (fixtureCheck1, fixtureCheck2) = SeekGraphicInCustomHouseObjectList(Teleports, item.Graphic); - - if (fixtureCheck1 != -1 && fixtureCheck2 != -1) - { - state |= CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR; - } - } - else - { - state |= CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FIXTURE; - } - } - } - - if (!ignore) - { - if (FloorVisionState[currentFloor] == (int) CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_HIDE_CONTENT) - { - state |= CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_IGNORE_IN_RENDER; - } - else if (FloorVisionState[currentFloor] == (int) CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_TRANSPARENT_CONTENT) - { - state |= CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_TRANSPARENT; - } - } - } - - if (!ignore) - { - if (FloorVisionState[currentFloor] == (int) CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_HIDE_ALL) - { - state |= CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_IGNORE_IN_RENDER; - } - } - - item.State = state; - } - - int z = foundationItem.Z + 7; - - for (int x = StartPos.X + 1; x < EndPos.X; x++) - { - for (int y = StartPos.Y + 1; y < EndPos.Y; y++) - { - IEnumerable multi = house.Components.Where(s => s.X == x && s.Y == y); - - if (multi == null) - { - continue; - } - - Multi floorMulti = null; - Multi floorCustomMulti = null; - - foreach (Multi item in multi) - { - if (item.Z != z || (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR) == 0) - { - continue; - } - - if (item.IsCustom) - { - floorCustomMulti = item; - } - else - { - floorMulti = item; - } - } - - if (floorMulti != null && floorCustomMulti == null) - { - Multi mo = house.Add - ( - floorMulti.Graphic, - 0, - (ushort) (foundationItem.X + (x - foundationItem.X)), - (ushort) (foundationItem.Y + (y - foundationItem.Y)), - (sbyte) z, - true, - false - ); - - mo.AlphaHue = 0xFF; - - CUSTOM_HOUSE_MULTI_OBJECT_FLAGS state = CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR; - - if (FloorVisionState[0] == (int) CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_HIDE_FLOOR) - { - state |= CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_IGNORE_IN_RENDER; - } - else if (FloorVisionState[0] == (int) CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_TRANSPARENT_FLOOR || FloorVisionState[0] == (int) CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_TRANSLUCENT_FLOOR) - { - state |= CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_TRANSPARENT; - } - - mo.State = state; - } - } - } - - for (int i = 0; i < FloorCount; i++) - { - int minZ = foundationItem.Z + 7 + i * 20; - int maxZ = minZ + 20; - - for (int j = 0; j < 2; j++) - { - List validatedFloors = new List(); - - for (int x = StartPos.X; x < EndPos.X + 1; x++) - { - for (int y = StartPos.Y; y < EndPos.Y + 1; y++) - { - IEnumerable multi = house.GetMultiAt(x, y); - - if (multi == null) - { - continue; - } - - foreach (Multi item in multi) - { - if (!item.IsCustom) - { - continue; - } - - if (j == 0) - { - if (i == 0 && item.Z < minZ) - { - item.State = item.State | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE; - - continue; - } - - if ((item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR) == 0) - { - continue; - } - - if (i == 0 && item.Z >= minZ && item.Z < maxZ) - { - item.State = item.State | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE; - - continue; - } - } - - if ((item.State & (CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_GENERIC_INTERNAL)) == 0 && item.Z >= minZ && item.Z < maxZ) - { - if (!ValidateItemPlace - ( - foundationItem, - item, - minZ, - maxZ, - validatedFloors - )) - { - item.State = item.State | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_INCORRECT_PLACE; - } - else - { - item.State = item.State | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE; - } - } - } - } - } - - if (i != 0 && j == 0) - { - foreach (Point point in validatedFloors) - { - IEnumerable multi = house.GetMultiAt(point.X, point.Y); - - if (multi == null) - { - continue; - } - - foreach (Multi item in multi) - { - if (item.IsCustom && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR) != 0 && item.Z >= minZ && item.Z < maxZ) - { - item.State = item.State & ~CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_INCORRECT_PLACE; - } - } - } - - for (int x = StartPos.X; x < EndPos.X + 1; x++) - { - int minY = 0, maxY = 0; - - for (int y = StartPos.Y; y < EndPos.Y + 1; y++) - { - IEnumerable multi = house.GetMultiAt(x, y); - - if (multi == null) - { - continue; - } - - foreach (Multi item in multi) - { - if (item.IsCustom && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR) != 0 && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE) != 0 && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_INCORRECT_PLACE) == 0 && item.Z >= minZ && item.Z < maxZ) - { - minY = y; - - break; - } - } - - if (minY != 0) - { - break; - } - } - - for (int y = EndPos.Y; y >= StartPos.Y; y--) - { - IEnumerable multi = house.GetMultiAt(x, y); - - if (multi == null) - { - continue; - } - - foreach (Multi item in multi) - { - if (item.IsCustom && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR) != 0 && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE) != 0 && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_INCORRECT_PLACE) == 0 && item.Z >= minZ && item.Z < maxZ) - { - maxY = y; - - break; - } - } - - if (maxY != 0) - { - break; - } - } - - for (int y = minY; y < maxY; y++) - { - IEnumerable multi = house.GetMultiAt(x, y); - - if (multi == null) - { - continue; - } - - foreach (Multi item in multi) - { - if (item.IsCustom && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR) != 0 && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE) != 0 && item.Z >= minZ && item.Z < maxZ) - { - item.State = item.State & ~CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_INCORRECT_PLACE; - } - } - } - } - - for (int y = StartPos.Y; y < EndPos.Y + 1; y++) - { - int minX = 0; - int maxX = 0; - - for (int x = StartPos.X; x < EndPos.X + 1; x++) - { - IEnumerable multi = house.GetMultiAt(x, y); - - if (multi == null) - { - continue; - } - - foreach (Multi item in multi) - { - if (item.IsCustom && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR) != 0 && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE) != 0 && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_INCORRECT_PLACE) == 0 && item.Z >= minZ && item.Z < maxZ) - { - minX = x; - - break; - } - } - - if (minX != 0) - { - break; - } - } - - for (int x = EndPos.X; x >= StartPos.X; x--) - { - IEnumerable multi = house.GetMultiAt(x, y); - - if (multi == null) - { - continue; - } - - foreach (Multi item in multi) - { - if (item.IsCustom && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR) != 0 && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE) != 0 && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_INCORRECT_PLACE) == 0 && item.Z >= minZ && item.Z < maxZ) - { - maxX = x; - - break; - } - } - - if (maxX != 0) - { - break; - } - } - - for (int x = minX; x < maxX; x++) - { - IEnumerable multi = house.GetMultiAt(x, y); - - if (multi == null) - { - continue; - } - - foreach (Multi item in multi) - { - if (item.IsCustom && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR) != 0 && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE) != 0 && item.Z >= minZ && item.Z < maxZ) - { - item.State = item.State & ~CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_INCORRECT_PLACE; - } - } - } - } - } - } - } - - z = foundationItem.Z + 7 + 20; - - ushort color = 0x0051; - - for (int i = 1; i < CurrentFloor; i++) - { - for (int x = StartPos.X; x < EndPos.X; x++) - { - for (int y = StartPos.Y; y < EndPos.Y; y++) - { - ushort tempColor = color; - - if (x == StartPos.X || y == StartPos.Y) - { - tempColor++; - } - - Multi mo = house.Add - ( - 0x0496, - tempColor, - (ushort)(foundationItem.X + (x - foundationItem.X)), - (ushort)(foundationItem.Y + (y - foundationItem.Y)), - (sbyte) z, - true, - false - ); - - mo.AlphaHue = 0xFF; - - mo.State = CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_GENERIC_INTERNAL | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_TRANSPARENT; - - mo.AddToTile(); - } - } - - color += 5; - z += 20; - } - } - } - - public void OnTargetWorld(GameObject place) - { - if (place != null /*&& place is Multi m*/) - { - int zOffset = 0; - - HouseCustomizationGump gump = UIManager.GetGump(Serial); - - if (CurrentFloor == 1) - { - zOffset = -7; - } - - if (SeekTile) - { - if (place is Multi) - { - SeekGraphic(place.Graphic); - } - } - else if (place.Z >= World.Player.Z + zOffset && place.Z < World.Player.Z + 20) - { - Item foundationItem = World.Items.Get(Serial); - - if (foundationItem == null || !World.HouseManager.TryGetHouse(Serial, out House house)) - { - return; - } - - if (Erasing) - { - if (!(place is Multi)) - { - return; - } - - if (CanEraseHere(place, out CUSTOM_HOUSE_BUILD_TYPE type)) - { - IEnumerable multi = house.GetMultiAt(place.X, place.Y); - - if (multi == null || !multi.Any()) - { - return; - } - - int z = 7 + (CurrentFloor - 1) * 20; - - if (type == CUSTOM_HOUSE_BUILD_TYPE.CHBT_STAIR || type == CUSTOM_HOUSE_BUILD_TYPE.CHBT_ROOF) - { - z = place.Z - (foundationItem.Z + z) + z; - } - - if (type == CUSTOM_HOUSE_BUILD_TYPE.CHBT_ROOF) - { - NetClient.Socket.Send_CustomHouseDeleteRoof(place.Graphic, place.X - foundationItem.X, place.Y - foundationItem.Y, z); - } - else - { - NetClient.Socket.Send_CustomHouseDeleteItem(place.Graphic, place.X - foundationItem.X, place.Y - foundationItem.Y, z); - } - - place.Destroy(); - } - } - else if (SelectedGraphic != 0) - { - CustomBuildObject[] list = new CustomBuildObject[10]; - - if (CanBuildHere(list, out CUSTOM_HOUSE_BUILD_TYPE type) && list.Length != 0) - { - //if (type != CUSTOM_HOUSE_BUILD_TYPE.CHBT_STAIR && !(place is Multi)) - // return; - - int placeX = place.X; - int placeY = place.Y; - - if (type == CUSTOM_HOUSE_BUILD_TYPE.CHBT_STAIR && CombinedStair) - { - if (gump.Page >= 0 && gump.Page < Stairs.Count) - { - CustomHouseStair stair = Stairs[gump.Page]; - - ushort graphic = 0; - - if (SelectedGraphic == stair.North) - { - graphic = (ushort) stair.MultiNorth; - } - else if (SelectedGraphic == stair.East) - { - graphic = (ushort) stair.MultiEast; - } - else if (SelectedGraphic == stair.South) - { - graphic = (ushort) stair.MultiSouth; - } - else if (SelectedGraphic == stair.West) - { - graphic = (ushort) stair.MultiWest; - } - - if (graphic != 0) - { - NetClient.Socket.Send_CustomHouseAddStair(graphic, placeX - foundationItem.X, placeY - foundationItem.Y); - } - } - } - else - { - CustomBuildObject item = list[0]; - - int x = placeX - foundationItem.X + item.X; - int y = placeY - foundationItem.Y + item.Y; - IEnumerable multi = house.GetMultiAt(placeX + item.X, placeY + item.Y); - - if (multi.Any() || type == CUSTOM_HOUSE_BUILD_TYPE.CHBT_STAIR) - { - if (!CombinedStair) - { - int minZ = foundationItem.Z + 7 + (CurrentFloor - 1) * 20; - int maxZ = minZ + 20; - - if (CurrentFloor == 1) - { - minZ -= 7; - } - - foreach (Multi multiObject in multi) - { - int testMinZ = minZ; - - if ((multiObject.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_ROOF) != 0) - { - testMinZ -= 3; - } - - if (multiObject.Z < testMinZ || multiObject.Z >= maxZ || !multiObject.IsCustom || (multiObject.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_GENERIC_INTERNAL) != 0 /*|| (multiObject.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_DONT_REMOVE) != 0*/ - ) - { - continue; - } - - if (type == CUSTOM_HOUSE_BUILD_TYPE.CHBT_STAIR) - { - if ((multiObject.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_STAIR) != 0) - { - multiObject.Destroy(); - } - } - else if (type == CUSTOM_HOUSE_BUILD_TYPE.CHBT_ROOF) - { - if ((multiObject.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_ROOF) != 0) - { - multiObject.Destroy(); - } - } - else if (type == CUSTOM_HOUSE_BUILD_TYPE.CHBT_FLOOR) - { - if ((multiObject.State & (CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FIXTURE)) != 0) - { - multiObject.Destroy(); - } - } - else - { - if ((multiObject.State & (CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_STAIR | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_ROOF | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_DONT_REMOVE)) == 0) - { - multiObject.Destroy(); - } - } - } - - // todo: remove foundation if no components - } - - if (type == CUSTOM_HOUSE_BUILD_TYPE.CHBT_ROOF) - { - NetClient.Socket.Send_CustomHouseAddRoof(item.Graphic, x, y, item.Z); - } - else - { - NetClient.Socket.Send_CustomHouseAddItem(item.Graphic, x, y); - } - } - } - - int xx = placeX - foundationItem.X; - int yy = placeY - foundationItem.Y; - int z = foundationItem.Z + 7 + (CurrentFloor - 1) * 20; - - if (type == CUSTOM_HOUSE_BUILD_TYPE.CHBT_STAIR && !CombinedStair) - { - z = foundationItem.Z; - } - - foreach (CustomBuildObject item in list) - { - if (item.Graphic == 0) - { - break; - } - - house.Add - ( - item.Graphic, - 0, - (ushort) (foundationItem.X + xx + item.X), - (ushort) (foundationItem.Y + yy + item.Y), - (sbyte) (z + item.Z), - true, - false - ); - } - } - } - - GenerateFloorPlace(); - gump.Update(); - } - } - } - - private void SeekGraphic(ushort graphic) - { - CUSTOM_HOUSE_GUMP_STATE state = 0; - (int res1, int res2) = ExistsInList(ref state, graphic); - - if (res1 != -1 && res2 != -1) - { - State = state; - HouseCustomizationGump gump = UIManager.GetGump(Serial); - - if (State == CUSTOM_HOUSE_GUMP_STATE.CHGS_WALL || State == CUSTOM_HOUSE_GUMP_STATE.CHGS_ROOF || State == CUSTOM_HOUSE_GUMP_STATE.CHGS_MISC) - { - Category = res1; - gump.Page = res2; - } - else - { - Category = -1; - gump.Page = res1; - } - - gump.UpdateMaxPage(); - SetTargetMulti(); - SelectedGraphic = graphic; - gump.Update(); - } - } - - public void SetTargetMulti() - { - TargetManager.SetTargetingMulti - ( - 0, - 0, - 0, - 0, - 0, - 0 - ); - - Erasing = false; - SeekTile = false; - SelectedGraphic = 0; - CombinedStair = false; - } - - public bool CanBuildHere(CustomBuildObject[] list, out CUSTOM_HOUSE_BUILD_TYPE type) - { - type = CUSTOM_HOUSE_BUILD_TYPE.CHBT_NORMAL; - - if (SelectedGraphic == 0) - { - return false; - } - - bool result = true; - - if (CombinedStair) - { - if (Components + 10 > MaxComponets) - { - return false; - } - - (int res1, int res2) = SeekGraphicInCustomHouseObjectList(Stairs, SelectedGraphic); - - if (res1 == -1 || res2 == -1 || res1 >= Stairs.Count) - { - list[0].Graphic = SelectedGraphic; - - list[0].X = 0; - - list[0].Y = 0; - - list[0].Z = 0; - - return false; - } - - CustomHouseStair item = Stairs[res1]; - - //if (StairMultis.Count == 0) - { - if (SelectedGraphic == item.North) - { - list[0].Graphic = (ushort) item.Block; - - list[0].X = 0; - - list[0].Y = -3; - - list[0].Z = 0; - - list[1].Graphic = (ushort) item.Block; - - list[1].X = 0; - - list[1].Y = -2; - - list[1].Z = 0; - - list[2].Graphic = (ushort) item.Block; - - list[2].X = 0; - - list[2].Y = -1; - - list[2].Z = 0; - - list[3].Graphic = (ushort) item.North; - - list[3].X = 0; - - list[3].Y = 0; - - list[3].Z = 0; - - list[4].Graphic = (ushort) item.Block; - - list[4].X = 0; - - list[4].Y = -3; - - list[4].Z = 5; - - list[5].Graphic = (ushort) item.Block; - - list[5].X = 0; - - list[5].Y = -2; - - list[5].Z = 5; - - list[6].Graphic = (ushort) item.North; - - list[6].X = 0; - - list[6].Y = -1; - - list[6].Z = 5; - - list[7].Graphic = (ushort) item.Block; - - list[7].X = 0; - - list[7].Y = -3; - - list[7].Z = 10; - - list[8].Graphic = (ushort) item.North; - - list[8].X = 0; - - list[8].Y = -2; - - list[8].Z = 10; - - list[9].Graphic = (ushort) item.North; - - list[9].X = 0; - - list[9].Y = -3; - - list[9].Z = 15; - } - else if (SelectedGraphic == item.East) - { - list[0].Graphic = (ushort) item.East; - - list[0].X = 0; - - list[0].Y = 0; - - list[0].Z = 0; - - list[1].Graphic = (ushort) item.Block; - - list[1].X = 1; - - list[1].Y = 0; - - list[1].Z = 0; - - list[2].Graphic = (ushort) item.Block; - - list[2].X = 2; - - list[2].Y = 0; - - list[2].Z = 0; - - list[3].Graphic = (ushort) item.Block; - - list[3].X = 3; - - list[3].Y = 0; - - list[3].Z = 0; - - list[4].Graphic = (ushort) item.East; - - list[4].X = 1; - - list[4].Y = 0; - - list[4].Z = 5; - - list[5].Graphic = (ushort) item.Block; - - list[5].X = 2; - - list[5].Y = 0; - - list[5].Z = 5; - - list[6].Graphic = (ushort) item.Block; - - list[6].X = 3; - - list[6].Y = 0; - - list[6].Z = 5; - - list[7].Graphic = (ushort) item.East; - - list[7].X = 2; - - list[7].Y = 0; - - list[7].Z = 10; - - list[8].Graphic = (ushort) item.Block; - - list[8].X = 3; - - list[8].Y = 0; - - list[8].Z = 10; - - list[9].Graphic = (ushort) item.East; - - list[9].X = 3; - - list[9].Y = 0; - - list[9].Z = 15; - } - else if (SelectedGraphic == item.South) - { - list[0].Graphic = (ushort) item.South; - - list[0].X = 0; - - list[0].Y = 0; - - list[0].Z = 0; - - list[1].Graphic = (ushort) item.Block; - - list[1].X = 0; - - list[1].Y = 1; - - list[1].Z = 0; - - list[2].Graphic = (ushort) item.Block; - - list[2].X = 0; - - list[2].Y = 2; - - list[2].Z = 0; - - list[3].Graphic = (ushort) item.Block; - - list[3].X = 0; - - list[3].Y = 3; - - list[3].Z = 0; - - list[4].Graphic = (ushort) item.South; - - list[4].X = 0; - - list[4].Y = 1; - - list[4].Z = 5; - - list[5].Graphic = (ushort) item.Block; - - list[5].X = 0; - - list[5].Y = 2; - - list[5].Z = 5; - - list[6].Graphic = (ushort) item.Block; - - list[6].X = 0; - - list[6].Y = 3; - - list[6].Z = 5; - - list[7].Graphic = (ushort) item.South; - - list[7].X = 0; - - list[7].Y = 2; - - list[7].Z = 10; - - list[8].Graphic = (ushort) item.Block; - - list[8].X = 0; - - list[8].Y = 3; - - list[8].Z = 10; - - list[9].Graphic = (ushort) item.South; - - list[9].X = 0; - - list[9].Y = 3; - - list[9].Z = 15; - } - else if (SelectedGraphic == item.West) - { - list[0].Graphic = (ushort) item.Block; - - list[0].X = -3; - - list[0].Y = 0; - - list[0].Z = 0; - - list[1].Graphic = (ushort) item.Block; - - list[1].X = -2; - - list[1].Y = 0; - - list[1].Z = 0; - - list[2].Graphic = (ushort) item.Block; - - list[2].X = -1; - - list[2].Y = 0; - - list[2].Z = 0; - - list[3].Graphic = (ushort) item.West; - - list[3].X = 0; - - list[3].Y = 0; - - list[3].Z = 0; - - list[4].Graphic = (ushort) item.Block; - - list[4].X = -3; - - list[4].Y = 0; - - list[4].Z = 5; - - list[5].Graphic = (ushort) item.Block; - - list[5].X = -2; - - list[5].Y = 0; - - list[5].Z = 5; - - list[6].Graphic = (ushort) item.West; - - list[6].X = -1; - - list[6].Y = 0; - - list[6].Z = 5; - - list[7].Graphic = (ushort) item.Block; - - list[7].X = -3; - - list[7].Y = 0; - - list[7].Z = 10; - - list[8].Graphic = (ushort) item.West; - - list[8].X = -2; - - list[8].Y = 0; - - list[8].Z = 10; - - list[9].Graphic = (ushort) item.West; - - list[9].X = -3; - - list[9].Y = 0; - - list[9].Z = 15; - } - else - { - list[0].Graphic = SelectedGraphic; - - list[0].X = 0; - - list[0].Y = 0; - - list[0].Z = 0; - } - } - - type = CUSTOM_HOUSE_BUILD_TYPE.CHBT_STAIR; - } - else - { - (int fixCheck1, int fixCheck2) = SeekGraphicInCustomHouseObjectList(Doors, SelectedGraphic); - - bool isFixture = false; - - if (fixCheck1 == -1 || fixCheck2 == -1) - { - (fixCheck1, fixCheck2) = SeekGraphicInCustomHouseObjectList(Teleports, SelectedGraphic); - - isFixture = fixCheck1 != -1 && fixCheck2 != -1; - - if (isFixture) - { - type = CUSTOM_HOUSE_BUILD_TYPE.CHBT_FLOOR; - } - } - else - { - isFixture = true; - type = CUSTOM_HOUSE_BUILD_TYPE.CHBT_NORMAL; - } - - if (isFixture) - { - if (Fixtures + 1 > MaxFixtures) - { - result = false; - } - } - else if (Components + 1 > MaxComponets) - { - result = false; - } - - if (State == CUSTOM_HOUSE_GUMP_STATE.CHGS_ROOF) - { - list[0].Graphic = SelectedGraphic; - - list[0].X = 0; - - list[0].Y = 0; - - list[0].Z = (RoofZ - 2) * 3; - - type = CUSTOM_HOUSE_BUILD_TYPE.CHBT_ROOF; - } - else - { - if (State == CUSTOM_HOUSE_GUMP_STATE.CHGS_STAIR) - { - list[0].Graphic = SelectedGraphic; - - list[0].X = 0; - - list[0].Y = 1; - - list[0].Z = 0; - - type = CUSTOM_HOUSE_BUILD_TYPE.CHBT_STAIR; - } - else - { - if (State == CUSTOM_HOUSE_GUMP_STATE.CHGS_FLOOR) - { - type = CUSTOM_HOUSE_BUILD_TYPE.CHBT_FLOOR; - } - - list[0].Graphic = SelectedGraphic; - - list[0].X = 0; - - list[0].Y = 0; - - list[0].Z = 0; - } - } - } - - if (SelectedObject.Object is GameObject gobj) - { - if (gobj.Z < MinHouseZ) - { - if (CombinedStair) - { - if (gobj.X >= EndPos.X || gobj.Y >= EndPos.Y) - { - return false; - } - } - else if (type != CUSTOM_HOUSE_BUILD_TYPE.CHBT_STAIR) - { - if (gobj.X > EndPos.X - 1 || gobj.Y > EndPos.Y - 1) - { - return false; - } - } - } - - //if ((type != CUSTOM_HOUSE_BUILD_TYPE.CHBT_STAIR || CombinedStair) && gobj.Z < MinHouseZ && - // (gobj.X == EndPos.X - 1 || gobj.Y == EndPos.Y - 1)) - //{ - // return false; - //} - - Item foundationItem = World.Items.Get(Serial); - - int minZ = (foundationItem?.Z ?? 0) + 7 + (CurrentFloor - 1) * 20; - int maxZ = minZ + 20; - - int boundsOffset = State != CUSTOM_HOUSE_GUMP_STATE.CHGS_WALL ? 1 : 0; - - Rectangle rect = new Rectangle(StartPos.X + boundsOffset, StartPos.Y + boundsOffset, EndPos.X, EndPos.Y); - - - foreach (CustomBuildObject item in list) - { - if (type == CUSTOM_HOUSE_BUILD_TYPE.CHBT_STAIR) - { - if (CombinedStair) - { - if (item.Z != 0) - { - continue; - } - } - else - { - int sx = gobj.X + item.X; - int sy = gobj.Y + item.Y; - - if (sy < EndPos.Y || sx == StartPos.X || gobj.Z >= MinHouseZ) - - //if ( !(sx > StartPos.X && sx < EndPos.X && sy >= EndPos.Y && sy <= EndPos.Y + 1) || gobj.Z >= MinHouseZ) - { - return false; - } - - if (gobj.Y + item.Y != EndPos.Y) - { - list[0].Y = 0; - } - - continue; - } - } - - if (!ValidateItemPlace(rect, item.Graphic, gobj.X + item.X, gobj.Y + item.Y)) - { - return false; - } - - if (type != CUSTOM_HOUSE_BUILD_TYPE.CHBT_FLOOR && foundationItem != null && World.HouseManager.TryGetHouse(Serial, out House house)) - { - //var multi = house.GetMultiAt(gobj.X + item.X, gobj.Y + item.Y); - - //if (multi != null) - { - foreach (Multi multiObject in house.Components.Where(s => s.X == gobj.X + item.X && s.Y == gobj.Y + item.Y)) - { - if (multiObject.IsCustom && (multiObject.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_GENERIC_INTERNAL) == 0 && multiObject.Z >= minZ && multiObject.Z < maxZ) - { - if (type == CUSTOM_HOUSE_BUILD_TYPE.CHBT_STAIR) - { - if ((multiObject.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR) == 0) - { - return false; - } - } - else - { - if ((multiObject.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_STAIR) != 0) - { - return false; - } - } - } - } - } - } - } - } - else - { - return false; - } - - return result; - } - - public bool CanEraseHere(GameObject place, out CUSTOM_HOUSE_BUILD_TYPE type) - { - type = CUSTOM_HOUSE_BUILD_TYPE.CHBT_NORMAL; - - if (place != null && place is Multi multi) - { - if (multi.IsCustom && (multi.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_GENERIC_INTERNAL) == 0) - { - if ((multi.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR) != 0) - { - type = CUSTOM_HOUSE_BUILD_TYPE.CHBT_FLOOR; - } - else if ((multi.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_STAIR) != 0) - { - type = CUSTOM_HOUSE_BUILD_TYPE.CHBT_STAIR; - } - else if ((multi.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_ROOF) != 0) - { - type = CUSTOM_HOUSE_BUILD_TYPE.CHBT_ROOF; - } - else if (place.X >= StartPos.X && place.X <= EndPos.X && place.Y >= StartPos.Y && place.Y <= EndPos.Y && place.Z >= MinHouseZ) - { - // it's into the bounds - } - else - { - return false; - } - - return true; - } - } - - return false; - } - - public (int, int) ExistsInList(ref CUSTOM_HOUSE_GUMP_STATE state, ushort graphic) - { - (int res1, int res2) = SeekGraphicInCustomHouseObjectListWithCategory(Walls, graphic); - - if (res1 == -1 || res2 == -1) - { - (res1, res2) = SeekGraphicInCustomHouseObjectList(Floors, graphic); - - if (res1 == -1 || res2 == -1) - { - (res1, res2) = SeekGraphicInCustomHouseObjectList(Doors, graphic); - - if (res1 == -1 || res2 == -1) - { - (res1, res2) = SeekGraphicInCustomHouseObjectListWithCategory(Miscs, graphic); - - if (res1 == -1 || res2 == -1) - { - (res1, res2) = SeekGraphicInCustomHouseObjectList(Stairs, graphic); - - if (res1 == -1 || res2 == -1) - { - (res1, res2) = SeekGraphicInCustomHouseObjectListWithCategory(Roofs, graphic); - - if (res1 != -1 && res2 != -1) - { - state = CUSTOM_HOUSE_GUMP_STATE.CHGS_ROOF; - } - } - else - { - state = CUSTOM_HOUSE_GUMP_STATE.CHGS_STAIR; - } - } - else - { - (int res_1, int res_2) = SeekGraphicInCustomHouseObjectList(Teleports, graphic); - - if (res_1 != -1 && res_2 != -1) - { - state = CUSTOM_HOUSE_GUMP_STATE.CHGS_FIXTURE; - res1 = res_1; - res2 = res_2; - } - else - { - state = CUSTOM_HOUSE_GUMP_STATE.CHGS_MISC; - } - } - } - else - { - state = CUSTOM_HOUSE_GUMP_STATE.CHGS_DOOR; - } - } - else - { - state = CUSTOM_HOUSE_GUMP_STATE.CHGS_FLOOR; - } - } - else - { - state = CUSTOM_HOUSE_GUMP_STATE.CHGS_WALL; - } - - return (res1, res2); - } - - private bool ValidateItemPlace(Rectangle rect, ushort graphic, int x, int y) - { - if (!rect.Contains(x, y)) - { - return false; - } - - (int infoCheck1, int infoCheck2) = SeekGraphicInCustomHouseObjectList(ObjectsInfo, graphic); - - if (infoCheck1 != -1 && infoCheck2 != -1) - { - CustomHousePlaceInfo info = ObjectsInfo[infoCheck1]; - - if (info.CanGoW == 0 && x == StartPos.X) - { - return false; - } - - if (info.CanGoN == 0 && y == StartPos.Y) - { - return false; - } - - if (info.CanGoNWS == 0 && x == StartPos.X && y == StartPos.Y) - { - return false; - } - } - - return true; - } - - public bool ValidateItemPlace(Item foundationItem, Multi item, int minZ, int maxZ, List validatedFloors) - { - if (item == null || !World.HouseManager.TryGetHouse(foundationItem, out House house) || !item.IsCustom) - { - return true; - } - - if ((item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR) != 0) - { - bool existsInList(List list, Point testedPoint) - { - foreach (Point point in list) - { - if (testedPoint == point) - { - return true; - } - } - - return false; - } - - if (ValidatePlaceStructure - ( - foundationItem, - house, - house.GetMultiAt(item.X, item.Y), - minZ - 20, - maxZ - 20, - (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_DIRECT_SUPPORT - ) || ValidatePlaceStructure - ( - foundationItem, - house, - house.GetMultiAt(item.X - 1, item.Y - 1), - minZ - 20, - maxZ - 20, - (int) (CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_DIRECT_SUPPORT | CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_CANGO_W) - ) || ValidatePlaceStructure - ( - foundationItem, - house, - house.GetMultiAt(item.X, item.Y - 1), - minZ - 20, - maxZ - 20, - (int) (CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_DIRECT_SUPPORT | CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_CANGO_N) - )) - { - Point[] table = - { - new Point(-1, 0), - new Point(0, -1), - new Point(1, 0), - new Point(0, 1) - }; - - for (int i = 0; i < 4; i++) - { - Point testPoint = new Point(item.X + table[i].X, item.Y + table[i].Y); - - if (!existsInList(validatedFloors, testPoint)) - { - validatedFloors.Add(testPoint); - } - } - - return true; - } - - return false; - } - - - if ((item.State & (CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_STAIR | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_ROOF | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FIXTURE)) != 0) - { - foreach (Multi temp in house.GetMultiAt(item.X, item.Y)) - { - if (temp == item) - { - continue; - } - - if ((temp.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR) != 0 && temp.Z >= minZ && temp.Z < maxZ) - { - if ((temp.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE) != 0 && (temp.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_INCORRECT_PLACE) == 0) - { - return true; - } - } - } - - return false; - } - - - (int infoCheck1, int infoCheck2) = SeekGraphicInCustomHouseObjectList(ObjectsInfo, item.Graphic); - - if (infoCheck1 != -1 && infoCheck2 != -1) - { - CustomHousePlaceInfo info = ObjectsInfo[infoCheck1]; - - if (info.CanGoW == 0 && item.X == StartPos.X) - { - return false; - } - - if (info.CanGoN == 0 && item.Y == StartPos.Y) - { - return false; - } - - if (info.CanGoNWS == 0 && item.X == StartPos.X && item.Y == StartPos.Y) - { - return false; - } - - if (info.Bottom == 0) - { - bool found = false; - - if (info.AdjUN != 0) - { - found = ValidatePlaceStructure - ( - foundationItem, - house, - house.GetMultiAt(item.X, item.Y + 1), - minZ, - maxZ, - (int) (CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_BOTTOM | CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_N) - ); - } - - if (!found && info.AdjUE != 0) - { - found = ValidatePlaceStructure - ( - foundationItem, - house, - house.GetMultiAt(item.X - 1, item.Y), - minZ, - maxZ, - (int) (CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_BOTTOM | CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_E) - ); - } - - if (!found && info.AdjUS != 0) - { - found = ValidatePlaceStructure - ( - foundationItem, - house, - house.GetMultiAt(item.X, item.Y - 1), - minZ, - maxZ, - (int) (CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_BOTTOM | CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_S) - ); - } - - if (!found && info.AdjUW != 0) - { - found = ValidatePlaceStructure - ( - foundationItem, - house, - house.GetMultiAt(item.X + 1, item.Y), - minZ, - maxZ, - (int) (CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_BOTTOM | CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_W) - ); - } - - if (!found) - { - return false; - } - } - - if (info.Top == 0) - { - bool found = false; - - if (info.AdjLN != 0) - { - found = ValidatePlaceStructure - ( - foundationItem, - house, - house.GetMultiAt(item.X, item.Y + 1), - minZ, - maxZ, - (int) (CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_TOP | CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_N) - ); - } - - if (!found && info.AdjLE != 0) - { - found = ValidatePlaceStructure - ( - foundationItem, - house, - house.GetMultiAt(item.X - 1, item.Y), - minZ, - maxZ, - (int) (CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_TOP | CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_E) - ); - } - - if (!found && info.AdjLS != 0) - { - found = ValidatePlaceStructure - ( - foundationItem, - house, - house.GetMultiAt(item.X, item.Y - 1), - minZ, - maxZ, - (int) (CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_TOP | CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_S) - ); - } - - if (!found && info.AdjLW != 0) - { - found = ValidatePlaceStructure - ( - foundationItem, - house, - house.GetMultiAt(item.X + 1, item.Y), - minZ, - maxZ, - (int) (CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_TOP | CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_W) - ); - } - - if (!found) - { - return false; - } - } - } - - return true; - } - - public bool ValidatePlaceStructure - ( - Item foundationItem, - House house, - IEnumerable multi, - int minZ, - int maxZ, - int flags - ) - { - if (house == null) - { - return false; - } - - - foreach (Multi item in multi) - { - List validatedFloors = new List(); - - if (item.IsCustom && (item.State & (CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FLOOR | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_STAIR | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_ROOF | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_FIXTURE)) == 0 && item.Z >= minZ && item.Z < maxZ) - { - (int info1, int info2) = SeekGraphicInCustomHouseObjectList(ObjectsInfo, item.Graphic); - - if (info1 != -1 && info2 != -1) - { - CustomHousePlaceInfo info = ObjectsInfo[info1]; - - if ((flags & (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_DIRECT_SUPPORT) != 0) - { - if ((item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_INCORRECT_PLACE) != 0 || info.DirectSupports == 0) - { - continue; - } - - if ((flags & (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_CANGO_W) != 0) - { - if (info.CanGoW != 0) - { - return true; - } - } - else if ((flags & (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_CANGO_N) != 0) - { - if (info.CanGoN != 0) - { - return true; - } - } - else - { - return true; - } - } - else if ((flags & (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_BOTTOM) != 0 && info.Bottom != 0 || (flags & (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_TOP) != 0 && info.Top != 0) - { - if ((item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE) == 0) - { - item.State |= CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE; - - if (!ValidateItemPlace - ( - foundationItem, - item, - minZ, - maxZ, - validatedFloors - )) - { - item.State = item.State | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_INCORRECT_PLACE; - } - else - { - item.State = item.State | CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_VALIDATED_PLACE; - } - } - - if ((item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_INCORRECT_PLACE) == 0) - { - if ((flags & (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_BOTTOM) != 0) - { - if ((flags & (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_N) != 0 && info.AdjUN != 0) - { - return true; - } - - if ((flags & (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_E) != 0 && info.AdjUE != 0) - { - return true; - } - - if ((flags & (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_S) != 0 && info.AdjUS != 0) - { - return true; - } - - if ((flags & (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_W) != 0 && info.AdjUW != 0) - { - return true; - } - } - else - { - if ((flags & (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_N) != 0 && info.AdjLN != 0) - { - return true; - } - - if ((flags & (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_E) != 0 && info.AdjLE != 0) - { - return true; - } - - if ((flags & (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_S) != 0 && info.AdjLS != 0) - { - return true; - } - - if ((flags & (int) CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS.CHVCF_W) != 0 && info.AdjLW != 0) - { - return true; - } - } - } - } - } - } - } - - return false; - } - - private static void ParseFile(List list, string path) where T : CustomHouseObject, new() - { - FileInfo file = new FileInfo(path); - - if (!file.Exists) - { - return; - } - - using (StreamReader reader = File.OpenText(file.FullName)) - { - while (!reader.EndOfStream) - { - string line = reader.ReadLine(); - - if (string.IsNullOrWhiteSpace(line)) - { - continue; - } - - T item = new T(); - - if (item.Parse(line)) - { - if (item.FeatureMask == 0 || ((int) World.ClientLockedFeatures.Flags & item.FeatureMask) != 0) - { - list.Add(item); - } - } - } - } - } - - private static void ParseFileWithCategory(List list, string path) where T : CustomHouseObject, new() where U : CustomHouseObjectCategory, new() - { - FileInfo file = new FileInfo(path); - - if (!file.Exists) - { - return; - } - - using (StreamReader reader = File.OpenText(file.FullName)) - { - while (!reader.EndOfStream) - { - string line = reader.ReadLine(); - - if (string.IsNullOrWhiteSpace(line)) - { - continue; - } - - T item = new T(); - - if (item.Parse(line)) - { - if (item.FeatureMask != 0 && ((int) World.ClientLockedFeatures.Flags & item.FeatureMask) == 0) - { - continue; - } - - bool found = false; - - foreach (U c in list) - { - if (c.Index == item.Category) - { - c.Items.Add(item); - found = true; - - break; - } - } - - - if (!found) - { - U c = new U - { - Index = item.Category - }; - - c.Items.Add(item); - list.Add(c); - } - } - } - } - } - - - private static (int, int) SeekGraphicInCustomHouseObjectListWithCategory(List list, ushort graphic) where T : CustomHouseObject where U : CustomHouseObjectCategory - { - for (int i = 0; i < list.Count; i++) - { - U c = list[i]; - - for (int j = 0; j < c.Items.Count; j++) - { - int contains = c.Items[j].Contains(graphic); - - if (contains != -1) - { - return (i, j); - } - } - } - - return (-1, -1); - } - - private static (int, int) SeekGraphicInCustomHouseObjectList(List list, ushort graphic) where T : CustomHouseObject - { - for (int i = 0; i < list.Count; i++) - { - int contains = list[i].Contains(graphic); - - if (contains != -1) - { - return (i, graphic); - } - } - - return (-1, -1); - } - } - - public enum CUSTOM_HOUSE_GUMP_STATE - { - CHGS_WALL = 0, - CHGS_DOOR, - CHGS_FLOOR, - CHGS_STAIR, - CHGS_ROOF, - CHGS_MISC, - CHGS_MENU, - CHGS_FIXTURE - } - - public enum CUSTOM_HOUSE_FLOOR_VISION_STATE - { - CHGVS_NORMAL = 0, - CHGVS_TRANSPARENT_CONTENT, - CHGVS_HIDE_CONTENT, - CHGVS_TRANSPARENT_FLOOR, - CHGVS_HIDE_FLOOR, - CHGVS_TRANSLUCENT_FLOOR, - CHGVS_HIDE_ALL - } - - public enum CUSTOM_HOUSE_BUILD_TYPE - { - CHBT_NORMAL = 0, - CHBT_ROOF, - CHBT_FLOOR, - CHBT_STAIR - } - - [Flags] - public enum CUSTOM_HOUSE_MULTI_OBJECT_FLAGS - { - CHMOF_GENERIC_INTERNAL = 0x01, - CHMOF_FLOOR = 0x02, - CHMOF_STAIR = 0x04, - CHMOF_ROOF = 0x08, - CHMOF_FIXTURE = 0x10, - CHMOF_TRANSPARENT = 0x20, - CHMOF_IGNORE_IN_RENDER = 0x40, - CHMOF_VALIDATED_PLACE = 0x80, - CHMOF_INCORRECT_PLACE = 0x100, - - CHMOF_DONT_REMOVE = 0x200, - CHMOF_PREVIEW = 0x400 - } - - [Flags] - public enum CUSTOM_HOUSE_VALIDATE_CHECK_FLAGS - { - CHVCF_TOP = 0x01, - CHVCF_BOTTOM = 0x02, - CHVCF_N = 0x04, - CHVCF_E = 0x08, - CHVCF_S = 0x10, - CHVCF_W = 0x20, - CHVCF_DIRECT_SUPPORT = 0x40, - CHVCF_CANGO_W = 0x80, - CHVCF_CANGO_N = 0x100 - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/HouseManager.cs b/src/ClassicUO.Client/Game/Managers/HouseManager.cs deleted file mode 100644 index 0fe610f1a..000000000 --- a/src/ClassicUO.Client/Game/Managers/HouseManager.cs +++ /dev/null @@ -1,162 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Game.GameObjects; - -namespace ClassicUO.Game.Managers -{ - public class HouseManager - { - private readonly Dictionary _houses = new Dictionary(); - - public IReadOnlyCollection Houses => _houses.Values; - - public void Add(uint serial, House revision) - { - _houses[serial] = revision; - } - - public bool TryGetHouse(uint serial, out House house) - { - return _houses.TryGetValue(serial, out house); - } - - public bool TryToRemove(uint serial, int distance) - { - if (!IsHouseInRange(serial, distance)) - { - if (_houses.TryGetValue(serial, out House house)) - { - house.ClearComponents(); - _houses.Remove(serial); - } - - - return true; - } - - return false; - } - - public bool IsHouseInRange(uint serial, int distance) - { - if (TryGetHouse(serial, out _)) - { - int currX = World.RangeSize.X; - int currY = World.RangeSize.Y; - - //if (World.Player.IsMoving) - //{ - // Mobile.Step step = World.Player.Steps.Back(); - - // currX = step.X; - // currY = step.Y; - //} - //else - //{ - // currX = World.Player.X; - // currY = World.Player.Y; - //} - - Item found = World.Items.Get(serial); - - if (found == null) - { - return true; - } - - distance += found.MultiDistanceBonus; - - return Math.Abs(found.X - currX) <= distance && Math.Abs(found.Y - currY) <= distance; - } - - return false; - } - - public bool EntityIntoHouse(uint house, GameObject obj) - { - if (obj != null && TryGetHouse(house, out _)) - { - Item found = World.Items.Get(house); - - if (found == null || !found.MultiInfo.HasValue) - { - return true; - } - - int minX = found.X + found.MultiInfo.Value.X; - int maxX = found.X + found.MultiInfo.Value.Width; - int minY = found.Y + found.MultiInfo.Value.Y; - int maxY = found.Y + found.MultiInfo.Value.Height; - - return obj.X >= minX && obj.X <= maxX && obj.Y >= minY && obj.Y <= maxY; - } - - return false; - } - - public void Remove(uint serial) - { - if (TryGetHouse(serial, out House house)) - { - house.ClearComponents(); - _houses.Remove(serial); - } - } - - public void RemoveMultiTargetHouse() - { - if (_houses.TryGetValue(0, out House house)) - { - house.ClearComponents(); - _houses.Remove(0); - } - } - - public bool Exists(uint serial) - { - return _houses.ContainsKey(serial); - } - - public void Clear() - { - foreach (KeyValuePair house in _houses) - { - house.Value.ClearComponents(); - } - - _houses.Clear(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/IgnoreManager.cs b/src/ClassicUO.Client/Game/Managers/IgnoreManager.cs deleted file mode 100644 index 07aa4b23f..000000000 --- a/src/ClassicUO.Client/Game/Managers/IgnoreManager.cs +++ /dev/null @@ -1,140 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Xml; -using ClassicUO.Configuration; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Resources; -using ClassicUO.Utility.Logging; - -namespace ClassicUO.Game.Managers -{ - public static class IgnoreManager - { - /// - /// Set of Char names - /// - public static HashSet IgnoredCharsList = new HashSet(); - - /// - /// Initialize Ignore Manager - /// - Load List from XML file - /// - public static void Initialize() - { - ReadIgnoreList(); - } - - /// - /// Add Char to ignored list - /// - /// Targeted Entity - public static void AddIgnoredTarget(Entity entity) - { - if (entity is Mobile m && !m.IsYellowHits && m.Serial != World.Player.Serial) - { - var charName = m.Name; - - if (IgnoredCharsList.Contains(charName)) - { - GameActions.Print(string.Format(ResGumps.AddToIgnoreListExist, charName)); - return; - } - - IgnoredCharsList.Add(charName); - // Redraw list of chars - UIManager.GetGump()?.Redraw(); - - GameActions.Print(string.Format(ResGumps.AddToIgnoreListSuccess, charName)); - return; - } - - GameActions.Print(string.Format(ResGumps.AddToIgnoreListNotMobile)); - } - - /// - /// Remove Char from Ignored List - /// - /// Char name - public static void RemoveIgnoredTarget(string charName) - { - if (IgnoredCharsList.Contains(charName)) - IgnoredCharsList.Remove(charName); - } - - /// - /// Load Ignored List from XML file - /// - private static void ReadIgnoreList() - { - HashSet list = new HashSet(); - - string ignoreXmlPath = Path.Combine(ProfileManager.ProfilePath, "ignore_list.xml"); - - if (!File.Exists(ignoreXmlPath)) - { - return; - } - - XmlDocument doc = new XmlDocument(); - - try - { - doc.Load(ignoreXmlPath); - } - catch (Exception ex) - { - Log.Error(ex.ToString()); - } - - XmlElement root = doc["ignore"]; - - if (root != null) - { - foreach (XmlElement xml in root.ChildNodes) - { - if (xml.Name != "info") - { - continue; - } - - string charName = xml.GetAttribute("charname"); - list.Add(charName); - } - } - - IgnoredCharsList = list; - } - - /// - /// Save List to XML File - /// - public static void SaveIgnoreList() - { - string ignoreXmlPath = Path.Combine(ProfileManager.ProfilePath, "ignore_list.xml"); - - using (XmlTextWriter xml = new XmlTextWriter(ignoreXmlPath, Encoding.UTF8) - { - Formatting = Formatting.Indented, - IndentChar = '\t', - Indentation = 1 - }) - { - xml.WriteStartDocument(true); - xml.WriteStartElement("ignore"); - - foreach (var ch in IgnoredCharsList) - { - xml.WriteStartElement("info"); - xml.WriteAttributeString("charname", ch); - xml.WriteEndElement(); - } - - xml.WriteEndElement(); - xml.WriteEndDocument(); - } - } - } -} diff --git a/src/ClassicUO.Client/Game/Managers/InfoBarManager.cs b/src/ClassicUO.Client/Game/Managers/InfoBarManager.cs deleted file mode 100644 index 839e0262e..000000000 --- a/src/ClassicUO.Client/Game/Managers/InfoBarManager.cs +++ /dev/null @@ -1,252 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Xml; -using ClassicUO.Configuration; -using ClassicUO.Resources; -using ClassicUO.Utility.Logging; - -namespace ClassicUO.Game.Managers -{ - internal class InfoBarManager - { - private readonly List infoBarItems; - - public InfoBarManager() - { - infoBarItems = new List(); - } - - public List GetInfoBars() - { - return infoBarItems; - } - - public static string[] GetVars() - { - if (!CUOEnviroment.IsOutlands) - { - return Enum.GetNames(typeof(InfoBarVars)); - } - - return Enum.GetNames(typeof(InfoBarVarsOutlands)); - } - - public void AddItem(InfoBarItem ibi) - { - infoBarItems.Add(ibi); - } - - public void RemoveItem(InfoBarItem item) - { - infoBarItems.Remove(item); - } - - public void Clear() - { - infoBarItems.Clear(); - } - - public void Save() - { - string path = Path.Combine(ProfileManager.ProfilePath, "infobar.xml"); - - using (XmlTextWriter xml = new XmlTextWriter(path, Encoding.UTF8) - { - Formatting = Formatting.Indented, - IndentChar = '\t', - Indentation = 1 - }) - { - xml.WriteStartDocument(true); - xml.WriteStartElement("infos"); - - foreach (InfoBarItem info in infoBarItems) - { - info.Save(xml); - } - - xml.WriteEndElement(); - xml.WriteEndDocument(); - } - } - - public void Load() - { - string path = Path.Combine(ProfileManager.ProfilePath, "infobar.xml"); - - if (!File.Exists(path)) - { - CreateDefault(); - Save(); - - return; - } - - XmlDocument doc = new XmlDocument(); - - try - { - doc.Load(path); - } - catch (Exception ex) - { - Log.Error(ex.ToString()); - - return; - } - - infoBarItems.Clear(); - - XmlElement root = doc["infos"]; - - if (root != null) - { - foreach (XmlElement xml in root.GetElementsByTagName("info")) - { - InfoBarItem item = new InfoBarItem(xml); - infoBarItems.Add(item); - } - } - } - - public void CreateDefault() - { - infoBarItems.Clear(); - - infoBarItems.Add(new InfoBarItem("", InfoBarVars.NameNotoriety, 0x3D2)); - infoBarItems.Add(new InfoBarItem(ResGeneral.Hits, InfoBarVars.HP, 0x1B6)); - infoBarItems.Add(new InfoBarItem(ResGeneral.Mana, InfoBarVars.Mana, 0x1ED)); - infoBarItems.Add(new InfoBarItem(ResGeneral.Stam, InfoBarVars.Stamina, 0x22E)); - infoBarItems.Add(new InfoBarItem(ResGeneral.Weight, InfoBarVars.Weight, 0x3D2)); - } - } - - internal enum InfoBarVars - { - HP = 0, - Mana, - Stamina, - Weight, - Followers, - Gold, - Damage, - Armor, - Luck, - FireResist, - ColdResist, - PoisonResist, - EnergyResist, - LowerReagentCost, - SpellDamageInc, - FasterCasting, - FasterCastRecovery, - HitChanceInc, - DefenseChanceInc, - LowerManaCost, - DamageChanceInc, - SwingSpeedInc, - StatsCap, - NameNotoriety, - TithingPoints - } - - internal enum InfoBarVarsOutlands - { - HP = 0, - Mana, - Stamina, - Weight, - Followers, - Gold, - Damage, - Armor, - FoodSatisfaction, - MurderTimer, - CriminalTimer, - PvpCooldown, - BandageTimer, - LowerReagentCost, - SpellDamageInc, - FasterCasting, - FasterCastRecovery, - HitChanceInc, - DefenseChanceInc, - LowerManaCost, - DamageChanceInc, - SwingSpeedInc, - MurderCount, - NameNotoriety, - TithingPoints - } - - internal class InfoBarItem - { - public InfoBarItem(string label, InfoBarVars var, ushort labelColor) - { - this.label = label; - this.var = var; - hue = labelColor; - } - - - public InfoBarItem(XmlElement xml) - { - if (xml == null) - { - return; - } - - label = xml.GetAttribute("text"); - var = (InfoBarVars) int.Parse(xml.GetAttribute("var")); - hue = ushort.Parse(xml.GetAttribute("hue")); - } - - public ushort hue; - - public string label; - public InfoBarVars var; - - public void Save(XmlTextWriter writer) - { - writer.WriteStartElement("info"); - writer.WriteAttributeString("text", label); - writer.WriteAttributeString("var", ((int) var).ToString()); - writer.WriteAttributeString("hue", hue.ToString()); - writer.WriteEndElement(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/JournalManager.cs b/src/ClassicUO.Client/Game/Managers/JournalManager.cs deleted file mode 100644 index c835ce47f..000000000 --- a/src/ClassicUO.Client/Game/Managers/JournalManager.cs +++ /dev/null @@ -1,161 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.IO; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Utility; -using ClassicUO.Utility.Collections; -using ClassicUO.Utility.Logging; - -namespace ClassicUO.Game.Managers -{ - public class JournalManager - { - private StreamWriter _fileWriter; - private bool _writerHasException; - - public static Deque Entries { get; } = new Deque(Constants.MAX_JOURNAL_HISTORY_COUNT); - - public void Add(string text, ushort hue, string name, TextType type, bool isunicode = true, MessageType messageType = MessageType.Regular) - { - JournalEntry entry = Entries.Count >= Constants.MAX_JOURNAL_HISTORY_COUNT ? Entries.RemoveFromFront() : new JournalEntry(); - - byte font = (byte) (isunicode ? 0 : 9); - - if (ProfileManager.CurrentProfile != null && ProfileManager.CurrentProfile.OverrideAllFonts) - { - font = ProfileManager.CurrentProfile.ChatFont; - isunicode = ProfileManager.CurrentProfile.OverrideAllFontsIsUnicode; - } - - DateTime timeNow = DateTime.Now; - - entry.Text = text; - entry.Font = font; - entry.Hue = hue; - entry.Name = name; - entry.IsUnicode = isunicode; - entry.Time = timeNow; - entry.TextType = type; - entry.MessageType = messageType; - - if (ProfileManager.CurrentProfile != null && ProfileManager.CurrentProfile.ForceUnicodeJournal) - { - entry.Font = 0; - entry.IsUnicode = true; - } - - Entries.AddToBack(entry); - EventSink.InvokeJournalEntryAdded(null, entry); - - if (_fileWriter == null && !_writerHasException) - { - CreateWriter(); - } - - string output = $"[{timeNow:G}] {name}: {text}"; - - if (string.IsNullOrWhiteSpace(name)) - { - output = $"[{timeNow:G}] {text}"; - } - - _fileWriter?.WriteLine(output); - } - - private void CreateWriter() - { - if (_fileWriter == null && ProfileManager.CurrentProfile != null && ProfileManager.CurrentProfile.SaveJournalToFile) - { - try - { - string path = FileSystemHelper.CreateFolderIfNotExists(Path.Combine(CUOEnviroment.ExecutablePath, "Data"), "Client", "JournalLogs"); - - _fileWriter = new StreamWriter(File.Open(Path.Combine(path, $"{DateTime.Now:yyyy_MM_dd_HH_mm_ss}_journal.txt"), FileMode.Create, FileAccess.Write, FileShare.Read)) - { - AutoFlush = true - }; - - try - { - string[] files = Directory.GetFiles(path, "*_journal.txt"); - Array.Sort(files); - Array.Reverse(files); - - for (int i = files.Length - 1; i >= 100; --i) - { - File.Delete(files[i]); - } - } - catch - { - } - } - catch (Exception ex) - { - Log.Error(ex.ToString()); - // we don't want to wast time. - _writerHasException = true; - } - } - } - - public void CloseWriter() - { - _fileWriter?.Flush(); - _fileWriter?.Dispose(); - _fileWriter = null; - } - - public void Clear() - { - //Entries.Clear(); - CloseWriter(); - } - } - - public class JournalEntry - { - public byte Font; - public ushort Hue; - - public bool IsUnicode; - public string Name; - public string Text; - - public TextType TextType; - public DateTime Time; - public MessageType MessageType; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/LastCharacterManager.cs b/src/ClassicUO.Client/Game/Managers/LastCharacterManager.cs deleted file mode 100644 index 94270bbd0..000000000 --- a/src/ClassicUO.Client/Game/Managers/LastCharacterManager.cs +++ /dev/null @@ -1,135 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Xml; -using ClassicUO.Configuration; -using ClassicUO.Game.Scenes; -using ClassicUO.Resources; -using ClassicUO.Utility.Logging; - -namespace ClassicUO.Game.Managers -{ - [JsonSerializable(typeof(LastCharacterInfo))] - [JsonSerializable(typeof(List))] - sealed partial class LastCharacterJsonContext : JsonSerializerContext { } - - public static class LastCharacterManager - { - private static readonly string _lastCharacterFilePath = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Profiles"); - private static readonly string _lastCharacterFile = Path.Combine(_lastCharacterFilePath, "lastcharacter.json"); - - private static List LastCharacters { get; set; } - - private static string LastCharacterNameOverride { get; set; } - - public static void Load() - { - LastCharacters = new List(); - - if (!File.Exists(_lastCharacterFile)) - { - ConfigurationResolver.Save(LastCharacters, _lastCharacterFile, LastCharacterJsonContext.Default); - } - - LastCharacters = ConfigurationResolver.Load>(_lastCharacterFile, LastCharacterJsonContext.Default); - - // safety check - if (LastCharacters == null) - { - LastCharacters = new List(); - } - } - - public static void Save(string account, string server, string name) - { - LastCharacterInfo lastChar = LastCharacters.FirstOrDefault(c => c.AccountName.Equals(account) && c.ServerName == server); - - // Check to see if they passed in -lastcharactername but picked another character, clear override then - if (!string.IsNullOrEmpty(LastCharacterNameOverride) && !LastCharacterNameOverride.Equals(name)) - { - LastCharacterNameOverride = string.Empty; - } - - if (lastChar != null) - { - lastChar.LastCharacterName = name; - } - else - { - LastCharacters.Add(new LastCharacterInfo - { - ServerName = server, - LastCharacterName = name, - AccountName = account - }); - } - - ConfigurationResolver.Save(LastCharacters, _lastCharacterFile, LastCharacterJsonContext.Default); - } - - public static string GetLastCharacter(string account, string server) - { - if (LastCharacters == null) - { - Load(); - } - - // If they passed in a -lastcharactername param, ignore json value, use that value instead - if (!string.IsNullOrEmpty(LastCharacterNameOverride)) - { - return LastCharacterNameOverride; - } - - LastCharacterInfo lastChar = LastCharacters.FirstOrDefault(c => c.AccountName.Equals(account) && c.ServerName == server); - - return lastChar != null ? lastChar.LastCharacterName : string.Empty; - } - - public static void OverrideLastCharacter(string name) - { - LastCharacterNameOverride = name; - } - } - - public class LastCharacterInfo - { - public string AccountName { get; set; } - public string ServerName { get; set; } - public string LastCharacterName { get; set; } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/MacroManager.cs b/src/ClassicUO.Client/Game/Managers/MacroManager.cs deleted file mode 100644 index 4339ddc9e..000000000 --- a/src/ClassicUO.Client/Game/Managers/MacroManager.cs +++ /dev/null @@ -1,2726 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Network; -using ClassicUO.Resources; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using SDL2; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml; -using static SDL2.SDL; - -namespace ClassicUO.Game.Managers -{ - public class MacroManager : LinkedObject - { - public static readonly string[] MacroNames = Enum.GetNames(typeof(MacroType)); - private readonly uint[] _itemsInHand = new uint[2]; - private MacroObject _lastMacro; - private long _nextTimer; - - private readonly byte[] _skillTable = - { - 1, 2, 35, 4, 6, 12, - 14, 15, 16, 19, 21, 56 /*imbuing*/, - 23, 3, 46, 9, 30, 22, - 48, 32, 33, 47, 36, 38 - }; - - private readonly int[] _spellsCountTable = - { - Constants.SPELLBOOK_1_SPELLS_COUNT, - Constants.SPELLBOOK_2_SPELLS_COUNT, - Constants.SPELLBOOK_3_SPELLS_COUNT, - Constants.SPELLBOOK_4_SPELLS_COUNT, - Constants.SPELLBOOK_5_SPELLS_COUNT, - Constants.SPELLBOOK_6_SPELLS_COUNT, - Constants.SPELLBOOK_7_SPELLS_COUNT - }; - - - public long WaitForTargetTimer { get; set; } - - public bool WaitingBandageTarget { get; set; } - - public static MacroManager TryGetMacroManager() - { - return Client.Game.GetScene().Macros; - } - - public void Load() - { - string path = Path.Combine(ProfileManager.ProfilePath, "macros.xml"); - - if (!File.Exists(path)) - { - Log.Trace("No macros.xml file. Creating a default file."); - - Clear(); - CreateDefaultMacros(); - Save(); - - return; - } - - XmlDocument doc = new XmlDocument(); - - try - { - doc.Load(path); - } - catch (Exception ex) - { - Log.Error(ex.ToString()); - - return; - } - - - Clear(); - - XmlElement root = doc["macros"]; - - if (root != null) - { - foreach (XmlElement xml in root.GetElementsByTagName("macro")) - { - Macro macro = new Macro(xml.GetAttribute("name")); - macro.Load(xml); - PushToBack(macro); - } - } - } - - public void Save() - { - List list = GetAllMacros(); - - string path = Path.Combine(ProfileManager.ProfilePath, "macros.xml"); - - using (XmlTextWriter xml = new XmlTextWriter(path, Encoding.UTF8) - { - Formatting = Formatting.Indented, - IndentChar = '\t', - Indentation = 1 - }) - { - xml.WriteStartDocument(true); - xml.WriteStartElement("macros"); - - foreach (Macro macro in list) - { - macro.Save(xml); - } - - xml.WriteEndElement(); - xml.WriteEndDocument(); - } - } - - private void CreateDefaultMacros() - { - PushToBack - ( - new Macro - ( - ResGeneral.Paperdoll, - (SDL.SDL_Keycode)112, - true, - false, - false - ) - { - Items = new MacroObject((MacroType)8, (MacroSubType)10) - { - SubMenuType = 1 - } - } - ); - - PushToBack - ( - new Macro - ( - ResGeneral.Options, - (SDL.SDL_Keycode)111, - true, - false, - false - ) - { - Items = new MacroObject((MacroType)8, (MacroSubType)9) - { - SubMenuType = 1 - } - } - ); - - PushToBack - ( - new Macro - ( - ResGeneral.Journal, - (SDL.SDL_Keycode)106, - true, - false, - false - ) - { - Items = new MacroObject((MacroType)8, (MacroSubType)12) - { - SubMenuType = 1 - } - } - ); - - PushToBack - ( - new Macro - ( - ResGeneral.Backpack, - (SDL.SDL_Keycode)105, - true, - false, - false - ) - { - Items = new MacroObject((MacroType)8, (MacroSubType)16) - { - SubMenuType = 1 - } - } - ); - - PushToBack - ( - new Macro - ( - ResGeneral.Radar, - (SDL.SDL_Keycode)114, - true, - false, - false - ) - { - Items = new MacroObject((MacroType)8, (MacroSubType)17) - { - SubMenuType = 1 - } - } - ); - - PushToBack - ( - new Macro - ( - ResGeneral.Bow, - (SDL.SDL_Keycode)98, - false, - true, - false - ) - { - Items = new MacroObject((MacroType)18, 0) - { - SubMenuType = 0 - } - } - ); - - PushToBack - ( - new Macro - ( - ResGeneral.Salute, - (SDL.SDL_Keycode)115, - false, - true, - false - ) - { - Items = new MacroObject((MacroType)19, 0) - { - SubMenuType = 0 - } - } - ); - } - - - public List GetAllMacros() - { - Macro m = (Macro)Items; - - while (m?.Previous != null) - { - m = (Macro)m.Previous; - } - - List macros = new List(); - - while (true) - { - if (m != null) - { - macros.Add(m); - } - else - { - break; - } - - m = (Macro)m.Next; - } - - return macros; - } - - public Macro FindMacro(SDL_GameControllerButton button) - { - Macro obj = (Macro)Items; - - while (obj != null) - { - if (obj.ControllerButtons != null) - { - if (obj.ControllerButtons.Length > 1) - { - if (Controller.AreButtonsPressed(obj.ControllerButtons)) - { - break; - } - } - else if (obj.ControllerButtons.Contains(button)) - { - break; - } - } - - obj = (Macro)obj.Next; - } - - return obj; - } - - public Macro FindMacro(SDL.SDL_Keycode key, bool alt, bool ctrl, bool shift) - { - Macro obj = (Macro)Items; - - while (obj != null) - { - if (obj.Key == key && obj.Alt == alt && obj.Ctrl == ctrl && obj.Shift == shift) - { - break; - } - - obj = (Macro)obj.Next; - } - - return obj; - } - - public Macro FindMacro(MouseButtonType button, bool alt, bool ctrl, bool shift) - { - Macro obj = (Macro)Items; - - while (obj != null) - { - if (obj.MouseButton == button && obj.Alt == alt && obj.Ctrl == ctrl && obj.Shift == shift) - { - break; - } - - obj = (Macro)obj.Next; - } - - return obj; - } - - public Macro FindMacro(bool wheelUp, bool alt, bool ctrl, bool shift) - { - Macro obj = (Macro)Items; - - while (obj != null) - { - if (obj.WheelScroll == true && obj.WheelUp == wheelUp && obj.Alt == alt && obj.Ctrl == ctrl && obj.Shift == shift) - { - break; - } - - obj = (Macro)obj.Next; - } - - return obj; - } - - public Macro FindMacro(string name) - { - Macro obj = (Macro)Items; - - while (obj != null) - { - if (obj.Name == name) - { - break; - } - - obj = (Macro)obj.Next; - } - - return obj; - } - - public void SetMacroToExecute(MacroObject macro) - { - _lastMacro = macro; - } - - public void Update() - { - while (_lastMacro != null) - { - switch (Process()) - { - case 2: - _lastMacro = null; - - break; - - case 1: return; - - case 0: - _lastMacro = (MacroObject)_lastMacro?.Next; - - break; - } - } - } - - private int Process() - { - int result; - - if (_lastMacro == null) // MRC_STOP - { - result = 2; - } - else if (_nextTimer <= Time.Ticks) - { - result = Process(_lastMacro); - } - else // MRC_BREAK_PARSER - { - result = 1; - } - - return result; - } - - private int Process(MacroObject macro) - { - if (macro == null) - { - return 0; - } - - int result = 0; - - switch (macro.Code) - { - case MacroType.Say: - case MacroType.Emote: - case MacroType.Whisper: - case MacroType.Yell: - case MacroType.RazorMacro: - - string text = ((MacroObjectString)macro).Text; - - if (!string.IsNullOrEmpty(text)) - { - MessageType type = MessageType.Regular; - ushort hue = ProfileManager.CurrentProfile.SpeechHue; - - switch (macro.Code) - { - case MacroType.Emote: - text = ResGeneral.EmoteChar + text + ResGeneral.EmoteChar; - type = MessageType.Emote; - hue = ProfileManager.CurrentProfile.EmoteHue; - - break; - - case MacroType.Whisper: - type = MessageType.Whisper; - hue = ProfileManager.CurrentProfile.WhisperHue; - - break; - - case MacroType.Yell: - type = MessageType.Yell; - - break; - - case MacroType.RazorMacro: - text = ">macro " + text; - - break; - } - - GameActions.Say(text, hue, type); - } - - break; - - case MacroType.Walk: - byte dt = (byte)Direction.Up; - - if (macro.SubCode != MacroSubType.NW) - { - dt = (byte)(macro.SubCode - 2); - - if (dt > 7) - { - dt = 0; - } - } - - if (!Pathfinder.AutoWalking) - { - World.Player.Walk((Direction)dt, false); - } - - break; - - case MacroType.WarPeace: - GameActions.ToggleWarMode(); - - break; - - case MacroType.Paste: - string txt = StringHelper.GetClipboardText(true); - - if (txt != null) - { - UIManager.SystemChat.TextBoxControl.AppendText(txt); - } - - break; - - case MacroType.Open: - case MacroType.Close: - case MacroType.Minimize: - case MacroType.Maximize: - - switch (macro.Code) - { - case MacroType.Open: - - switch (macro.SubCode) - { - case MacroSubType.Configuration: - GameActions.OpenSettings(); - - break; - - case MacroSubType.Paperdoll: - GameActions.OpenPaperdoll(World.Player); - - break; - - case MacroSubType.Status: - GameActions.OpenStatusBar(); - - break; - - case MacroSubType.Journal: - GameActions.OpenJournal(); - - break; - - case MacroSubType.Skills: - GameActions.OpenSkills(); - - break; - - case MacroSubType.MageSpellbook: - case MacroSubType.NecroSpellbook: - case MacroSubType.PaladinSpellbook: - case MacroSubType.BushidoSpellbook: - case MacroSubType.NinjitsuSpellbook: - case MacroSubType.SpellWeavingSpellbook: - case MacroSubType.MysticismSpellbook: - - SpellBookType type = SpellBookType.Magery; - - switch (macro.SubCode) - { - case MacroSubType.NecroSpellbook: - type = SpellBookType.Necromancy; - - break; - - case MacroSubType.PaladinSpellbook: - type = SpellBookType.Chivalry; - - break; - - case MacroSubType.BushidoSpellbook: - type = SpellBookType.Bushido; - - break; - - case MacroSubType.NinjitsuSpellbook: - type = SpellBookType.Ninjitsu; - - break; - - case MacroSubType.SpellWeavingSpellbook: - type = SpellBookType.Spellweaving; - - break; - - case MacroSubType.MysticismSpellbook: - type = SpellBookType.Mysticism; - - break; - - case MacroSubType.BardSpellbook: - type = SpellBookType.Mastery; - - break; - } - - NetClient.Socket.Send_OpenSpellBook((byte)type); - - break; - - case MacroSubType.Chat: - GameActions.OpenChat(); - - break; - - case MacroSubType.Backpack: - GameActions.OpenBackpack(); - - break; - - case MacroSubType.Overview: - GameActions.OpenMiniMap(); - - break; - - case MacroSubType.WorldMap: - GameActions.OpenWorldMap(); - - break; - - case MacroSubType.Mail: - case MacroSubType.PartyManifest: - PartyGump party = UIManager.GetGump(); - - if (party == null) - { - int x = Client.Game.Window.ClientBounds.Width / 2 - 272; - int y = Client.Game.Window.ClientBounds.Height / 2 - 240; - UIManager.Add(new PartyGump(x, y, World.Party.CanLoot)); - } - else - { - party.BringOnTop(); - } - - break; - - case MacroSubType.Guild: - GameActions.OpenGuildGump(); - - break; - - case MacroSubType.QuestLog: - GameActions.RequestQuestMenu(); - - break; - - case MacroSubType.PartyChat: - case MacroSubType.CombatBook: - case MacroSubType.RacialAbilitiesBook: - case MacroSubType.BardSpellbook: - Log.Warn($"Macro '{macro.SubCode}' not implemented"); - - break; - } - - break; - - case MacroType.Close: - case MacroType.Minimize: - case MacroType.Maximize: - - switch (macro.SubCode) - { - case MacroSubType.WorldMap: - - if (macro.Code == MacroType.Close) - { - UIManager.GetGump()?.Dispose(); - } - - break; - - case MacroSubType.Configuration: - - if (macro.Code == MacroType.Close) - { - UIManager.GetGump()?.Dispose(); - UIManager.GetGump()?.Dispose(); - } - - break; - - case MacroSubType.Paperdoll: - - PaperDollGump paperdoll = UIManager.GetGump(World.Player.Serial); - - if (paperdoll != null) - { - if (macro.Code == MacroType.Close) - { - paperdoll.Dispose(); - } - else if (macro.Code == MacroType.Minimize) - { - paperdoll.IsMinimized = true; - } - else if (macro.Code == MacroType.Maximize) - { - paperdoll.IsMinimized = false; - } - } - - break; - - case MacroSubType.Status: - - StatusGumpBase status = StatusGumpBase.GetStatusGump(); - - if (macro.Code == MacroType.Close) - { - if (status != null) - { - status.Dispose(); - } - else - { - UIManager.GetGump(World.Player)?.Dispose(); - } - } - else if (macro.Code == MacroType.Minimize) - { - if (status != null) - { - status.Dispose(); - - if (ProfileManager.CurrentProfile.CustomBarsToggled) - { - UIManager.Add(new HealthBarGumpCustom(World.Player) { X = status.ScreenCoordinateX, Y = status.ScreenCoordinateY }); - } - else - { - UIManager.Add(new HealthBarGump(World.Player) { X = status.ScreenCoordinateX, Y = status.ScreenCoordinateY }); - } - } - else - { - UIManager.GetGump(World.Player)?.BringOnTop(); - } - } - else if (macro.Code == MacroType.Maximize) - { - if (status != null) - { - status.BringOnTop(); - } - else - { - BaseHealthBarGump healthbar = UIManager.GetGump(World.Player); - - if (healthbar != null) - { - UIManager.Add(StatusGumpBase.AddStatusGump(healthbar.ScreenCoordinateX, healthbar.ScreenCoordinateY)); - } - } - } - - break; - - case MacroSubType.Journal: - - JournalGump journal = UIManager.GetGump(); - - if (journal != null) - { - if (macro.Code == MacroType.Close) - { - journal.Dispose(); - } - else if (macro.Code == MacroType.Minimize) - { - journal.IsMinimized = true; - } - else if (macro.Code == MacroType.Maximize) - { - journal.IsMinimized = false; - } - } - - break; - - case MacroSubType.Skills: - - if (ProfileManager.CurrentProfile.StandardSkillsGump) - { - StandardSkillsGump skillgump = UIManager.GetGump(); - - if (skillgump != null) - { - if (macro.Code == MacroType.Close) - { - skillgump.Dispose(); - } - else if (macro.Code == MacroType.Minimize) - { - skillgump.IsMinimized = true; - } - else if (macro.Code == MacroType.Maximize) - { - skillgump.IsMinimized = false; - } - } - } - else - { - if (macro.Code == MacroType.Close) - { - UIManager.GetGump()?.Dispose(); - } - } - - break; - - case MacroSubType.MageSpellbook: - case MacroSubType.NecroSpellbook: - case MacroSubType.PaladinSpellbook: - case MacroSubType.BushidoSpellbook: - case MacroSubType.NinjitsuSpellbook: - case MacroSubType.SpellWeavingSpellbook: - case MacroSubType.MysticismSpellbook: - - SpellbookGump spellbook = UIManager.GetGump(); - - if (spellbook != null) - { - if (macro.Code == MacroType.Close) - { - spellbook.Dispose(); - } - else if (macro.Code == MacroType.Minimize) - { - spellbook.IsMinimized = true; - } - else if (macro.Code == MacroType.Maximize) - { - spellbook.IsMinimized = false; - } - } - - break; - - case MacroSubType.Overview: - - if (macro.Code == MacroType.Close) - { - UIManager.GetGump()?.Dispose(); - } - else if (macro.Code == MacroType.Minimize) - { - UIManager.GetGump()?.ToggleSize(false); - } - else if (macro.Code == MacroType.Maximize) - { - UIManager.GetGump()?.ToggleSize(true); - } - - break; - - case MacroSubType.Backpack: - - Item backpack = World.Player.FindItemByLayer(Layer.Backpack); - - if (backpack != null) - { - ContainerGump backpackGump = UIManager.GetGump(backpack.Serial); - - if (backpackGump != null) - { - if (macro.Code == MacroType.Close) - { - backpackGump.Dispose(); - } - else if (macro.Code == MacroType.Minimize) - { - backpackGump.IsMinimized = true; - } - else if (macro.Code == MacroType.Maximize) - { - backpackGump.IsMinimized = false; - } - } - } - - break; - - case MacroSubType.Mail: - Log.Warn($"Macro '{macro.SubCode}' not implemented"); - - break; - - case MacroSubType.PartyManifest: - - if (macro.Code == MacroType.Close) - { - UIManager.GetGump()?.Dispose(); - } - - break; - - case MacroSubType.PartyChat: - case MacroSubType.CombatBook: - case MacroSubType.RacialAbilitiesBook: - case MacroSubType.BardSpellbook: - Log.Warn($"Macro '{macro.SubCode}' not implemented"); - - break; - } - - break; - } - - break; - - case MacroType.OpenDoor: - GameActions.OpenDoor(); - - break; - - case MacroType.UseSkill: - int skill = macro.SubCode - MacroSubType.Anatomy; - - if (skill >= 0 && skill < 24) - { - skill = _skillTable[skill]; - - if (skill != 0xFF) - { - GameActions.UseSkill(skill); - } - } - - break; - - case MacroType.LastSkill: - GameActions.UseSkill(GameActions.LastSkillIndex); - - break; - - case MacroType.CastSpell: - int spell = macro.SubCode - MacroSubType.Clumsy + 1; - - if (spell > 0 && spell <= 151) - { - int totalCount = 0; - int spellType; - - for (spellType = 0; spellType < 7; spellType++) - { - totalCount += _spellsCountTable[spellType]; - - if (spell <= totalCount) - { - break; - } - } - - if (spellType < 7) - { - spell -= totalCount - _spellsCountTable[spellType]; - spell += spellType * 100; - - if (spellType > 2) - { - spell += 100; - - // fix offset for mysticism - if (spellType == 6) - { - spell -= 23; - } - } - - GameActions.CastSpell(spell); - } - } - - break; - - case MacroType.LastSpell: - GameActions.CastSpell(GameActions.LastSpellIndex); - - break; - - case MacroType.Bow: - case MacroType.Salute: - int index = macro.Code - MacroType.Bow; - - const string BOW = "bow"; - const string SALUTE = "salute"; - - GameActions.EmoteAction(index == 0 ? BOW : SALUTE); - - break; - - case MacroType.QuitGame: - Client.Game.GetScene()?.RequestQuitGame(); - - break; - - case MacroType.AllNames: - GameActions.AllNames(); - - break; - - case MacroType.LastObject: - - if (World.Get(World.LastObject) != null) - { - GameActions.DoubleClick(World.LastObject); - } - - break; - - case MacroType.UseItemInHand: - Item itemInLeftHand = World.Player.FindItemByLayer(Layer.OneHanded); - - if (itemInLeftHand != null) - { - GameActions.DoubleClick(itemInLeftHand.Serial); - } - else - { - Item itemInRightHand = World.Player.FindItemByLayer(Layer.TwoHanded); - - if (itemInRightHand != null) - { - GameActions.DoubleClick(itemInRightHand.Serial); - } - } - - break; - - case MacroType.LastTarget: - - //if (WaitForTargetTimer == 0) - // WaitForTargetTimer = Time.Ticks + Constants.WAIT_FOR_TARGET_DELAY; - - if (TargetManager.IsTargeting) - { - //if (TargetManager.TargetingState != TargetType.Object) - //{ - // TargetManager.TargetGameObject(TargetManager.LastGameObject); - //} - //else - - if (TargetManager.TargetingState != CursorTarget.Object && !TargetManager.LastTargetInfo.IsEntity) - { - TargetManager.TargetLast(); - } - else if (TargetManager.LastTargetInfo.IsEntity) - { - TargetManager.Target(TargetManager.LastTargetInfo.Serial); - } - else - { - TargetManager.Target(TargetManager.LastTargetInfo.Graphic, TargetManager.LastTargetInfo.X, TargetManager.LastTargetInfo.Y, TargetManager.LastTargetInfo.Z); - } - - WaitForTargetTimer = 0; - } - else if (WaitForTargetTimer < Time.Ticks) - { - WaitForTargetTimer = 0; - } - else - { - result = 1; - } - - break; - - case MacroType.TargetSelf: - - //if (WaitForTargetTimer == 0) - // WaitForTargetTimer = Time.Ticks + Constants.WAIT_FOR_TARGET_DELAY; - - if (TargetManager.IsTargeting) - { - TargetManager.Target(World.Player); - WaitForTargetTimer = 0; - } - else if (WaitForTargetTimer < Time.Ticks) - { - WaitForTargetTimer = 0; - } - else - { - result = 1; - } - - break; - - case MacroType.ArmDisarm: - int handIndex = 1 - (macro.SubCode - MacroSubType.LeftHand); - GameScene gs = Client.Game.GetScene(); - - if (handIndex < 0 || handIndex > 1 || Client.Game.GameCursor.ItemHold.Enabled) - { - break; - } - - if (_itemsInHand[handIndex] != 0) - { - GameActions.PickUp(_itemsInHand[handIndex], 0, 0, 1); - GameActions.Equip(); - - _itemsInHand[handIndex] = 0; - _nextTimer = Time.Ticks + 1000; - } - else - { - Item backpack = World.Player.FindItemByLayer(Layer.Backpack); - - if (backpack == null) - { - break; - } - - Item item = World.Player.FindItemByLayer(Layer.OneHanded + (byte)handIndex); - - if (item != null) - { - _itemsInHand[handIndex] = item.Serial; - - GameActions.PickUp(item, 0, 0, 1); - - GameActions.DropItem - ( - Client.Game.GameCursor.ItemHold.Serial, - 0xFFFF, - 0xFFFF, - 0, - backpack.Serial - ); - - _nextTimer = Time.Ticks + 1000; - } - } - - break; - - case MacroType.WaitForTarget: - - if (WaitForTargetTimer == 0) - { - WaitForTargetTimer = Time.Ticks + Constants.WAIT_FOR_TARGET_DELAY; - } - - if (TargetManager.IsTargeting || WaitForTargetTimer < Time.Ticks) - { - WaitForTargetTimer = 0; - } - else - { - result = 1; - } - - break; - - case MacroType.TargetNext: - - uint sel_obj = World.FindNext(ScanTypeObject.Mobiles, TargetManager.LastTargetInfo.Serial, false); - - if (SerialHelper.IsValid(sel_obj)) - { - TargetManager.LastTargetInfo.SetEntity(sel_obj); - TargetManager.LastAttack = sel_obj; - } - - break; - - case MacroType.AttackLast: - if (TargetManager.LastTargetInfo.IsEntity) - { - GameActions.Attack(TargetManager.LastTargetInfo.Serial); - } - - break; - - case MacroType.Delay: - MacroObjectString mosss = (MacroObjectString)macro; - string str = mosss.Text; - - if (!string.IsNullOrEmpty(str) && int.TryParse(str, out int rr)) - { - _nextTimer = Time.Ticks + rr; - } - - break; - - case MacroType.CircleTrans: - ProfileManager.CurrentProfile.UseCircleOfTransparency = !ProfileManager.CurrentProfile.UseCircleOfTransparency; - - break; - - case MacroType.CloseGump: - - UIManager.Gumps.Where(s => !(s is TopBarGump) && !(s is BuffGump) && !(s is ImprovedBuffGump) && !(s is WorldViewportGump)).ToList().ForEach(s => s.Dispose()); - - break; - - case MacroType.AlwaysRun: - ProfileManager.CurrentProfile.AlwaysRun = !ProfileManager.CurrentProfile.AlwaysRun; - - GameActions.Print(ProfileManager.CurrentProfile.AlwaysRun ? ResGeneral.AlwaysRunIsNowOn : ResGeneral.AlwaysRunIsNowOff); - - break; - - case MacroType.SaveDesktop: - ProfileManager.CurrentProfile?.Save(ProfileManager.ProfilePath); - - break; - - case MacroType.EnableRangeColor: - ProfileManager.CurrentProfile.NoColorObjectsOutOfRange = true; - - break; - - case MacroType.DisableRangeColor: - ProfileManager.CurrentProfile.NoColorObjectsOutOfRange = false; - - break; - - case MacroType.ToggleRangeColor: - ProfileManager.CurrentProfile.NoColorObjectsOutOfRange = !ProfileManager.CurrentProfile.NoColorObjectsOutOfRange; - - break; - - case MacroType.AttackSelectedTarget: - - if (SerialHelper.IsMobile(TargetManager.SelectedTarget)) - { - GameActions.Attack(TargetManager.SelectedTarget); - } - - break; - - case MacroType.UseSelectedTarget: - if (SerialHelper.IsValid(TargetManager.SelectedTarget)) - { - GameActions.DoubleClick(TargetManager.SelectedTarget); - } - - break; - - case MacroType.CurrentTarget: - - if (TargetManager.SelectedTarget != 0) - { - if (WaitForTargetTimer == 0) - { - WaitForTargetTimer = Time.Ticks + Constants.WAIT_FOR_TARGET_DELAY; - } - - if (TargetManager.IsTargeting) - { - TargetManager.Target(TargetManager.SelectedTarget); - WaitForTargetTimer = 0; - } - else if (WaitForTargetTimer < Time.Ticks) - { - WaitForTargetTimer = 0; - } - else - { - result = 1; - } - } - - break; - - case MacroType.TargetSystemOnOff: - - GameActions.Print(ResGeneral.TargetSystemNotImplemented); - - break; - - case MacroType.BandageSelf: - case MacroType.BandageTarget: - - if (Client.Version < ClientVersion.CV_5020 || ProfileManager.CurrentProfile.BandageSelfOld) - { - if (WaitingBandageTarget) - { - if (WaitForTargetTimer == 0) - { - WaitForTargetTimer = Time.Ticks + Constants.WAIT_FOR_TARGET_DELAY; - } - - if (TargetManager.IsTargeting) - { - if (macro.Code == MacroType.BandageSelf) - { - TargetManager.Target(World.Player); - } - else if (TargetManager.LastTargetInfo.IsEntity) - { - TargetManager.Target(TargetManager.LastTargetInfo.Serial); - } - - WaitingBandageTarget = false; - WaitForTargetTimer = 0; - } - else if (WaitForTargetTimer < Time.Ticks) - { - WaitingBandageTarget = false; - WaitForTargetTimer = 0; - } - else - { - result = 1; - } - } - else - { - Item bandage = World.Player.FindBandage(); - - if (bandage != null) - { - WaitingBandageTarget = true; - GameActions.DoubleClick(bandage); - result = 1; - } - } - } - else - { - Item bandage = World.Player.FindBandage(); - - if (bandage != null) - { - if (macro.Code == MacroType.BandageSelf) - { - NetClient.Socket.Send_TargetSelectedObject(bandage.Serial, World.Player.Serial); - } - else if (SerialHelper.IsMobile(TargetManager.SelectedTarget)) - { - NetClient.Socket.Send_TargetSelectedObject(bandage.Serial, TargetManager.SelectedTarget); - } - } - } - - break; - - case MacroType.SetUpdateRange: - case MacroType.ModifyUpdateRange: - - if (macro is MacroObjectString moss && !string.IsNullOrEmpty(moss.Text) && byte.TryParse(moss.Text, out byte res)) - { - if (res < Constants.MIN_VIEW_RANGE) - { - res = Constants.MIN_VIEW_RANGE; - } - else if (res > Constants.MAX_VIEW_RANGE) - { - res = Constants.MAX_VIEW_RANGE; - } - - World.ClientViewRange = res; - - GameActions.Print(string.Format(ResGeneral.ClientViewRangeIsNow0, res)); - } - - break; - - case MacroType.IncreaseUpdateRange: - World.ClientViewRange++; - - if (World.ClientViewRange > Constants.MAX_VIEW_RANGE) - { - World.ClientViewRange = Constants.MAX_VIEW_RANGE; - } - - GameActions.Print(string.Format(ResGeneral.ClientViewRangeIsNow0, World.ClientViewRange)); - - break; - - case MacroType.DecreaseUpdateRange: - World.ClientViewRange--; - - if (World.ClientViewRange < Constants.MIN_VIEW_RANGE) - { - World.ClientViewRange = Constants.MIN_VIEW_RANGE; - } - - GameActions.Print(string.Format(ResGeneral.ClientViewRangeIsNow0, World.ClientViewRange)); - - break; - - case MacroType.MaxUpdateRange: - World.ClientViewRange = Constants.MAX_VIEW_RANGE; - GameActions.Print(string.Format(ResGeneral.ClientViewRangeIsNow0, World.ClientViewRange)); - - break; - - case MacroType.MinUpdateRange: - World.ClientViewRange = Constants.MIN_VIEW_RANGE; - GameActions.Print(string.Format(ResGeneral.ClientViewRangeIsNow0, World.ClientViewRange)); - - break; - - case MacroType.DefaultUpdateRange: - World.ClientViewRange = Constants.MAX_VIEW_RANGE; - GameActions.Print(string.Format(ResGeneral.ClientViewRangeIsNow0, World.ClientViewRange)); - - break; - - case MacroType.SelectNext: - case MacroType.SelectPrevious: - case MacroType.SelectNearest: - // scanRange: - // 0 - SelectNext - // 1 - SelectPrevious - // 2 - SelectNearest - ScanModeObject scanRange = (ScanModeObject)(macro.Code - MacroType.SelectNext); - - // scantype: - // 0 - Hostile (only hostile mobiles: gray, criminal, enemy, murderer) - // 1 - Party (only party members) - // 2 - Follower (only your followers) - // 3 - Object (???) - // 4 - Mobile (any mobiles) - ScanTypeObject scantype = (ScanTypeObject)(macro.SubCode - MacroSubType.Hostile); - - if (scanRange == ScanModeObject.Nearest) - { - SetLastTarget(World.FindNearest(scantype)); - } - else - { - SetLastTarget(World.FindNext(scantype, TargetManager.SelectedTarget, scanRange == ScanModeObject.Previous)); - } - - break; - - case MacroType.ToggleBuffIconGump: - if (ProfileManager.CurrentProfile.UseImprovedBuffBar) - { - ImprovedBuffGump buff = UIManager.GetGump(); - if (buff != null) - { - buff.Dispose(); - } - else - { - UIManager.Add(new ImprovedBuffGump()); - } - } - else - { - BuffGump buff = UIManager.GetGump(); - - if (buff != null) - { - buff.Dispose(); - } - else - { - UIManager.Add(new BuffGump(100, 100)); - } - } - break; - - case MacroType.InvokeVirtue: - byte id = (byte)(macro.SubCode - MacroSubType.Honor + 1); - NetClient.Socket.Send_InvokeVirtueRequest(id); - - break; - - case MacroType.PrimaryAbility: - GameActions.UsePrimaryAbility(); - - break; - - case MacroType.SecondaryAbility: - GameActions.UseSecondaryAbility(); - - break; - - case MacroType.ToggleGargoyleFly: - - if (World.Player.Race == RaceType.GARGOYLE) - { - NetClient.Socket.Send_ToggleGargoyleFlying(); - } - - break; - - case MacroType.EquipLastWeapon: - NetClient.Socket.Send_EquipLastWeapon(); - - break; - - case MacroType.KillGumpOpen: - // TODO: - break; - - case MacroType.Zoom: - - switch (macro.SubCode) - { - case MacroSubType.MSC_NONE: - case MacroSubType.DefaultZoom: - Client.Game.Scene.Camera.Zoom = ProfileManager.CurrentProfile.DefaultScale; - - break; - - case MacroSubType.ZoomIn: - Client.Game.Scene.Camera.ZoomIn(); - - break; - - case MacroSubType.ZoomOut: - Client.Game.Scene.Camera.ZoomOut(); - - break; - } - - break; - - case MacroType.ToggleChatVisibility: - UIManager.SystemChat?.ToggleChatVisibility(); - - break; - - case MacroType.Aura: - // hold to draw - break; - - case MacroType.AuraOnOff: - AuraManager.ToggleVisibility(); - - break; - - case MacroType.Grab: - GameActions.Print(ResGeneral.TargetAnItemToGrabIt); - TargetManager.SetTargeting(CursorTarget.Grab, 0, TargetType.Neutral); - - break; - - case MacroType.SetGrabBag: - GameActions.Print(ResGumps.TargetContainerToGrabItemsInto); - TargetManager.SetTargeting(CursorTarget.SetGrabBag, 0, TargetType.Neutral); - - break; - - case MacroType.NamesOnOff: - NameOverHeadManager.ToggleOverheads(); - - break; - - case MacroType.UsePotion: - scantype = (ScanTypeObject)(macro.SubCode - MacroSubType.ConfusionBlastPotion); - - ushort start = (ushort)(0x0F06 + scantype); - - Item potion = World.Player.FindItemByGraphic(start); - - if (potion != null) - { - GameActions.DoubleClick(potion); - } - - break; - - case MacroType.UseObject: - Item obj; - - switch (macro.SubCode) - { - case MacroSubType.BestHealPotion: - Span healpotion_clilocs = stackalloc int[3] { 1041330, 1041329, 1041329 }; - - obj = World.Player.FindPreferredItemByCliloc(healpotion_clilocs); - - if (obj != null) - { - GameActions.DoubleClick(obj); - } - - break; - - case MacroSubType.BestCurePotion: - Span curepotion_clilocs = stackalloc int[3] { 1041317, 1041316, 1041315 }; - - obj = World.Player.FindPreferredItemByCliloc(curepotion_clilocs); - - if (obj != null) - { - GameActions.DoubleClick(obj); - } - - break; - - case MacroSubType.BestRefreshPotion: - Span refreshpotion_clilocs = stackalloc int[2] { 1041327, 1041326 }; - - obj = World.Player.FindPreferredItemByCliloc(refreshpotion_clilocs); - - if (obj != null) - { - GameActions.DoubleClick(obj); - } - - break; - - case MacroSubType.BestStrengthPotion: - Span strpotion_clilocs = stackalloc int[2] { 1041321, 1041320 }; - - obj = World.Player.FindPreferredItemByCliloc(strpotion_clilocs); - - if (obj != null) - { - GameActions.DoubleClick(obj); - } - - break; - - case MacroSubType.BestAgiPotion: - Span agipotion_clilocs = stackalloc int[2] { 1041319, 1041318 }; - - obj = World.Player.FindPreferredItemByCliloc(agipotion_clilocs); - - if (obj != null) - { - GameActions.DoubleClick(obj); - } - - break; - - case MacroSubType.BestExplosionPotion: - Span explopotion_clilocs = stackalloc int[3] { 1041333, 1041332, 1041331 }; - - obj = World.Player.FindPreferredItemByCliloc(explopotion_clilocs); - - if (obj != null) - { - GameActions.DoubleClick(obj); - } - - break; - - case MacroSubType.BestConflagPotion: - Span conflagpotion_clilocs = stackalloc int[2] { 1072098, 1072095 }; - - obj = World.Player.FindPreferredItemByCliloc(conflagpotion_clilocs); - - if (obj != null) - { - GameActions.DoubleClick(obj); - } - - break; - - case MacroSubType.HealStone: - obj = World.Player.FindItemByCliloc(1095376); - - if (obj != null) - { - GameActions.DoubleClick(obj); - } - - break; - - case MacroSubType.SpellStone: - obj = World.Player.FindItemByCliloc(1095377); - - if (obj != null) - { - GameActions.DoubleClick(obj); - } - - break; - - case MacroSubType.EnchantedApple: - obj = World.Player.FindItemByCliloc(1032248); - - if (obj != null) - { - GameActions.DoubleClick(obj); - } - - break; - - case MacroSubType.PetalsOfTrinsic: - obj = World.Player.FindItemByCliloc(1062926); - - if (obj != null) - { - GameActions.DoubleClick(obj); - } - - break; - - case MacroSubType.OrangePetals: - obj = World.Player.FindItemByCliloc(1053122); - - if (obj != null) - { - GameActions.DoubleClick(obj); - } - - break; - - case MacroSubType.SmokeBomb: - obj = World.Player.FindItemByGraphic(0x2808); - - if (obj != null) - { - GameActions.DoubleClick(obj); - } - - break; - - case MacroSubType.TrappedBox: - Span trapbox_clilocs = stackalloc int[7] { 1015093, 1022473, 1044309, 1022474, 1023709, 1027808, 1027809 }; - - obj = World.Player.FindPreferredItemByCliloc(trapbox_clilocs); - - if (obj != null) - { - GameActions.DoubleClick(obj); - } - - break; - } - - break; - - case MacroType.CloseAllHealthBars: - - //Includes HealthBarGump/HealthBarGumpCustom - IEnumerable healthBarGumps = UIManager.Gumps.OfType(); - - foreach (BaseHealthBarGump healthbar in healthBarGumps) - { - if (UIManager.AnchorManager[healthbar] == null && healthbar.LocalSerial != World.Player) - { - healthbar.Dispose(); - } - } - - break; - - case MacroType.CloseInactiveHealthBars: - IEnumerable inactiveHealthBarGumps = UIManager.Gumps.OfType().Where(hb => hb.IsInactive); - - foreach (var healthbar in inactiveHealthBarGumps) - { - if (healthbar.LocalSerial == World.Player) continue; - - if (UIManager.AnchorManager[healthbar] != null) - { - UIManager.AnchorManager[healthbar].DetachControl(healthbar); - } - - healthbar.Dispose(); - } - break; - - case MacroType.CloseCorpses: - var gridLootType = ProfileManager.CurrentProfile?.GridLootType; // 0 = none, 1 = only grid, 2 = both - if (gridLootType == 0 || gridLootType == 2) - { - IEnumerable containerGumps = UIManager.Gumps.OfType().Where(cg => cg.Graphic == ContainerGump.CORPSES_GUMP); - - foreach (var containerGump in containerGumps) - { - containerGump.Dispose(); - } - } - if (gridLootType == 1 || gridLootType == 2) - { - IEnumerable gridLootGumps = UIManager.Gumps.OfType(); - - foreach (var gridLootGump in gridLootGumps) - { - gridLootGump.Dispose(); - } - } - break; - - case MacroType.ToggleDrawRoofs: - ProfileManager.CurrentProfile.DrawRoofs = !ProfileManager.CurrentProfile.DrawRoofs; - - break; - - case MacroType.ToggleTreeStumps: - StaticFilters.CleanTreeTextures(); - ProfileManager.CurrentProfile.TreeToStumps = !ProfileManager.CurrentProfile.TreeToStumps; - - break; - - case MacroType.ToggleVegetation: - ProfileManager.CurrentProfile.HideVegetation = !ProfileManager.CurrentProfile.HideVegetation; - - break; - - case MacroType.ToggleCaveTiles: - StaticFilters.CleanCaveTextures(); - ProfileManager.CurrentProfile.EnableCaveBorder = !ProfileManager.CurrentProfile.EnableCaveBorder; - - break; - - case MacroType.LookAtMouse: - // handle in gamesceneinput - break; - - case MacroType.UseCounterBar: - string counterIndex = ((MacroObjectString)macro).Text; - - if (!string.IsNullOrEmpty(counterIndex) && int.TryParse(counterIndex, out int cIndex)) - { - CounterBarGump.CurrentCounterBarGump?.GetCounterItem(cIndex)?.Use(); - } - break; - case MacroType.ClientCommand: - string command = ((MacroObjectString)macro).Text; - - if (!string.IsNullOrEmpty(command)) - { - string[] parts = command.Split(' '); - CommandManager.Execute(parts[0], parts); - } - break; - } - - - return result; - } - - private static void SetLastTarget(uint serial) - { - if (SerialHelper.IsValid(serial)) - { - Entity ent = World.Get(serial); - - if (SerialHelper.IsMobile(serial)) - { - if (ent != null) - { - GameActions.MessageOverhead(string.Format(ResGeneral.Target0, ent.Name), Notoriety.GetHue(((Mobile)ent).NotorietyFlag), World.Player); - - TargetManager.SelectedTarget = serial; - TargetManager.LastTargetInfo.SetEntity(serial); - - return; - } - } - else - { - if (ent != null) - { - GameActions.MessageOverhead(string.Format(ResGeneral.Target0, ent.Name), 992, World.Player); - TargetManager.SelectedTarget = serial; - TargetManager.LastTargetInfo.SetEntity(serial); - - return; - } - } - } - - GameActions.Print(ResGeneral.EntityNotFound); - } - - } - - - public class Macro : LinkedObject, IEquatable - { - public Macro(string name, SDL.SDL_Keycode key, bool alt, bool ctrl, bool shift) : this(name) - { - Key = key; - Alt = alt; - Ctrl = ctrl; - Shift = shift; - } - - public Macro(string name, MouseButtonType button, bool alt, bool ctrl, bool shift) : this(name) - { - MouseButton = button; - Alt = alt; - Ctrl = ctrl; - Shift = shift; - } - - public Macro(string name, bool wheelUp, bool alt, bool ctrl, bool shift) : this(name) - { - WheelScroll = true; - WheelUp = wheelUp; - Alt = alt; - Ctrl = ctrl; - Shift = shift; - } - - public Macro(string name) - { - Name = name; - } - - public string Name { get; } - - public SDL.SDL_GameControllerButton[] ControllerButtons { get; set; } - public SDL.SDL_Keycode Key { get; set; } - public MouseButtonType MouseButton { get; set; } - public bool WheelScroll { get; set; } - public bool WheelUp { get; set; } - public bool Alt { get; set; } - public bool Ctrl { get; set; } - public bool Shift { get; set; } - public bool HideLabel = false; - public ushort Hue = 0x00; - public ushort? Graphic = null; - private byte _scale = 100; - public byte Scale - { - get { return _scale; } - set - { - if (value <= 10) _scale = 10; - else _scale = value; - } - } - - public bool Equals(Macro other) - { - if (other == null) - { - return false; - } - - return Key == other.Key && Alt == other.Alt && Ctrl == other.Ctrl && Shift == other.Shift && Name == other.Name; - } - - //public Macro Left { get; set; } - //public Macro Right { get; set; } - - //private void AppendMacro(MacroObject item) - //{ - // if (FirstNode == null) - // { - // FirstNode = item; - // } - // else - // { - // MacroObject o = FirstNode; - - // while (o.Right != null) - // { - // o = o.Right; - // } - - // o.Right = item; - // item.Left = o; - // } - //} - - - public void Save(XmlTextWriter writer) - { - writer.WriteStartElement("macro"); - writer.WriteAttributeString("name", Name); - writer.WriteAttributeString("key", ((int)Key).ToString()); - writer.WriteAttributeString("mousebutton", ((int)MouseButton).ToString()); - writer.WriteAttributeString("wheelscroll", WheelScroll.ToString()); - writer.WriteAttributeString("wheelup", WheelUp.ToString()); - writer.WriteAttributeString("alt", Alt.ToString()); - writer.WriteAttributeString("ctrl", Ctrl.ToString()); - writer.WriteAttributeString("shift", Shift.ToString()); - writer.WriteAttributeString("hidelabel", HideLabel.ToString()); - writer.WriteAttributeString("hue", Hue.ToString()); - writer.WriteAttributeString("graphic", Graphic.HasValue ? Graphic.ToString() : string.Empty); - writer.WriteAttributeString("scale", Scale.ToString()); - - writer.WriteStartElement("actions"); - - for (MacroObject action = (MacroObject)Items; action != null; action = (MacroObject)action.Next) - { - writer.WriteStartElement("action"); - writer.WriteAttributeString("code", ((int)action.Code).ToString()); - writer.WriteAttributeString("subcode", ((int)action.SubCode).ToString()); - writer.WriteAttributeString("submenutype", action.SubMenuType.ToString()); - - if (action.HasString()) - { - writer.WriteAttributeString("text", ((MacroObjectString)action).Text); - } - - writer.WriteEndElement(); - } - - writer.WriteEndElement(); - - if (ControllerButtons != null) - { - writer.WriteStartElement("controllerbuttons"); - foreach (var b in ControllerButtons) - { - writer.WriteElementString("button", ((int)b).ToString()); - } - writer.WriteEndElement(); - } - - - - writer.WriteEndElement(); - } - - public void Load(XmlElement xml) - { - if (xml == null) - { - return; - } - - Key = (SDL.SDL_Keycode)int.Parse(xml.GetAttribute("key")); - Alt = bool.Parse(xml.GetAttribute("alt")); - Ctrl = bool.Parse(xml.GetAttribute("ctrl")); - Shift = bool.Parse(xml.GetAttribute("shift")); - bool.TryParse(xml.GetAttribute("hidelabel"), out HideLabel); - ushort.TryParse(xml.GetAttribute("hue"), out Hue); - if (byte.TryParse(xml.GetAttribute("scale"), out byte savedScale)) - { - Scale = savedScale; - } - if (ushort.TryParse(xml.GetAttribute("graphic"), out var graphic)) - { - Graphic = graphic; - } - - if (xml.HasAttribute("mousebutton")) - { - MouseButton = (MouseButtonType)int.Parse(xml.GetAttribute("mousebutton")); - } - - if (xml.HasAttribute("wheelscroll")) - { - WheelScroll = bool.Parse(xml.GetAttribute("wheelscroll")); - } - - if (xml.HasAttribute("wheelup")) - { - WheelUp = bool.Parse(xml.GetAttribute("wheelup")); - } - - XmlElement actions = xml["actions"]; - - if (actions != null) - { - foreach (XmlElement xmlAction in actions.GetElementsByTagName("action")) - { - MacroType code = (MacroType)int.Parse(xmlAction.GetAttribute("code")); - MacroSubType sub = (MacroSubType)int.Parse(xmlAction.GetAttribute("subcode")); - - // ########### PATCH ########### - // FIXME: path to remove the MovePlayer macro. This macro is not needed. We have Walk. - if ((int)code == 61 /*MacroType.MovePlayer*/) - { - code = MacroType.Walk; - - switch ((int)sub) - { - case 211: // top - sub = MacroSubType.NW; - - break; - - case 214: // left - sub = MacroSubType.SW; - - break; - - case 213: // down - sub = MacroSubType.SE; - - break; - - case 212: // right - sub = MacroSubType.NE; - - break; - } - } - // ########### END PATCH ########### - - sbyte subMenuType = sbyte.Parse(xmlAction.GetAttribute("submenutype")); - - MacroObject m; - - if (xmlAction.HasAttribute("text")) - { - m = new MacroObjectString(code, sub, xmlAction.GetAttribute("text")); - } - else - { - m = new MacroObject(code, sub); - } - - m.SubMenuType = subMenuType; - - PushToBack(m); - } - } - - XmlElement buttons = xml["controllerbuttons"]; - - if (buttons != null) - { - List savedButtons = new List(); - foreach (XmlElement buttonNum in buttons.GetElementsByTagName("button")) - { - if (int.TryParse(buttonNum.InnerText, out int b)) - { - if (Enum.IsDefined(typeof(SDL_GameControllerButton), b)) - { - savedButtons.Add((SDL_GameControllerButton)b); - } - } - } - ControllerButtons = savedButtons.ToArray(); - } - } - - - public static MacroObject Create(MacroType code) - { - MacroObject obj; - - switch (code) - { - case MacroType.Say: - case MacroType.Emote: - case MacroType.Whisper: - case MacroType.Yell: - case MacroType.Delay: - case MacroType.SetUpdateRange: - case MacroType.ModifyUpdateRange: - case MacroType.RazorMacro: - case MacroType.UseCounterBar: - case MacroType.ClientCommand: - obj = new MacroObjectString(code, MacroSubType.MSC_NONE); - - break; - - default: - obj = new MacroObject(code, MacroSubType.MSC_NONE); - - break; - } - - return obj; - } - - public static Macro CreateEmptyMacro(string name) - { - Macro macro = new Macro - ( - name, - (SDL.SDL_Keycode)0, - false, - false, - false - ); - - MacroObject item = new MacroObject(MacroType.None, MacroSubType.MSC_NONE); - - macro.PushToBack(item); - - return macro; - } - - public static Macro CreateFastMacro(string name, MacroType type, MacroSubType sub) - { - Macro macro = new Macro - ( - name, - (SDL.SDL_Keycode)0, - false, - false, - false - ); - - MacroObject item = new MacroObject(type, sub); - - macro.PushToBack(item); - - return macro; - } - - public static void GetBoundByCode(MacroType code, ref int count, ref int offset) - { - switch (code) - { - case MacroType.Walk: - offset = (int)MacroSubType.NW; - count = MacroSubType.Configuration - MacroSubType.NW; - - break; - - case MacroType.Open: - case MacroType.Close: - case MacroType.Minimize: - case MacroType.Maximize: - offset = (int)MacroSubType.Configuration; - count = MacroSubType.Anatomy - MacroSubType.Configuration; - - break; - - case MacroType.UseSkill: - offset = (int)MacroSubType.Anatomy; - count = MacroSubType.LeftHand - MacroSubType.Anatomy; - - break; - - case MacroType.ArmDisarm: - offset = (int)MacroSubType.LeftHand; - count = MacroSubType.Honor - MacroSubType.LeftHand; - - break; - - case MacroType.InvokeVirtue: - offset = (int)MacroSubType.Honor; - count = MacroSubType.Clumsy - MacroSubType.Honor; - - break; - - case MacroType.CastSpell: - offset = (int)MacroSubType.Clumsy; - count = MacroSubType.Hostile - MacroSubType.Clumsy; - - break; - - case MacroType.SelectNext: - case MacroType.SelectPrevious: - case MacroType.SelectNearest: - offset = (int)MacroSubType.Hostile; - count = MacroSubType.MscTotalCount - MacroSubType.Hostile; - - break; - - case MacroType.UsePotion: - offset = (int)MacroSubType.ConfusionBlastPotion; - count = MacroSubType.DefaultZoom - MacroSubType.ConfusionBlastPotion; - - break; - - case MacroType.Zoom: - offset = (int)MacroSubType.DefaultZoom; - count = 1 + MacroSubType.ZoomOut - MacroSubType.DefaultZoom; - - break; - - case MacroType.UseObject: - offset = (int)MacroSubType.BestHealPotion; - count = 1 + MacroSubType.SpellStone - MacroSubType.BestHealPotion; - - break; - - case MacroType.LookAtMouse: - offset = (int)MacroSubType.LookForwards; - count = 1 + MacroSubType.LookBackwards - MacroSubType.LookForwards; - - break; - } - } - } - - - public class MacroObject : LinkedObject - { - public MacroObject(MacroType code, MacroSubType sub) - { - Code = code; - SubCode = sub; - - switch (code) - { - case MacroType.Walk: - case MacroType.Open: - case MacroType.Close: - case MacroType.Minimize: - case MacroType.Maximize: - case MacroType.UseSkill: - case MacroType.ArmDisarm: - case MacroType.InvokeVirtue: - case MacroType.CastSpell: - case MacroType.SelectNext: - case MacroType.SelectPrevious: - case MacroType.SelectNearest: - case MacroType.UsePotion: - case MacroType.Zoom: - case MacroType.UseObject: - case MacroType.LookAtMouse: - - if (sub == MacroSubType.MSC_NONE) - { - int count = 0; - int offset = 0; - Macro.GetBoundByCode(code, ref count, ref offset); - SubCode = (MacroSubType)offset; - } - - SubMenuType = 1; - - break; - - case MacroType.Say: - case MacroType.Emote: - case MacroType.Whisper: - case MacroType.Yell: - case MacroType.Delay: - case MacroType.SetUpdateRange: - case MacroType.ModifyUpdateRange: - case MacroType.RazorMacro: - case MacroType.UseCounterBar: - case MacroType.ClientCommand: - SubMenuType = 2; - - break; - - default: - SubMenuType = 0; - - break; - } - } - - public MacroType Code { get; set; } - public MacroSubType SubCode { get; set; } - public sbyte SubMenuType { get; set; } - - public virtual bool HasString() - { - return false; - } - } - - public class MacroObjectString : MacroObject - { - public MacroObjectString(MacroType code, MacroSubType sub, string str = "") : base(code, sub) - { - Text = str; - } - - public string Text { get; set; } - - public override bool HasString() - { - return true; - } - } - - public enum MacroType - { - None = 0, - Say, - Emote, - Whisper, - Yell, - Walk, - WarPeace, - Paste, - Open, - Close, - Minimize, - Maximize, - OpenDoor, - UseSkill, - LastSkill, - CastSpell, - LastSpell, - LastObject, - Bow, - Salute, - QuitGame, - AllNames, - LastTarget, - TargetSelf, - ArmDisarm, - WaitForTarget, - TargetNext, - AttackLast, - Delay, - CircleTrans, - CloseGump, - AlwaysRun, - SaveDesktop, - KillGumpOpen, - PrimaryAbility, - SecondaryAbility, - EquipLastWeapon, - SetUpdateRange, - ModifyUpdateRange, - IncreaseUpdateRange, - DecreaseUpdateRange, - MaxUpdateRange, - MinUpdateRange, - DefaultUpdateRange, - EnableRangeColor, - DisableRangeColor, - ToggleRangeColor, - InvokeVirtue, - SelectNext, - SelectPrevious, - SelectNearest, - AttackSelectedTarget, - UseSelectedTarget, - CurrentTarget, - TargetSystemOnOff, - ToggleBuffIconGump, - BandageSelf, - BandageTarget, - ToggleGargoyleFly, - Zoom, - ToggleChatVisibility, - INVALID, - Aura = 62, - AuraOnOff, - Grab, - SetGrabBag, - NamesOnOff, - UseItemInHand, - UsePotion, - CloseAllHealthBars, - RazorMacro, - ToggleDrawRoofs, - ToggleTreeStumps, - ToggleVegetation, - ToggleCaveTiles, - CloseInactiveHealthBars, - CloseCorpses, - UseObject, - LookAtMouse, - UseCounterBar, - ClientCommand - } - - public enum MacroSubType - { - MSC_NONE = 0, - NW, //Walk group - N, - NE, - E, - SE, - S, - SW, - W, - Configuration, //Open/Close/Minimize/Maximize group - Paperdoll, - Status, - Journal, - Skills, - MageSpellbook, - Chat, - Backpack, - Overview, - WorldMap, - Mail, - PartyManifest, - PartyChat, - NecroSpellbook, - PaladinSpellbook, - CombatBook, - BushidoSpellbook, - NinjitsuSpellbook, - Guild, - SpellWeavingSpellbook, - QuestLog, - MysticismSpellbook, - RacialAbilitiesBook, - BardSpellbook, - Anatomy, //Skills group - AnimalLore, - AnimalTaming, - ArmsLore, - Begging, - Cartography, - DetectingHidden, - Discordance, - EvaluatingIntelligence, - ForensicEvaluation, - Hiding, - Imbuing, - Inscription, - ItemIdentification, - Meditation, - Peacemaking, - Poisoning, - Provocation, - RemoveTrap, - SpiritSpeak, - Stealing, - Stealth, - TasteIdentification, - Tracking, - LeftHand, - ///Arm/Disarm group - RightHand, - Honor, //Invoke Virture group - Sacrifice, - Valor, - Clumsy, //Cast Spell group - CreateFood, - Feeblemind, - Heal, - MagicArrow, - NightSight, - ReactiveArmor, - Weaken, - Agility, - Cunning, - Cure, - Harm, - MagicTrap, - MagicUntrap, - Protection, - Strength, - Bless, - Fireball, - MagicLock, - Poison, - Telekinesis, - Teleport, - Unlock, - WallOfStone, - ArchCure, - ArchProtection, - Curse, - FireField, - GreaterHeal, - Lightning, - ManaDrain, - Recall, - BladeSpirits, - DispellField, - Incognito, - MagicReflection, - MindBlast, - Paralyze, - PoisonField, - SummonCreature, - Dispel, - EnergyBolt, - Explosion, - Invisibility, - Mark, - MassCurse, - ParalyzeField, - Reveal, - ChainLightning, - EnergyField, - FlameStrike, - GateTravel, - ManaVampire, - MassDispel, - MeteorSwarm, - Polymorph, - Earthquake, - EnergyVortex, - Resurrection, - AirElemental, - SummonDaemon, - EarthElemental, - FireElemental, - WaterElemental, - AnimateDead, - BloodOath, - CorpseSkin, - CurseWeapon, - EvilOmen, - HorrificBeast, - LichForm, - MindRot, - PainSpike, - PoisonStrike, - Strangle, - SummonFamilar, - VampiricEmbrace, - VengefulSpirit, - Wither, - WraithForm, - Exorcism, - CleanceByFire, - CloseWounds, - ConsecrateWeapon, - DispelEvil, - DivineFury, - EnemyOfOne, - HolyLight, - NobleSacrifice, - RemoveCurse, - SacredJourney, - HonorableExecution, - Confidence, - Evasion, - CounterAttack, - LightingStrike, - MomentumStrike, - FocusAttack, - DeathStrike, - AnimalForm, - KiAttack, - SurpriceAttack, - Backstab, - Shadowjump, - MirrorImage, - ArcaneCircle, - GiftOfRenewal, - ImmolatingWeapon, - Attunement, - Thunderstorm, - NaturesFury, - SummonFey, - SummonFiend, - ReaperForm, - Wildfire, - EssenceOfWind, - DryadAllure, - EtherealVoyage, - WordOfDeath, - GiftOfLife, - ArcaneEmpowermen, - NetherBolt, - HealingStone, - PurgeMagic, - Enchant, - Sleep, - EagleStrike, - AnimatedWeapon, - StoneForm, - SpellTrigger, - MassSleep, - CleansingWinds, - Bombard, - SpellPlague, - HailStorm, - NetherCyclone, - RisingColossus, - Inspire, - Invigorate, - Resilience, - Perseverance, - Tribulation, - Despair, - Hostile, //Select Next/Preveous/Nearest group - Party, - Follower, - Object, - Mobile, - MscTotalCount, - - INVALID_0, - INVALID_1, - INVALID_2, - INVALID_3, - - - ConfusionBlastPotion = 215, - CurePotion, - AgilityPotion, - StrengthPotion, - PoisonPotion, - RefreshPotion, - HealPotion, - ExplosionPotion, - - DefaultZoom, - ZoomIn, - ZoomOut, - - BestHealPotion, - BestCurePotion, - BestRefreshPotion, - BestStrengthPotion, - BestAgiPotion, - BestExplosionPotion, - BestConflagPotion, - EnchantedApple, - PetalsOfTrinsic, - OrangePetals, - TrappedBox, - SmokeBomb, - HealStone, - SpellStone, - - LookForwards, - LookBackwards - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/MessageEventArgs.cs b/src/ClassicUO.Client/Game/Managers/MessageEventArgs.cs deleted file mode 100644 index 0a266f820..000000000 --- a/src/ClassicUO.Client/Game/Managers/MessageEventArgs.cs +++ /dev/null @@ -1,91 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using System; - -namespace ClassicUO.Game.Managers -{ - public class MessageEventArgs : EventArgs - { - public MessageEventArgs - ( - Entity parent, - string text, - string name, - ushort hue, - MessageType type, - byte font, - TextType text_type, - bool unicode = false, - string lang = null - ) - { - Parent = parent; - Text = text; - Name = name; - Hue = hue; - Type = type; - Font = font; - Language = lang; - AffixType = AffixType.None; - IsUnicode = unicode; - TextType = text_type; - } - - - public Entity Parent { get; } - - public string Text { get; } - - public string Name { get; } - - public ushort Hue { get; } - - public MessageType Type { get; } - - public byte Font { get; } - - public string Language { get; } - - public uint Cliloc { get; set; } - - public AffixType AffixType { get; } - - public string Affix { get; } - - public bool IsUnicode { get; } - - public TextType TextType { get; } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/MessageManager.cs b/src/ClassicUO.Client/Game/Managers/MessageManager.cs deleted file mode 100644 index 15727a01f..000000000 --- a/src/ClassicUO.Client/Game/Managers/MessageManager.cs +++ /dev/null @@ -1,406 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Utility; -using System; -using System.Collections.Generic; - -namespace ClassicUO.Game.Managers -{ - //enum MessageFont : byte - //{ - // INVALID = 0xFF, - // Bold = 0, - // Shadow = 1, - // BoldShadow = 2, - // Normal = 3, - // Gothic = 4, - // Italic = 5, - // SmallDark = 6, - // Colorful = 7, - // Rune = 8, - // SmallLight = 9 - //} - - public enum AffixType : byte - { - Append = 0x00, - Prepend = 0x01, - System = 0x02, - None = 0xFF - } - - - internal static class MessageManager - { - public static PromptData PromptData { get; set; } - - public static void HandleMessage - ( - Entity parent, - string text, - string name, - ushort hue, - MessageType type, - byte font, - TextType textType, - bool unicode = false, - string lang = null - ) - { - if (string.IsNullOrEmpty(text)) - { - return; - } - - Profile currentProfile = ProfileManager.CurrentProfile; - - EventSink.InvokeRawMessageReceived(parent, new MessageEventArgs - ( - parent, - text, - name, - hue, - type, - font, - textType, - unicode, - lang - )); - - if (currentProfile != null && currentProfile.OverrideAllFonts) - { - font = currentProfile.ChatFont; - unicode = currentProfile.OverrideAllFontsIsUnicode; - } - - switch (type) - { - case MessageType.ChatSystem: - break; - case MessageType.Command: - case MessageType.Encoded: - case MessageType.System: - break; - case MessageType.Party: - { - if (!ProfileManager.CurrentProfile.DisplayPartyChatOverhead) - break; - if (parent == null) - { - bool handled = false; - foreach (PartyMember member in World.Party.Members) - if (member != null) - if (member.Name == name) - { - Mobile m = World.Mobiles.Get(member.Serial); - if (m != null) - { - parent = m; - handled = true; - break; - } - - } - if (!handled) break; - } - - // If person who send that message is in ignores list - but filter out Spell Text - if (IgnoreManager.IgnoredCharsList.Contains(parent.Name) && type != MessageType.Spell) - break; - - TextObject msg = CreateMessage - ( - text, - hue, - font, - unicode, - type, - textType - ); - - parent.AddMessage(msg); - break; - } - case MessageType.Guild: - if (currentProfile.IgnoreGuildMessages) return; - break; - - case MessageType.Alliance: - if (currentProfile.IgnoreAllianceMessages) return; - break; - - case MessageType.Spell: - { - //server hue color per default - if (!string.IsNullOrEmpty(text) && SpellDefinition.WordToTargettype.TryGetValue(text, out SpellDefinition spell)) - { - if (currentProfile != null && currentProfile.EnabledSpellFormat && !string.IsNullOrWhiteSpace(currentProfile.SpellDisplayFormat)) - { - ValueStringBuilder sb = new ValueStringBuilder(currentProfile.SpellDisplayFormat.AsSpan()); - { - sb.Replace("{power}".AsSpan(), spell.PowerWords.AsSpan()); - sb.Replace("{spell}".AsSpan(), spell.Name.AsSpan()); - - text = sb.ToString().Trim(); - } - sb.Dispose(); - } - - //server hue color per default if not enabled - if (currentProfile != null && currentProfile.EnabledSpellHue) - { - if (spell.TargetType == TargetType.Beneficial) - { - hue = currentProfile.BeneficHue; - } - else if (spell.TargetType == TargetType.Harmful) - { - hue = currentProfile.HarmfulHue; - } - else - { - hue = currentProfile.NeutralHue; - } - } - } - - goto case MessageType.Label; - } - - default: - case MessageType.Focus: - case MessageType.Whisper: - case MessageType.Yell: - case MessageType.Regular: - case MessageType.Label: - if (textType == TextType.OBJECT) - { - for (LinkedListNode gump = UIManager.Gumps.Last; gump != null; gump = gump.Previous) - { - if (gump.Value is GridContainer && !gump.Value.IsDisposed) - { - ((GridContainer)gump.Value).HandleObjectMessage(parent, text, hue); - } - } - } - goto case MessageType.Limit3Spell; - case MessageType.Limit3Spell: - { - if (parent == null) - { - break; - } - - // If person who send that message is in ignores list - but filter out Spell Text - if (IgnoreManager.IgnoredCharsList.Contains(parent.Name) && type != MessageType.Spell) - break; - - TextObject msg = CreateMessage - ( - text, - hue, - font, - unicode, - type, - textType - ); - - msg.Owner = parent; - - if (parent is Item it && !it.OnGround) - { - msg.X = DelayedObjectClickManager.X; - msg.Y = DelayedObjectClickManager.Y; - msg.IsTextGump = true; - bool found = false; - - for (LinkedListNode gump = UIManager.Gumps.Last; gump != null; gump = gump.Previous) - { - Control g = gump.Value; - - if (!g.IsDisposed) - { - switch (g) - { - case PaperDollGump paperDoll when g.LocalSerial == it.Container: - paperDoll.AddText(msg); - found = true; - - break; - - case ContainerGump container when g.LocalSerial == it.Container: - container.AddText(msg); - found = true; - - break; - - case TradingGump trade when trade.ID1 == it.Container || trade.ID2 == it.Container: - trade.AddText(msg); - found = true; - - break; - } - } - - if (found) - { - break; - } - } - } - - parent.AddMessage(msg); - - break; - } - } - - EventSink.InvokeMessageReceived(parent, new MessageEventArgs - ( - parent, - text, - name, - hue, - type, - font, - textType, - unicode, - lang - )); - } - - public static TextObject CreateMessage - ( - string msg, - ushort hue, - byte font, - bool isunicode, - MessageType type, - TextType textType - ) - { - - ushort fixedColor = (ushort)(hue & 0x3FFF); - - if (fixedColor != 0) - { - if (fixedColor >= 0x0BB8) - { - fixedColor = 1; - } - - fixedColor |= (ushort)(hue & 0xC000); - } - else - { - fixedColor = (ushort)(hue & 0x8000); - } - - - TextObject textObject = TextObject.Create(); - textObject.Alpha = 0xFF; - textObject.Type = type; - //textObject.Hue = fixedColor; - - if (!isunicode && textType == TextType.OBJECT) - { - fixedColor = 0x7FFF; - } - - //Ignored the fixedColor in the textbox creation because it seems to interfere with correct colors, but if issues arrise I left the fixColor code here - - textObject.TextBox = new TextBox( - msg, - ProfileManager.CurrentProfile.OverheadChatFont, - ProfileManager.CurrentProfile.OverheadChatFontSize, - ProfileManager.CurrentProfile.OverheadChatWidth, - hue, - FontStashSharp.RichText.TextHorizontalAlignment.Center, - true - ) - { AcceptMouseInput = !ProfileManager.CurrentProfile.DisableMouseInteractionOverheadText }; - - textObject.Time = CalculateTimeToLive(textObject.TextBox); - - return textObject; - } - - private static long CalculateTimeToLive(TextBox rtext) - { - Profile currentProfile = ProfileManager.CurrentProfile; - - if (currentProfile == null) - { - return 0; - } - - long timeToLive; - - if (currentProfile.ScaleSpeechDelay) - { - int delay = currentProfile.SpeechDelay; - - if (delay < 10) - { - delay = 10; - } - - int fakeLines = 0; - if (rtext.Text.Length > 99) - fakeLines = 3; - else if (rtext.Text.Length > 66) - fakeLines = 2; - else - fakeLines = 1; - - - timeToLive = (long)(4000 * fakeLines * delay / 100.0f); - } - else - { - long delay = (5497558140000 * currentProfile.SpeechDelay) >> 32 >> 5; - - timeToLive = (delay >> 31) + delay; - } - - timeToLive += Time.Ticks; - - return timeToLive; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/MobileStatusRequestQueue.cs b/src/ClassicUO.Client/Game/Managers/MobileStatusRequestQueue.cs deleted file mode 100644 index 0fc34a3fc..000000000 --- a/src/ClassicUO.Client/Game/Managers/MobileStatusRequestQueue.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ClassicUO.Game.Managers -{ - internal class MobileStatusRequestQueue - { - private ConcurrentQueue requestedSerials = new ConcurrentQueue(); - private static MobileStatusRequestQueue instance; - private Task queueProccessor; - public static MobileStatusRequestQueue Instance - { - get - { - instance ??= new MobileStatusRequestQueue(); - return instance; - } - } - private MobileStatusRequestQueue(){ } - - public void RequestMobileStatus(uint serial) - { - requestedSerials.Enqueue(serial); - if (requestedSerials.Count > 0 && (queueProccessor == null || queueProccessor.IsCompleted || !queueProccessor.Status.Equals(TaskStatus.Running))) - { - queueProccessor = Task.Factory.StartNew(() => { - while (requestedSerials.TryDequeue(out var serial)) - { - GameActions.RequestMobileStatus(serial); - GameActions.Print($"Processing {serial}"); - Task.Delay(1000).Wait(); - } - }); - } - } - } -} diff --git a/src/ClassicUO.Client/Game/Managers/NameOverHeadManager.cs b/src/ClassicUO.Client/Game/Managers/NameOverHeadManager.cs deleted file mode 100644 index 82f79758b..000000000 --- a/src/ClassicUO.Client/Game/Managers/NameOverHeadManager.cs +++ /dev/null @@ -1,477 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Utility.Logging; -using SDL2; - -namespace ClassicUO.Game.Managers -{ - [Flags] - internal enum NameOverheadOptions - { - None = 0, - - // Items - Containers = 1 << 0, - Gold = 1 << 1, - Stackable = 1 << 2, - LockedDown = 1 << 3, - Other = 1 << 4, - - // Corpses - MonsterCorpses = 1 << 5, - HumanoidCorpses = 1 << 6, - OwnCorpses = 1 << 7, - - // Mobiles (type) - Humanoid = 1 << 8, - Monster = 1 << 9, - OwnFollowers = 1 << 10, - Self = 1 << 11, - ExcludeSelf = 1 << 12, - - // Mobiles (notoriety) - Innocent = 1 << 13, - Ally = 1 << 14, - Gray = 1 << 15, - Criminal = 1 << 16, - Enemy = 1 << 17, - Murderer = 1 << 18, - Invulnerable = 1 << 19, - - AllItems = Containers | Gold | Stackable | LockedDown | Other, - AllMobiles = Humanoid | Monster | OwnFollowers | Self, - MobilesAndCorpses = AllMobiles | MonsterCorpses | HumanoidCorpses, - } - - internal static class NameOverHeadManager - { - private static NameOverHeadHandlerGump _gump; - private static SDL.SDL_Keycode _lastKeySym = SDL.SDL_Keycode.SDLK_UNKNOWN; - private static SDL.SDL_Keymod _lastKeyMod = SDL.SDL_Keymod.KMOD_NONE; - - public static string LastActiveNameOverheadOption - { - get => ProfileManager.CurrentProfile.LastActiveNameOverheadOption; - set => ProfileManager.CurrentProfile.LastActiveNameOverheadOption = value; - } - - public static NameOverheadOptions ActiveOverheadOptions { get; set; } - - public static bool IsPermaToggled - { - get => ProfileManager.CurrentProfile.NameOverheadToggled; - private set => ProfileManager.CurrentProfile.NameOverheadToggled = value; - } - - public static bool IsTemporarilyShowing { get; private set; } - public static bool IsShowing => IsPermaToggled || IsTemporarilyShowing || Keyboard.Ctrl && Keyboard.Shift; - - private static List Options { get; set; } = new List(); - - public static string Search { get; set; } = string.Empty; - - public static bool IsAllowed(Entity serial) - { - if (serial == null) - return false; - - if (SerialHelper.IsItem(serial)) - return HandleItemOverhead(serial); - - if (SerialHelper.IsMobile(serial)) - return HandleMobileOverhead(serial); - - return false; - } - - private static bool HandleMobileOverhead(Entity serial) - { - var mobile = serial as Mobile; - - if (mobile == null) - return false; - - if(mobile.Equals(World.Player) && ActiveOverheadOptions.HasFlag(NameOverheadOptions.ExcludeSelf)) - return false; - - // Mobile types - if (ActiveOverheadOptions.HasFlag(NameOverheadOptions.Humanoid) && mobile.IsHuman) - return true; - - if (ActiveOverheadOptions.HasFlag(NameOverheadOptions.Monster) && !mobile.IsHuman) - return true; - - if (ActiveOverheadOptions.HasFlag(NameOverheadOptions.OwnFollowers) && mobile.IsRenamable && mobile.NotorietyFlag != NotorietyFlag.Invulnerable && mobile.NotorietyFlag != NotorietyFlag.Enemy) - return true; - - // Mobile notorieties - if (ActiveOverheadOptions.HasFlag(NameOverheadOptions.Innocent) && mobile.NotorietyFlag == NotorietyFlag.Innocent) - return true; - - if (ActiveOverheadOptions.HasFlag(NameOverheadOptions.Ally) && mobile.NotorietyFlag == NotorietyFlag.Ally) - return true; - - if (ActiveOverheadOptions.HasFlag(NameOverheadOptions.Gray) && mobile.NotorietyFlag == NotorietyFlag.Gray) - return true; - - if (ActiveOverheadOptions.HasFlag(NameOverheadOptions.Criminal) && mobile.NotorietyFlag == NotorietyFlag.Criminal) - return true; - - if (ActiveOverheadOptions.HasFlag(NameOverheadOptions.Enemy) && mobile.NotorietyFlag == NotorietyFlag.Enemy) - return true; - - if (ActiveOverheadOptions.HasFlag(NameOverheadOptions.Murderer) && mobile.NotorietyFlag == NotorietyFlag.Murderer) - return true; - - if (ActiveOverheadOptions.HasFlag(NameOverheadOptions.Invulnerable) && mobile.NotorietyFlag == NotorietyFlag.Invulnerable) - return true; - - if(ActiveOverheadOptions.HasFlag(NameOverheadOptions.Self) && mobile.Equals(World.Player)) - return true; - - return false; - } - - private static bool HandleItemOverhead(Entity serial) - { - var item = serial as Item; - - if (item == null) - return false; - - if (item.IsCorpse) - { - return HandleCorpseOverhead(item); - } - - if (item.ItemData.IsContainer && ActiveOverheadOptions.HasFlag(NameOverheadOptions.Containers)) - return true; - - if (item.IsCoin && ActiveOverheadOptions.HasFlag(NameOverheadOptions.Gold)) - return true; - - if (item.ItemData.IsStackable && ActiveOverheadOptions.HasFlag(NameOverheadOptions.Stackable)) - return true; - - if (item.IsLocked && ActiveOverheadOptions.HasFlag(NameOverheadOptions.LockedDown)) - return true; - - if (ActiveOverheadOptions.HasFlag(NameOverheadOptions.Other)) - return true; - - return false; - } - - private static bool HandleCorpseOverhead(Item item) - { - var isHumanCorpse = item.IsHumanCorpse; - - if (isHumanCorpse && ActiveOverheadOptions.HasFlag(NameOverheadOptions.HumanoidCorpses)) - return true; - - if (!isHumanCorpse && ActiveOverheadOptions.HasFlag(NameOverheadOptions.MonsterCorpses)) - return true; - - // TODO: Add support for IsOwnCorpse, which was coded by Dyru - return false; - } - - public static void Open() - { - if (_gump == null || _gump.IsDisposed) - { - _gump = new NameOverHeadHandlerGump(); - UIManager.Add(_gump); - } - - _gump.IsEnabled = true; - _gump.IsVisible = true; - } - - public static void Close() - { - if (_gump == null) - return; - - _gump.IsEnabled = false; - _gump.IsVisible = false; - } - - public static void ToggleOverheads() - { - SetOverheadToggled(!IsPermaToggled); - } - - public static void SetOverheadToggled(bool toggled) - { - if (IsPermaToggled == toggled) - return; - - IsPermaToggled = toggled; - _gump?.UpdateCheckboxes(); - } - - public static void Load() - { - string path = Path.Combine(ProfileManager.ProfilePath, "nameoverhead.xml"); - - if (!File.Exists(path)) - { - Log.Trace("No nameoverhead.xml file. Creating a default file."); - - - Options.Clear(); - CreateDefaultEntries(); - Save(); - - return; - } - - Options.Clear(); - XmlDocument doc = new(); - - try - { - doc.Load(path); - } - catch (Exception ex) - { - Log.Error(ex.ToString()); - - return; - } - - - XmlElement root = doc["nameoverhead"]; - - if (root != null) - { - foreach (XmlElement xml in root.GetElementsByTagName("nameoverheadoption")) - { - var option = new NameOverheadOption(xml.GetAttribute("name")); - option.Load(xml); - Options.Add(option); - } - } - } - - public static void Save() - { - var list = Options; - - string path = Path.Combine(ProfileManager.ProfilePath, "nameoverhead.xml"); - - using XmlTextWriter xml = new(path, Encoding.UTF8) - { - Formatting = Formatting.Indented, - IndentChar = '\t', - Indentation = 1 - }; - - xml.WriteStartDocument(true); - xml.WriteStartElement("nameoverhead"); - - foreach (var option in list) - { - option.Save(xml); - } - - xml.WriteEndElement(); - xml.WriteEndDocument(); - } - - private static void CreateDefaultEntries() - { - Options.AddRange - ( - new[] - { - new NameOverheadOption("All", int.MaxValue), - new NameOverheadOption("Mobiles only", (int)NameOverheadOptions.AllMobiles), - new NameOverheadOption("Items only", (int)NameOverheadOptions.AllItems), - new NameOverheadOption("Mobiles & Corpses only", (int)NameOverheadOptions.MobilesAndCorpses), - } - ); - } - - public static NameOverheadOption FindOption(string name) - { - return Options.Find(o => o.Name == name); - } - - public static void AddOption(NameOverheadOption option) - { - Options.Add(option); - _gump?.RedrawOverheadOptions(); - } - - public static void RemoveOption(NameOverheadOption option) - { - Options.Remove(option); - _gump?.RedrawOverheadOptions(); - } - - public static NameOverheadOption FindOptionByHotkey(SDL.SDL_Keycode key, bool alt, bool ctrl, bool shift) - { - return Options.FirstOrDefault(o => o.Key == key && o.Alt == alt && o.Ctrl == ctrl && o.Shift == shift); - } - - public static List GetAllOptions() => Options; - - public static void RegisterKeyDown(SDL.SDL_Keysym key) - { - if (_lastKeySym == key.sym && _lastKeyMod == key.mod) - return; - - _lastKeySym = key.sym; - _lastKeyMod = key.mod; - - bool shift = (key.mod & SDL.SDL_Keymod.KMOD_SHIFT) != SDL.SDL_Keymod.KMOD_NONE; - bool alt = (key.mod & SDL.SDL_Keymod.KMOD_ALT) != SDL.SDL_Keymod.KMOD_NONE; - bool ctrl = (key.mod & SDL.SDL_Keymod.KMOD_CTRL) != SDL.SDL_Keymod.KMOD_NONE; - - var option = FindOptionByHotkey(key.sym, alt, ctrl, shift); - - if (option == null) - return; - - SetActiveOption(option); - - IsTemporarilyShowing = true; - } - - public static void RegisterKeyUp(SDL.SDL_Keysym key) - { - if (key.sym != _lastKeySym) - return; - - _lastKeySym = SDL.SDL_Keycode.SDLK_UNKNOWN; - - IsTemporarilyShowing = false; - } - - public static void SetActiveOption(NameOverheadOption option) - { - if (option == null) - { - ActiveOverheadOptions = NameOverheadOptions.None; - LastActiveNameOverheadOption = string.Empty; - } - else - { - ActiveOverheadOptions = (NameOverheadOptions)option.NameOverheadOptionFlags; - LastActiveNameOverheadOption = option.Name; - _gump?.UpdateCheckboxes(); - } - } - } - - internal class NameOverheadOption - { - public NameOverheadOption(string name, SDL.SDL_Keycode key, bool alt, bool ctrl, bool shift, int optionflagscode) : this(name) - { - Key = key; - Alt = alt; - Ctrl = ctrl; - Shift = shift; - NameOverheadOptionFlags = optionflagscode; - } - - public NameOverheadOption(string name) - { - Name = name; - } - - public NameOverheadOption(string name, int optionflagcode) - { - Name = name; - NameOverheadOptionFlags = optionflagcode; - } - - public string Name { get; } - - public SDL.SDL_Keycode Key { get; set; } - public bool Alt { get; set; } - public bool Ctrl { get; set; } - public bool Shift { get; set; } - public int NameOverheadOptionFlags { get; set; } - - public bool Equals(NameOverheadOption other) - { - if (other == null) - { - return false; - } - - return Key == other.Key && Alt == other.Alt && Ctrl == other.Ctrl && Shift == other.Shift && Name == other.Name; - } - - public void Save(XmlTextWriter writer) - { - writer.WriteStartElement("nameoverheadoption"); - writer.WriteAttributeString("name", Name); - writer.WriteAttributeString("key", ((int)Key).ToString()); - writer.WriteAttributeString("alt", Alt.ToString()); - writer.WriteAttributeString("ctrl", Ctrl.ToString()); - writer.WriteAttributeString("shift", Shift.ToString()); - writer.WriteAttributeString("optionflagscode", NameOverheadOptionFlags.ToString()); - - writer.WriteEndElement(); - } - - public void Load(XmlElement xml) - { - if (xml == null) - { - return; - } - - Key = (SDL.SDL_Keycode)int.Parse(xml.GetAttribute("key")); - Alt = bool.Parse(xml.GetAttribute("alt")); - Ctrl = bool.Parse(xml.GetAttribute("ctrl")); - Shift = bool.Parse(xml.GetAttribute("shift")); - NameOverheadOptionFlags = int.Parse(xml.GetAttribute("optionflagscode")); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/ObjectPropertiesListManager.cs b/src/ClassicUO.Client/Game/Managers/ObjectPropertiesListManager.cs deleted file mode 100644 index 04c77704e..000000000 --- a/src/ClassicUO.Client/Game/Managers/ObjectPropertiesListManager.cs +++ /dev/null @@ -1,368 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Network; - -namespace ClassicUO.Game.Managers -{ - public sealed class ObjectPropertiesListManager - { - private readonly Dictionary _itemsProperties = new Dictionary(); - - public void Add(uint serial, uint revision, string name, string data, int namecliloc) - { - if (!_itemsProperties.TryGetValue(serial, out ItemProperty prop)) - { - prop = new ItemProperty(); - _itemsProperties[serial] = prop; - } - - prop.Serial = serial; - prop.Revision = revision; - prop.Name = name; - prop.Data = data; - prop.NameCliloc = namecliloc; - - EventSink.InvokeOPLOnReceive(null, new OPLEventArgs(serial, name, data)); - } - - public bool Contains(uint serial) - { - if (_itemsProperties.TryGetValue(serial, out ItemProperty p)) - { - return true; //p.Revision != 0; <-- revision == 0 can contain the name. - } - - // if we don't have the OPL of this item, let's request it to the server. - // Original client seems asking for OPL when character is not running. - // We'll ask OPL when mouse is over an object. - PacketHandlers.AddMegaClilocRequest(serial); - - return false; - } - - public bool IsRevisionEquals(uint serial, uint revision) - { - if (_itemsProperties.TryGetValue(serial, out ItemProperty prop)) - { - return (revision & ~0x40000000) == prop.Revision || // remove the mask - revision == prop.Revision; // if mask removing didn't work, try a simple compare. - } - - return false; - } - - public bool TryGetRevision(uint serial, out uint revision) - { - if (_itemsProperties.TryGetValue(serial, out ItemProperty p)) - { - revision = p.Revision; - - return true; - } - - revision = 0; - - return false; - } - - public bool TryGetNameAndData(uint serial, out string name, out string data) - { - if (_itemsProperties.TryGetValue(serial, out ItemProperty p)) - { - name = p.Name; - data = p.Data; - - return true; - } - - name = data = null; - - return false; - } - - public int GetNameCliloc(uint serial) - { - if (_itemsProperties.TryGetValue(serial, out ItemProperty p)) - { - return p.NameCliloc; - } - - return 0; - } - - public ItemPropertiesData TryGetItemPropertiesData(uint serial) - { - if (Contains(serial)) - if (World.Items.TryGetValue(serial, out Item item)) - return new ItemPropertiesData(item); - return null; - } - - public void Remove(uint serial) - { - _itemsProperties.Remove(serial); - } - - public void Clear() - { - _itemsProperties.Clear(); - } - } - - internal class ItemProperty - { - public bool IsEmpty => string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(Data); - public string Data; - public string Name; - public uint Revision; - public uint Serial; - public int NameCliloc; - - public string CreateData(bool extended) - { - return string.Empty; - } - } - - public class ItemPropertiesData - { - public readonly bool HasData = false; - public string Name = ""; - public readonly string RawData = ""; - public readonly uint serial; - public string[] RawLines; - public readonly Item item, itemComparedTo; - public List singlePropertyData = new List(); - - public ItemPropertiesData(Item item, Item compareTo = null) - { - if (item == null) - return; - this.item = item; - itemComparedTo = compareTo; - - serial = item.Serial; - if (World.OPL.TryGetNameAndData(item.Serial, out Name, out RawData)) - { - Name = Name.Trim(); - HasData = true; - processData(); - } - } - - public ItemPropertiesData(string tooltip) - { - if (string.IsNullOrEmpty(tooltip)) - return; - if (tooltip.Contains("\n")) - { - Name = tooltip.Substring(0, tooltip.IndexOf("\n")); - RawData = tooltip.Substring(tooltip.IndexOf("\n") + 1); - } - else - { - Name = tooltip; - } - HasData = true; - processData(); - } - - private void processData() - { - string formattedData = TextBox.ConvertHtmlToFontStashSharpCommand(RawData); - - RawLines = formattedData.Split(new string[] { "\n", "
" }, StringSplitOptions.None); - - foreach (string line in RawLines) - { - singlePropertyData.Add(new SinglePropertyData(line)); - } - - if(itemComparedTo != null) - { - GenComparisonData(); - } - } - - private void GenComparisonData() - { - if(itemComparedTo == null) return; - - ItemPropertiesData itemPropertiesData = new ItemPropertiesData(itemComparedTo); - if (itemPropertiesData.HasData) - { - foreach (SinglePropertyData thisItem in singlePropertyData) - { - foreach (SinglePropertyData secondItem in itemPropertiesData.singlePropertyData) - { - if (String.Equals(thisItem.Name, secondItem.Name, StringComparison.InvariantCultureIgnoreCase)) - { - if (thisItem.FirstValue != -1 && secondItem.FirstValue != -1) - { - thisItem.FirstDiff = thisItem.FirstValue - secondItem.FirstValue; - } - - if (thisItem.SecondValue > -1 && secondItem.SecondValue > -1) - { - thisItem.SecondDiff = thisItem.SecondValue - secondItem.SecondValue; - } - break; - } - } - } - } - } - - public bool GenerateComparisonTooltip(ItemPropertiesData comparedTo, out string compiledToolTip) - { - if (!HasData) - { - compiledToolTip = null; - return false; - } - - string finalTooltip = Name + "\n"; - - foreach (SinglePropertyData thisItem in singlePropertyData) - { - bool foundMatch = false; - foreach (SinglePropertyData secondItem in comparedTo.singlePropertyData) - { - if (String.Equals(thisItem.Name, secondItem.Name, StringComparison.InvariantCultureIgnoreCase)) - { - foundMatch = true; - finalTooltip += thisItem.Name; - - if (thisItem.FirstValue != -1 && secondItem.FirstValue != -1) - { - double diff = thisItem.FirstValue - secondItem.FirstValue; - finalTooltip += $" {thisItem.FirstValue}"; - if (diff != 0) - { - finalTooltip += $"({(diff >= 0 ? "/c[green]+" : "/c[red]")} {diff}/cd)"; - } - } - - if (thisItem.SecondValue > -1 && secondItem.SecondValue > -1) - { - double diff = thisItem.SecondValue - secondItem.SecondValue; - finalTooltip += $" {thisItem.SecondValue}"; - if (diff != 0) - { - finalTooltip += $"({(diff >= 0 ? "/c[green]+" : "/c[red]")}{diff}/cd)"; - } - } - - finalTooltip += "\n"; - break; - } - } - if (!foundMatch) - finalTooltip += thisItem.ToString() + "\n"; - } - - compiledToolTip = finalTooltip; - return true; - } - - public string CompileTooltip() - { - string result = ""; - - result += Name + "\n"; - foreach (SinglePropertyData data in singlePropertyData) - result += $"{data.Name} [{data.FirstValue}] [{data.SecondValue}]\n"; - - return result; - } - - public class SinglePropertyData - { - public string OriginalString; - public string Name = ""; - public double FirstValue = -1; - public double SecondValue = -1; - public double FirstDiff = 0; - public double SecondDiff = 0; - - public SinglePropertyData(string line) - { - OriginalString = line; - - string pattern = @"(-?\d+(\.)?(\d+)?)"; - MatchCollection matches = Regex.Matches(line, pattern, RegexOptions.CultureInvariant); - - Match nameMatch = Regex.Match(line, @"(\D+)"); - if (nameMatch.Success) - { - Name = nameMatch.Value; - //Name = Regex.Replace(Name, "/c[\"?'?(?.*?)\"?'?]", "", RegexOptions.Multiline | RegexOptions.IgnoreCase); - Name = Name.Replace("/cd", ""); - } - - if (Name.Length < 1) - Name = line; - - if (matches.Count > 0) - { - double.TryParse(matches[0].Value, out FirstValue); - if (matches.Count > 1) - { - double.TryParse(matches[1].Value, out SecondValue); - } - } - } - - public override string ToString() - { - string output = ""; - - if (Name != null) - output += Name; - - if (FirstValue != -1) - output += $" {FirstValue}"; - - if (SecondValue != -1) - output += $" {SecondValue}"; - - return output; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/PartyManager.cs b/src/ClassicUO.Client/Game/Managers/PartyManager.cs deleted file mode 100644 index 5f58704b2..000000000 --- a/src/ClassicUO.Client/Game/Managers/PartyManager.cs +++ /dev/null @@ -1,287 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.IO; -using ClassicUO.Resources; - -namespace ClassicUO.Game.Managers -{ - public class PartyManager - { - private const int PARTY_SIZE = 10; - - public uint Leader { get; set; } - public uint Inviter { get; set; } - public bool CanLoot { get; set; } - - public PartyMember[] Members { get; } = new PartyMember[PARTY_SIZE]; - - - public long PartyHealTimer { get; set; } - public uint PartyHealTarget { get; set; } - - public void ParsePacket(ref StackDataReader p) - { - byte code = p.ReadUInt8(); - - bool add = false; - - switch (code) - { - case 1: - add = true; - goto case 2; - - case 2: - byte count = p.ReadUInt8(); - - if (count <= 1) - { - Leader = 0; - Inviter = 0; - - for (int i = 0; i < PARTY_SIZE; i++) - { - if (Members[i] == null || Members[i].Serial == 0) - { - break; - } - - BaseHealthBarGump gump = UIManager.GetGump(Members[i].Serial); - - - if (gump != null) - { - if (code == 2) - { - Members[i].Serial = 0; - } - - gump.RequestUpdateContents(); - } - } - - Clear(); - - UIManager.GetGump()?.RequestUpdateContents(); - - break; - } - - Clear(); - - uint to_remove = 0xFFFF_FFFF; - - if (!add) - { - to_remove = p.ReadUInt32BE(); - - UIManager.GetGump(to_remove)?.RequestUpdateContents(); - } - - bool remove_all = !add && to_remove == World.Player; - int done = 0; - - for (int i = 0; i < count; i++) - { - uint serial = p.ReadUInt32BE(); - bool remove = !add && serial == to_remove; - - if (remove && serial == to_remove && i == 0) - { - remove_all = true; - } - - if (!remove && !remove_all) - { - if (!Contains(serial)) - { - Members[i] = new PartyMember(serial); - } - - done++; - } - - if (i == 0 && !remove && !remove_all) - { - Leader = serial; - } - - BaseHealthBarGump gump = UIManager.GetGump(serial); - - if (gump != null) - { - gump.RequestUpdateContents(); - } - else - { - if (serial == World.Player) - { - } - } - } - - if (done <= 1 && !add) - { - for (int i = 0; i < PARTY_SIZE; i++) - { - if (Members[i] != null && SerialHelper.IsValid(Members[i].Serial)) - { - uint serial = Members[i].Serial; - - Members[i] = null; - - UIManager.GetGump(serial)?.RequestUpdateContents(); - } - } - - Clear(); - } - - - UIManager.GetGump()?.RequestUpdateContents(); - - break; - - case 3: - case 4: - uint ser = p.ReadUInt32BE(); - string name = p.ReadUnicodeBE(); - - for (int i = 0; i < PARTY_SIZE; i++) - { - if (Members[i] != null && Members[i].Serial == ser) - { - MessageManager.HandleMessage - ( - null, - name, - Members[i].Name, - ProfileManager.CurrentProfile.PartyMessageHue, - MessageType.Party, - 3, - TextType.GUILD_ALLY - ); - - break; - } - } - - break; - - case 7: - Inviter = p.ReadUInt32BE(); - - if (ProfileManager.CurrentProfile.PartyInviteGump) - { - UIManager.Add(new PartyInviteGump(Inviter)); - } - - break; - } - } - - public bool Contains(uint serial) - { - for (int i = 0; i < PARTY_SIZE; i++) - { - PartyMember mem = Members[i]; - - if (mem != null && mem.Serial == serial) - { - return true; - } - } - - return false; - } - - public void Clear() - { - Leader = 0; - Inviter = 0; - - for (int i = 0; i < PARTY_SIZE; i++) - { - Members[i] = null; - } - } - } - - public class PartyMember : IEquatable - { - private string _name; - - public PartyMember(uint serial) - { - Serial = serial; - _name = Name; - } - - public string Name - { - get - { - Mobile mobile = World.Mobiles.Get(Serial); - - if (mobile != null) - { - _name = mobile.Name; - - if (string.IsNullOrEmpty(_name)) - { - _name = ResGeneral.NotSeeing; - } - } - - return _name; - } - } - - public bool Equals(PartyMember other) - { - if (other == null) - { - return false; - } - - return other.Serial == Serial; - } - - public uint Serial; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/Season.cs b/src/ClassicUO.Client/Game/Managers/Season.cs deleted file mode 100644 index a1936e1ba..000000000 --- a/src/ClassicUO.Client/Game/Managers/Season.cs +++ /dev/null @@ -1,43 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Managers -{ - public enum Season - { - Spring, - Summer, - Fall, - Winter, - Desolation - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/SeasonManager.cs b/src/ClassicUO.Client/Game/Managers/SeasonManager.cs deleted file mode 100644 index 20e6dd4a3..000000000 --- a/src/ClassicUO.Client/Game/Managers/SeasonManager.cs +++ /dev/null @@ -1,720 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Assets; -using System; -using System.IO; - -namespace ClassicUO.Game.Managers -{ - internal static class SeasonManager - { - private static ushort[] _springLandTile; - private static ushort[] _summerLandTile; - private static ushort[] _fallLandTile; - private static ushort[] _winterLandTile; - private static ushort[] _desolationLandTile; - - private static ushort[] _springGraphic; - private static ushort[] _summerGraphic; - private static ushort[] _fallGraphic; - private static ushort[] _winterGraphic; - private static ushort[] _desolationGraphic; - - private static readonly string _seasonsFilePath = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Client"); - private static readonly string _seasonsFile = Path.Combine(_seasonsFilePath, "seasons.txt"); - - static SeasonManager() - { - LoadSeasonFile(); - } - - public static void LoadSeasonFile() - { - _springLandTile = new ushort[ArtLoader.MAX_LAND_DATA_INDEX_COUNT]; - _summerLandTile = new ushort[ArtLoader.MAX_LAND_DATA_INDEX_COUNT]; - _fallLandTile = new ushort[ArtLoader.MAX_LAND_DATA_INDEX_COUNT]; - _winterLandTile = new ushort[ArtLoader.MAX_LAND_DATA_INDEX_COUNT]; - _desolationLandTile = new ushort[ArtLoader.MAX_LAND_DATA_INDEX_COUNT]; - - _springGraphic = new ushort[ArtLoader.MAX_STATIC_DATA_INDEX_COUNT]; - _summerGraphic = new ushort[ArtLoader.MAX_STATIC_DATA_INDEX_COUNT]; - _fallGraphic = new ushort[ArtLoader.MAX_STATIC_DATA_INDEX_COUNT]; - _winterGraphic = new ushort[ArtLoader.MAX_STATIC_DATA_INDEX_COUNT]; - _desolationGraphic = new ushort[ArtLoader.MAX_STATIC_DATA_INDEX_COUNT]; - - if (!File.Exists(_seasonsFile)) - { - CreateDefaultSeasonsFile(); - } - - using (StreamReader reader = new StreamReader(_seasonsFile)) - { - while (!reader.EndOfStream) - { - string line = reader.ReadLine(); - - if (string.IsNullOrEmpty(line) || line.StartsWith("#") || line.StartsWith("//")) - { - continue; - } - - string[] seasonLine = line.Split(','); - - if (seasonLine.Length < 4) - { - continue; - } - - ushort orig = seasonLine[2].StartsWith("0x", StringComparison.InvariantCultureIgnoreCase) ? - Convert.ToUInt16(seasonLine[2], 16) : - Convert.ToUInt16(seasonLine[2]); - - ushort replace = seasonLine[3].StartsWith("0x", StringComparison.InvariantCultureIgnoreCase) ? - Convert.ToUInt16(seasonLine[3], 16) : - Convert.ToUInt16(seasonLine[3]); - - bool isStatic = seasonLine[1].StartsWith("static", StringComparison.InvariantCultureIgnoreCase); - - switch (seasonLine[0].ToLower()) - { - case "spring": - - if (isStatic) - { - _springGraphic[orig] = replace; - } - else - { - _springLandTile[orig] = replace; - } - - break; - - case "summer": - - if (isStatic) - { - _summerGraphic[orig] = replace; - } - else - { - _summerLandTile[orig] = replace; - } - - break; - - case "fall": - - if (isStatic) - { - _fallGraphic[orig] = replace; - } - else - { - _fallLandTile[orig] = replace; - } - - break; - - case "winter": - - if (isStatic) - { - _winterGraphic[orig] = replace; - } - else - { - _winterLandTile[orig] = replace; - } - - break; - - case "desolation": - if (isStatic) - { - _desolationGraphic[orig] = replace; - } - else - { - _desolationLandTile[orig] = replace; - } - - break; - } - } - } - } - - public static ushort GetSeasonGraphic(Season season, ushort graphic) - { - switch (season) - { - case Season.Spring: return _springGraphic[graphic] == 0 ? graphic : _springGraphic[graphic]; - case Season.Summer: return _summerGraphic[graphic] == 0 ? graphic : _summerGraphic[graphic]; - case Season.Fall: return _fallGraphic[graphic] == 0 ? graphic : _fallGraphic[graphic]; - case Season.Winter: return _winterGraphic[graphic] == 0 ? graphic : _winterGraphic[graphic]; - case Season.Desolation: return _desolationGraphic[graphic] == 0 ? graphic : _desolationGraphic[graphic]; - } - - return graphic; - } - - public static ushort GetLandSeasonGraphic(Season season, ushort graphic) - { - switch (season) - { - case Season.Spring: return _springLandTile[graphic] == 0 ? graphic : _springLandTile[graphic]; - case Season.Summer: return _summerLandTile[graphic] == 0 ? graphic : _summerLandTile[graphic]; - case Season.Fall: return _fallLandTile[graphic] == 0 ? graphic : _fallLandTile[graphic]; - case Season.Winter: return _winterLandTile[graphic] == 0 ? graphic : _winterLandTile[graphic]; - case Season.Desolation: return _desolationLandTile[graphic] == 0 ? graphic : _desolationLandTile[graphic]; - } - - return graphic; - } - - #region CreateDefaultFile - - private static void CreateDefaultSeasonsFile() - { - if (File.Exists(_seasonsFile)) - { - return; - } - - using (StreamWriter writer = new StreamWriter(_seasonsFile)) - { - writer.WriteLine("spring,static,0x0CA7,0x0C84"); - writer.WriteLine("spring,static,0x0CAC,0x0C46"); - writer.WriteLine("spring,static,0x0CAD,0x0C48"); - writer.WriteLine("spring,static,0x0CAE,0x0CB5"); - writer.WriteLine("spring,static,0x0C4A,0x0CB5"); - writer.WriteLine("spring,static,0x0CAF,0x0C4E"); - writer.WriteLine("spring,static,0x0CB0,0x0C4D"); - writer.WriteLine("spring,static,0x0CB6,0x0D2B"); - writer.WriteLine("spring,static,0x0D0D,0x0D2B"); - writer.WriteLine("spring,static,0x0D14,0x0D2B"); - writer.WriteLine("spring,static,0x0D0C,0x0D29"); - writer.WriteLine("spring,static,0x0D0E,0x0CBE"); - writer.WriteLine("spring,static,0x0D0F,0x0CBF"); - writer.WriteLine("spring,static,0x0D10,0x0CC0"); - writer.WriteLine("spring,static,0x0D11,0x0C87"); - writer.WriteLine("spring,static,0x0D12,0x0C38"); - writer.WriteLine("spring,static,0x0D13,0x0D2F"); - writer.WriteLine("fall,static,0x0CD1,0x0CD2"); - writer.WriteLine("fall,static,0x0CD4,0x0CD5"); - writer.WriteLine("fall,static,0x0CDB,0x0CDC"); - writer.WriteLine("fall,static,0x0CDE,0x0CDF"); - writer.WriteLine("fall,static,0x0CE1,0x0CE2"); - writer.WriteLine("fall,static,0x0CE4,0x0CE5"); - writer.WriteLine("fall,static,0x0CE7,0x0CE8"); - writer.WriteLine("fall,static,0x0D95,0x0D97"); - writer.WriteLine("fall,static,0x0D99,0x0D9B"); - writer.WriteLine("fall,static,0x0CCE,0x0CCF"); - writer.WriteLine("fall,static,0x0CE9,0x0D3F"); - writer.WriteLine("fall,static,0x0C9E,0x0D3F"); - writer.WriteLine("fall,static,0x0CEA,0x0D40"); - writer.WriteLine("fall,static,0x0C84,0x1B22"); - writer.WriteLine("fall,static,0x0CB0,0x1B22"); - writer.WriteLine("fall,static,0x0C8B,0x0CC6"); - writer.WriteLine("fall,static,0x0C8C,0x0CC6"); - writer.WriteLine("fall,static,0x0C8D,0x0CC6"); - writer.WriteLine("fall,static,0x0C8E,0x0CC6"); - writer.WriteLine("fall,static,0x0CA7,0x0C48"); - writer.WriteLine("fall,static,0x0CAC,0x1B1F"); - writer.WriteLine("fall,static,0x0CAD,0x1B20"); - writer.WriteLine("fall,static,0x0CAE,0x1B21"); - writer.WriteLine("fall,static,0x0CAF,0x0D0D"); - writer.WriteLine("fall,static,0x0CB5,0x0D10"); - writer.WriteLine("fall,static,0x0CB6,0x0D2B"); - writer.WriteLine("fall,static,0x0CC7,0x0C4E"); - writer.WriteLine("winter,static,0x0CA7,0x0CC6"); - writer.WriteLine("winter,static,0x0CAC,0x0D3D"); - writer.WriteLine("winter,static,0x0CAD,0x0D33"); - writer.WriteLine("winter,static,0x0CAE,0x0D33"); - writer.WriteLine("winter,static,0x0CB5,0x0D33"); - writer.WriteLine("winter,static,0x0CAF,0x17CD"); - writer.WriteLine("winter,static,0x0C87,0x17CD"); - writer.WriteLine("winter,static,0x0C89,0x17CD"); - writer.WriteLine("winter,static,0x0D16,0x17CD"); - writer.WriteLine("winter,static,0x0D17,0x17CD"); - writer.WriteLine("winter,static,0x0D32,0x17CD"); - writer.WriteLine("winter,static,0x0D33,0x17CD"); - writer.WriteLine("winter,static,0x0CB0,0x17CD"); - writer.WriteLine("winter,static,0x0C8E,0x1B8D"); - writer.WriteLine("winter,static,0x0C99,0x1B8D"); - writer.WriteLine("winter,static,0x0C46,0x1B9D"); - writer.WriteLine("winter,static,0x0C49,0x1B9D"); - writer.WriteLine("winter,static,0x0C45,0x1B9C"); - writer.WriteLine("winter,static,0x0C48,0x1B9C"); - writer.WriteLine("winter,static,0x0CBF,0x1B9C"); - writer.WriteLine("winter,static,0x0C4E,0x1B9C"); - writer.WriteLine("winter,static,0x0D2B,0x1B9C"); - writer.WriteLine("winter,static,0x0C85,0x1B9C"); - writer.WriteLine("winter,static,0x0D15,0x1B9C"); - writer.WriteLine("winter,static,0x0D29,0x1B9C"); - writer.WriteLine("winter,static,0x0CB1,0x17CD"); - writer.WriteLine("winter,static,0x0CB2,0x17CD"); - writer.WriteLine("winter,static,0x0CB3,0x17CD"); - writer.WriteLine("winter,static,0x0CB4,0x17CD"); - writer.WriteLine("winter,static,0x0CB7,0x17CD"); - writer.WriteLine("winter,static,0x0CC5,0x17CD"); - writer.WriteLine("winter,static,0x0D0C,0x17CD"); - writer.WriteLine("winter,static,0x0CB6,0x17CD"); - writer.WriteLine("winter,static,0x0C37,0x1B1F"); - writer.WriteLine("winter,static,0x0C38,0x1B1F"); - writer.WriteLine("winter,static,0x0C47,0x1B1F"); - writer.WriteLine("winter,static,0x0C4A,0x1B1F"); - writer.WriteLine("winter,static,0x0C4B,0x1B1F"); - writer.WriteLine("winter,static,0x0C4D,0x1B1F"); - writer.WriteLine("winter,static,0x0C8C,0x1B1F"); - writer.WriteLine("winter,static,0x0D2F,0x1B1F"); - writer.WriteLine("winter,static,0x0C8D,0x1B22"); - writer.WriteLine("winter,static,0x0C93,0x1B22"); - writer.WriteLine("winter,static,0x0C94,0x1B22"); - writer.WriteLine("winter,static,0x0C98,0x1B22"); - writer.WriteLine("winter,static,0x0C9F,0x1B22"); - writer.WriteLine("winter,static,0x0CA0,0x1B22"); - writer.WriteLine("winter,static,0x0CA1,0x1B22"); - writer.WriteLine("winter,static,0x0CA2,0x1B22"); - writer.WriteLine("winter,static,0x0CA3,0x1BAE"); - writer.WriteLine("winter,static,0x0CA4,0x1BAE"); - writer.WriteLine("winter,static,0x0D0D,0x1BAE"); - writer.WriteLine("winter,static,0x0D0E,0x1BAE"); - writer.WriteLine("winter,static,0x0D10,0x1BAE"); - writer.WriteLine("winter,static,0x0D12,0x1BAE"); - writer.WriteLine("winter,static,0x0D13,0x1BAE"); - writer.WriteLine("winter,static,0x0D18,0x1BAE"); - writer.WriteLine("winter,static,0x0D19,0x1BAE"); - writer.WriteLine("winter,static,0x0D2D,0x1BAE"); - writer.WriteLine("winter,static,0x0CC7,0x1B20"); - writer.WriteLine("winter,static,0x0C84,0x1B84"); - writer.WriteLine("winter,static,0x0C8B,0x1B84"); - writer.WriteLine("winter,static,0x0CE9,0x0CCA"); - writer.WriteLine("winter,static,0x0C9E,0x0CCA"); - writer.WriteLine("winter,static,0x33A1,0x17CD"); - writer.WriteLine("winter,static,0x33A2,0x17CD"); - writer.WriteLine("winter,static,0x33A3,0x17CD"); - writer.WriteLine("winter,static,0x33A4,0x17CD"); - writer.WriteLine("winter,static,0x33A6,0x17CD"); - writer.WriteLine("winter,static,0x33AB,0x17CD"); - writer.WriteLine("winter,landtile,196,282"); - writer.WriteLine("winter,landtile,197,283"); - writer.WriteLine("winter,landtile,198,284"); - writer.WriteLine("winter,landtile,199,285"); - writer.WriteLine("winter,landtile,248,282"); - writer.WriteLine("winter,landtile,249,283"); - writer.WriteLine("winter,landtile,250,284"); - writer.WriteLine("winter,landtile,251,285"); - writer.WriteLine("winter,landtile,349,937"); - writer.WriteLine("winter,landtile,350,940"); - writer.WriteLine("winter,landtile,351,938"); - writer.WriteLine("winter,landtile,352,939"); - writer.WriteLine("winter,landtile,200,282"); - writer.WriteLine("winter,landtile,201,283"); - writer.WriteLine("winter,landtile,202,284"); - writer.WriteLine("winter,landtile,203,285"); - writer.WriteLine("winter,landtile,204,282"); - writer.WriteLine("winter,landtile,205,283"); - writer.WriteLine("winter,landtile,206,284"); - writer.WriteLine("winter,landtile,207,285"); - writer.WriteLine("winter,landtile,208,282"); - writer.WriteLine("winter,landtile,209,283"); - writer.WriteLine("winter,landtile,210,284"); - writer.WriteLine("winter,landtile,211,285"); - writer.WriteLine("winter,landtile,212,282"); - writer.WriteLine("winter,landtile,213,283"); - writer.WriteLine("winter,landtile,214,284"); - writer.WriteLine("winter,landtile,215,285"); - writer.WriteLine("winter,landtile,216,282"); - writer.WriteLine("winter,landtile,217,283"); - writer.WriteLine("winter,landtile,218,284"); - writer.WriteLine("winter,landtile,219,285"); - writer.WriteLine("winter,landtile,1697,282"); - writer.WriteLine("winter,landtile,1698,283"); - writer.WriteLine("winter,landtile,1699,284"); - writer.WriteLine("winter,landtile,1700,285"); - writer.WriteLine("winter,landtile,1711,282"); - writer.WriteLine("winter,landtile,1712,283"); - writer.WriteLine("winter,landtile,1713,284"); - writer.WriteLine("winter,landtile,1714,285"); - writer.WriteLine("winter,landtile,1715,282"); - writer.WriteLine("winter,landtile,1716,283"); - writer.WriteLine("winter,landtile,1717,284"); - writer.WriteLine("winter,landtile,1718,285"); - writer.WriteLine("winter,landtile,1719,282"); - writer.WriteLine("winter,landtile,1720,283"); - writer.WriteLine("winter,landtile,1721,284"); - writer.WriteLine("winter,landtile,1722,285"); - writer.WriteLine("winter,landtile,1723,282"); - writer.WriteLine("winter,landtile,1724,283"); - writer.WriteLine("winter,landtile,1725,284"); - writer.WriteLine("winter,landtile,1726,285"); - writer.WriteLine("winter,landtile,1727,282"); - writer.WriteLine("winter,landtile,1728,283"); - writer.WriteLine("winter,landtile,1729,284"); - writer.WriteLine("winter,landtile,1730,285"); - writer.WriteLine("winter,landtile,332,932"); - writer.WriteLine("winter,landtile,333,929"); - writer.WriteLine("winter,landtile,334,930"); - writer.WriteLine("winter,landtile,335,931"); - writer.WriteLine("winter,landtile,353,908"); - writer.WriteLine("winter,landtile,354,907"); - writer.WriteLine("winter,landtile,355,905"); - writer.WriteLine("winter,landtile,356,906"); - writer.WriteLine("winter,landtile,357,904"); - writer.WriteLine("winter,landtile,358,903"); - writer.WriteLine("winter,landtile,359,902"); - writer.WriteLine("winter,landtile,360,901"); - writer.WriteLine("winter,landtile,361,912"); - writer.WriteLine("winter,landtile,362,911"); - writer.WriteLine("winter,landtile,363,909"); - writer.WriteLine("winter,landtile,364,910"); - writer.WriteLine("winter,landtile,369,916"); - writer.WriteLine("winter,landtile,370,915"); - writer.WriteLine("winter,landtile,371,914"); - writer.WriteLine("winter,landtile,372,913"); - writer.WriteLine("winter,landtile,1351,917"); - writer.WriteLine("winter,landtile,1352,918"); - writer.WriteLine("winter,landtile,1353,919"); - writer.WriteLine("winter,landtile,1354,920"); - writer.WriteLine("winter,landtile,1355,921"); - writer.WriteLine("winter,landtile,1356,922"); - writer.WriteLine("winter,landtile,1357,923"); - writer.WriteLine("winter,landtile,1358,924"); - writer.WriteLine("winter,landtile,1359,925"); - writer.WriteLine("winter,landtile,1360,927"); - writer.WriteLine("winter,landtile,1361,928"); - writer.WriteLine("winter,landtile,1362,930"); - writer.WriteLine("winter,landtile,1363,933"); - writer.WriteLine("winter,landtile,1364,934"); - writer.WriteLine("winter,landtile,1365,935"); - writer.WriteLine("winter,landtile,1366,936"); - writer.WriteLine("winter,landtile,804,931"); - writer.WriteLine("winter,landtile,805,929"); - writer.WriteLine("winter,landtile,806,926"); - writer.WriteLine("winter,landtile,807,925"); - writer.WriteLine("winter,landtile,808,932"); - writer.WriteLine("winter,landtile,809,930"); - writer.WriteLine("winter,landtile,810,928"); - writer.WriteLine("winter,landtile,811,927"); - writer.WriteLine("winter,landtile,812,919"); - writer.WriteLine("winter,landtile,813,920"); - writer.WriteLine("winter,landtile,814,917"); - writer.WriteLine("winter,landtile,815,921"); - writer.WriteLine("winter,landtile,3,282"); - writer.WriteLine("winter,landtile,4,283"); - writer.WriteLine("winter,landtile,5,284"); - writer.WriteLine("winter,landtile,6,285"); - writer.WriteLine("winter,landtile,121,910"); - writer.WriteLine("winter,landtile,122,909"); - writer.WriteLine("winter,landtile,123,912"); - writer.WriteLine("winter,landtile,124,911"); - writer.WriteLine("winter,landtile,125,906"); - writer.WriteLine("winter,landtile,126,905"); - writer.WriteLine("winter,landtile,130,908"); - writer.WriteLine("winter,landtile,131,907"); - writer.WriteLine("winter,landtile,133,904"); - writer.WriteLine("winter,landtile,134,904"); - writer.WriteLine("winter,landtile,135,903"); - writer.WriteLine("winter,landtile,136,903"); - writer.WriteLine("winter,landtile,137,902"); - writer.WriteLine("winter,landtile,138,902"); - writer.WriteLine("winter,landtile,139,901"); - writer.WriteLine("winter,landtile,140,901"); - writer.WriteLine("winter,landtile,871,917"); - writer.WriteLine("winter,landtile,872,918"); - writer.WriteLine("winter,landtile,873,919"); - writer.WriteLine("winter,landtile,874,920"); - writer.WriteLine("winter,landtile,875,921"); - writer.WriteLine("winter,landtile,876,922"); - writer.WriteLine("winter,landtile,877,923"); - writer.WriteLine("winter,landtile,878,924"); - writer.WriteLine("winter,landtile,879,925"); - writer.WriteLine("winter,landtile,880,926"); - writer.WriteLine("winter,landtile,881,927"); - writer.WriteLine("winter,landtile,882,928"); - writer.WriteLine("winter,landtile,883,929"); - writer.WriteLine("winter,landtile,884,930"); - writer.WriteLine("winter,landtile,885,931"); - writer.WriteLine("winter,landtile,886,932"); - writer.WriteLine("winter,landtile,887,933"); - writer.WriteLine("winter,landtile,888,934"); - writer.WriteLine("winter,landtile,889,935"); - writer.WriteLine("winter,landtile,890,936"); - writer.WriteLine("winter,landtile,891,937"); - writer.WriteLine("winter,landtile,892,938"); - writer.WriteLine("winter,landtile,893,939"); - writer.WriteLine("winter,landtile,894,940"); - writer.WriteLine("winter,landtile,365,916"); - writer.WriteLine("winter,landtile,366,915"); - writer.WriteLine("winter,landtile,367,913"); - writer.WriteLine("winter,landtile,368,914"); - writer.WriteLine("winter,landtile,236,278"); - writer.WriteLine("winter,landtile,237,279"); - writer.WriteLine("winter,landtile,238,276"); - writer.WriteLine("winter,landtile,239,277"); - writer.WriteLine("winter,landtile,240,305"); - writer.WriteLine("winter,landtile,241,302"); - writer.WriteLine("winter,landtile,242,303"); - writer.WriteLine("winter,landtile,243,304"); - writer.WriteLine("winter,landtile,244,272"); - writer.WriteLine("winter,landtile,245,273"); - writer.WriteLine("winter,landtile,246,274"); - writer.WriteLine("winter,landtile,247,275"); - writer.WriteLine("winter,landtile,561,268"); - writer.WriteLine("winter,landtile,562,269"); - writer.WriteLine("winter,landtile,563,270"); - writer.WriteLine("winter,landtile,564,271"); - writer.WriteLine("winter,landtile,565,272"); - writer.WriteLine("winter,landtile,566,273"); - writer.WriteLine("winter,landtile,567,274"); - writer.WriteLine("winter,landtile,568,275"); - writer.WriteLine("winter,landtile,569,276"); - writer.WriteLine("winter,landtile,570,277"); - writer.WriteLine("winter,landtile,571,278"); - writer.WriteLine("winter,landtile,572,279"); - writer.WriteLine("winter,landtile,573,1861"); - writer.WriteLine("winter,landtile,574,1862"); - writer.WriteLine("winter,landtile,575,1863"); - writer.WriteLine("winter,landtile,576,1864"); - writer.WriteLine("winter,landtile,577,1865"); - writer.WriteLine("winter,landtile,578,1866"); - writer.WriteLine("winter,landtile,579,1867"); - writer.WriteLine("winter,landtile,1741,1868"); - writer.WriteLine("winter,landtile,1742,1869"); - writer.WriteLine("winter,landtile,1743,1870"); - writer.WriteLine("winter,landtile,1744,1871"); - writer.WriteLine("winter,landtile,1745,1872"); - writer.WriteLine("winter,landtile,1746,1873"); - writer.WriteLine("winter,landtile,1747,1874"); - writer.WriteLine("winter,landtile,1748,1875"); - writer.WriteLine("winter,landtile,1749,1876"); - writer.WriteLine("winter,landtile,1750,1877"); - writer.WriteLine("winter,landtile,1751,1878"); - writer.WriteLine("winter,landtile,1752,1879"); - writer.WriteLine("winter,landtile,1753,1880"); - writer.WriteLine("winter,landtile,1754,1881"); - writer.WriteLine("winter,landtile,1755,1882"); - writer.WriteLine("winter,landtile,1756,1883"); - writer.WriteLine("winter,landtile,1757,1884"); - writer.WriteLine("winter,landtile,1758,282"); - writer.WriteLine("winter,landtile,1759,283"); - writer.WriteLine("winter,landtile,1760,284"); - writer.WriteLine("winter,landtile,1761,285"); - writer.WriteLine("winter,landtile,26,379"); - writer.WriteLine("winter,landtile,27,378"); - writer.WriteLine("winter,landtile,28,377"); - writer.WriteLine("winter,landtile,29,380"); - writer.WriteLine("winter,landtile,30,381"); - writer.WriteLine("winter,landtile,31,382"); - writer.WriteLine("winter,landtile,32,383"); - writer.WriteLine("winter,landtile,33,384"); - writer.WriteLine("winter,landtile,34,385"); - writer.WriteLine("winter,landtile,35,386"); - writer.WriteLine("winter,landtile,36,387"); - writer.WriteLine("winter,landtile,37,388"); - writer.WriteLine("winter,landtile,38,389"); - writer.WriteLine("winter,landtile,39,390"); - writer.WriteLine("winter,landtile,40,391"); - writer.WriteLine("winter,landtile,41,392"); - writer.WriteLine("winter,landtile,42,393"); - writer.WriteLine("winter,landtile,43,394"); - writer.WriteLine("winter,landtile,44,387"); - writer.WriteLine("winter,landtile,45,388"); - writer.WriteLine("winter,landtile,46,383"); - writer.WriteLine("winter,landtile,47,380"); - writer.WriteLine("winter,landtile,48,383"); - writer.WriteLine("winter,landtile,49,378"); - writer.WriteLine("winter,landtile,50,379"); - writer.WriteLine("winter,landtile,141,379"); - writer.WriteLine("winter,landtile,142,386"); - writer.WriteLine("winter,landtile,143,385"); - writer.WriteLine("winter,landtile,144,393"); - writer.WriteLine("winter,landtile,145,378"); - writer.WriteLine("winter,landtile,146,387"); - writer.WriteLine("winter,landtile,147,391"); - writer.WriteLine("winter,landtile,148,392"); - writer.WriteLine("winter,landtile,149,377"); - writer.WriteLine("winter,landtile,150,379"); - writer.WriteLine("winter,landtile,151,383"); - writer.WriteLine("winter,landtile,152,380"); - writer.WriteLine("winter,landtile,153,387"); - writer.WriteLine("winter,landtile,154,388"); - writer.WriteLine("winter,landtile,155,393"); - writer.WriteLine("winter,landtile,156,391"); - writer.WriteLine("winter,landtile,157,387"); - writer.WriteLine("winter,landtile,158,385"); - writer.WriteLine("winter,landtile,159,385"); - writer.WriteLine("winter,landtile,160,389"); - writer.WriteLine("winter,landtile,161,379"); - writer.WriteLine("winter,landtile,162,384"); - writer.WriteLine("winter,landtile,163,380"); - writer.WriteLine("winter,landtile,164,379"); - writer.WriteLine("winter,landtile,165,378"); - writer.WriteLine("winter,landtile,166,378"); - writer.WriteLine("winter,landtile,167,394"); - writer.WriteLine("winter,landtile,1521,282"); - writer.WriteLine("winter,landtile,1522,283"); - writer.WriteLine("winter,landtile,1523,284"); - writer.WriteLine("winter,landtile,1524,285"); - writer.WriteLine("winter,landtile,1529,282"); - writer.WriteLine("winter,landtile,1530,283"); - writer.WriteLine("winter,landtile,1531,284"); - writer.WriteLine("winter,landtile,1532,285"); - writer.WriteLine("winter,landtile,1533,282"); - writer.WriteLine("winter,landtile,1534,283"); - writer.WriteLine("winter,landtile,1535,284"); - writer.WriteLine("winter,landtile,1536,285"); - writer.WriteLine("winter,landtile,1537,282"); - writer.WriteLine("winter,landtile,1538,283"); - writer.WriteLine("winter,landtile,1539,284"); - writer.WriteLine("winter,landtile,1540,285"); - writer.WriteLine("winter,landtile,741,379"); - writer.WriteLine("winter,landtile,742,385"); - writer.WriteLine("winter,landtile,743,389"); - writer.WriteLine("winter,landtile,744,393"); - writer.WriteLine("winter,landtile,745,378"); - writer.WriteLine("winter,landtile,746,384"); - writer.WriteLine("winter,landtile,747,388"); - writer.WriteLine("winter,landtile,748,392"); - writer.WriteLine("winter,landtile,749,377"); - writer.WriteLine("winter,landtile,750,385"); - writer.WriteLine("winter,landtile,751,383"); - writer.WriteLine("winter,landtile,752,380"); - writer.WriteLine("winter,landtile,753,391"); - writer.WriteLine("winter,landtile,754,388"); - writer.WriteLine("winter,landtile,755,385"); - writer.WriteLine("winter,landtile,756,384"); - writer.WriteLine("winter,landtile,757,391"); - writer.WriteLine("winter,landtile,758,379"); - writer.WriteLine("winter,landtile,759,393"); - writer.WriteLine("winter,landtile,760,383"); - writer.WriteLine("winter,landtile,761,385"); - writer.WriteLine("winter,landtile,762,391"); - writer.WriteLine("winter,landtile,763,391"); - writer.WriteLine("winter,landtile,764,379"); - writer.WriteLine("winter,landtile,765,384"); - writer.WriteLine("winter,landtile,766,384"); - writer.WriteLine("winter,landtile,767,379"); - writer.WriteLine("winter,landtile,9,282"); - writer.WriteLine("winter,landtile,10,283"); - writer.WriteLine("winter,landtile,11,284"); - writer.WriteLine("winter,landtile,12,285"); - writer.WriteLine("winter,landtile,13,282"); - writer.WriteLine("winter,landtile,14,283"); - writer.WriteLine("winter,landtile,15,284"); - writer.WriteLine("winter,landtile,16,285"); - writer.WriteLine("winter,landtile,17,282"); - writer.WriteLine("winter,landtile,18,283"); - writer.WriteLine("winter,landtile,19,284"); - writer.WriteLine("winter,landtile,20,285"); - writer.WriteLine("winter,landtile,21,282"); - writer.WriteLine("desolation,static,0x1B7E,0x1E34"); - writer.WriteLine("desolation,static,0x0D2B,0x1B15"); - writer.WriteLine("desolation,static,0x0D11,0x122B"); - writer.WriteLine("desolation,static,0x0D14,0x122B"); - writer.WriteLine("desolation,static,0x0D17,0x122B"); - writer.WriteLine("desolation,static,0x0D16,0x1B8D"); - writer.WriteLine("desolation,static,0x0CB9,0x1B8D"); - writer.WriteLine("desolation,static,0x0CBA,0x1B8D"); - writer.WriteLine("desolation,static,0x0CBB,0x1B8D"); - writer.WriteLine("desolation,static,0x0CBC,0x1B8D"); - writer.WriteLine("desolation,static,0x0CBD,0x1B8D"); - writer.WriteLine("desolation,static,0x0CBE,0x1B8D"); - writer.WriteLine("desolation,static,0x0CC7,0x1B0D"); - writer.WriteLine("desolation,static,0x0CE9,0x0ED7"); - writer.WriteLine("desolation,static,0x0CEA,0x0D3F"); - writer.WriteLine("desolation,static,0x0D0F,0x1B1C"); - writer.WriteLine("desolation,static,0x0CB8,0x1CEA"); - writer.WriteLine("desolation,static,0x0C84,0x1B84"); - writer.WriteLine("desolation,static,0x0C8B,0x1B84"); - writer.WriteLine("desolation,static,0x0C9E,0x1182"); - writer.WriteLine("desolation,static,0x0CAD,0x1AE1"); - writer.WriteLine("desolation,static,0x0C4C,0x1B16"); - writer.WriteLine("desolation,static,0x0C8E,0x1B8D"); - writer.WriteLine("desolation,static,0x0C99,0x1B8D"); - writer.WriteLine("desolation,static,0x0CAC,0x1B8D"); - writer.WriteLine("desolation,static,0x0C46,0x1B9D"); - writer.WriteLine("desolation,static,0x0C49,0x1B9D"); - writer.WriteLine("desolation,static,0x0CB6,0x1B9D"); - writer.WriteLine("desolation,static,0x0C45,0x1B9C"); - writer.WriteLine("desolation,static,0x0C48,0x1B9C"); - writer.WriteLine("desolation,static,0x0C4E,0x1B9C"); - writer.WriteLine("desolation,static,0x0C85,0x1B9C"); - writer.WriteLine("desolation,static,0x0CA7,0x1B9C"); - writer.WriteLine("desolation,static,0x0CAE,0x1B9C"); - writer.WriteLine("desolation,static,0x0CAF,0x1B9C"); - writer.WriteLine("desolation,static,0x0CB5,0x1B9C"); - writer.WriteLine("desolation,static,0x0D15,0x1B9C"); - writer.WriteLine("desolation,static,0x0D29,0x1B9C"); - writer.WriteLine("desolation,static,0x0C37,0x1BAE"); - writer.WriteLine("desolation,static,0x0C38,0x1BAE"); - writer.WriteLine("desolation,static,0x0C47,0x1BAE"); - writer.WriteLine("desolation,static,0x0C4A,0x1BAE"); - writer.WriteLine("desolation,static,0x0C4B,0x1BAE"); - writer.WriteLine("desolation,static,0x0C4D,0x1BAE"); - writer.WriteLine("desolation,static,0x0C8C,0x1BAE"); - writer.WriteLine("desolation,static,0x0C8D,0x1BAE"); - writer.WriteLine("desolation,static,0x0C93,0x1BAE"); - writer.WriteLine("desolation,static,0x0C94,0x1BAE"); - writer.WriteLine("desolation,static,0x0C98,0x1BAE"); - writer.WriteLine("desolation,static,0x0C9F,0x1BAE"); - writer.WriteLine("desolation,static,0x0CA0,0x1BAE"); - writer.WriteLine("desolation,static,0x0CA1,0x1BAE"); - writer.WriteLine("desolation,static,0x0CA2,0x1BAE"); - writer.WriteLine("desolation,static,0x0CA3,0x1BAE"); - writer.WriteLine("desolation,static,0x0CA4,0x1BAE"); - writer.WriteLine("desolation,static,0x0CB0,0x1BAE"); - writer.WriteLine("desolation,static,0x0CB1,0x1BAE"); - writer.WriteLine("desolation,static,0x0CB2,0x1BAE"); - writer.WriteLine("desolation,static,0x0CB3,0x1BAE"); - writer.WriteLine("desolation,static,0x0CB4,0x1BAE"); - writer.WriteLine("desolation,static,0x0CB7,0x1BAE"); - writer.WriteLine("desolation,static,0x0CC5,0x1BAE"); - writer.WriteLine("desolation,static,0x0D0C,0x1BAE"); - writer.WriteLine("desolation,static,0x0D0D,0x1BAE"); - writer.WriteLine("desolation,static,0x0D0E,0x1BAE"); - writer.WriteLine("desolation,static,0x0D10,0x1BAE"); - writer.WriteLine("desolation,static,0x0D12,0x1BAE"); - writer.WriteLine("desolation,static,0x0D13,0x1BAE"); - writer.WriteLine("desolation,static,0x0D18,0x1BAE"); - writer.WriteLine("desolation,static,0x0D19,0x1BAE"); - writer.WriteLine("desolation,static,0x0D2D,0x1BAE"); - writer.WriteLine("desolation,static,0x0D2F,0x1BAE"); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/SimpleAccountManager.cs b/src/ClassicUO.Client/Game/Managers/SimpleAccountManager.cs deleted file mode 100644 index 10e31f400..000000000 --- a/src/ClassicUO.Client/Game/Managers/SimpleAccountManager.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.Collections.Generic; -using System.IO; - -namespace ClassicUO.Game.Managers -{ - internal static class SimpleAccountManager - { - private static string accountPath = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Profiles"); - - public static string[] GetAccounts() - { - List accounts = new List(); - - if (Directory.Exists(accountPath)) - { - var dirs = Directory.GetDirectories(accountPath); - - foreach (var dir in dirs) - { - accounts.Add(Path.GetFileName(dir)); - } - } - return accounts.ToArray(); - } - } -} diff --git a/src/ClassicUO.Client/Game/Managers/SkillsGroupManager.cs b/src/ClassicUO.Client/Game/Managers/SkillsGroupManager.cs deleted file mode 100644 index 848ab4bdc..000000000 --- a/src/ClassicUO.Client/Game/Managers/SkillsGroupManager.cs +++ /dev/null @@ -1,575 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Xml; -using ClassicUO.Configuration; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.IO; -using ClassicUO.Assets; -using ClassicUO.Resources; -using ClassicUO.Utility.Logging; - -namespace ClassicUO.Game.Managers -{ - internal sealed class SkillsGroup - { - private readonly byte[] _list = new byte[60]; - - public SkillsGroup() - { - for (int i = 0; i < _list.Length; i++) - { - _list[i] = 0xFF; - } - } - - public SkillsGroup Left { get; set; } - public SkillsGroup Right { get; set; } - public int Count; - public bool IsMaximized; - public string Name = ResGeneral.NoName; - - public byte GetSkill(int index) - { - if (index < 0 || index >= Count) - { - return 0xFF; - } - - return _list[index]; - } - - public void Add(byte item) - { - if (!Contains(item)) - { - _list[Count++] = item; - } - } - - public void Remove(byte item) - { - bool removed = false; - - for (int i = 0; i < Count; i++) - { - if (_list[i] == item) - { - removed = true; - - for (; i < Count - 1; i++) - { - _list[i] = _list[i + 1]; - } - - break; - } - } - - if (removed) - { - Count--; - - if (Count < 0) - { - Count = 0; - } - - _list[Count] = 0xFF; - } - } - - public bool Contains(byte item) - { - for (int i = 0; i < Count; i++) - { - if (_list[i] == item) - { - return true; - } - } - - return false; - } - - public unsafe void Sort() - { - byte* table = stackalloc byte[60]; - int index = 0; - - int count = SkillsLoader.Instance.SkillsCount; - - for (int i = 0; i < count; i++) - { - for (int j = 0; j < Count; j++) - { - if (SkillsLoader.Instance.GetSortedIndex(i) == _list[j]) - { - table[index++] = _list[j]; - - break; - } - } - } - - for (int j = 0; j < Count; j++) - { - _list[j] = table[j]; - } - } - - public void TransferTo(SkillsGroup group) - { - for (int i = 0; i < Count; i++) - { - group.Add(_list[i]); - } - - group.Sort(); - } - - public void Save(XmlTextWriter xml) - { - xml.WriteStartElement("group"); - xml.WriteAttributeString("name", Name); - xml.WriteStartElement("skillids"); - - for (int i = 0; i < Count; i++) - { - byte idx = GetSkill(i); - - if (idx != 0xFF) - { - xml.WriteStartElement("skill"); - xml.WriteAttributeString("id", idx.ToString()); - xml.WriteEndElement(); - } - } - - xml.WriteEndElement(); - xml.WriteEndElement(); - } - } - - internal static class SkillsGroupManager - { - public static readonly List Groups = new List(); - - - public static void Add(SkillsGroup g) - { - Groups.Add(g); - } - - public static bool Remove(SkillsGroup g) - { - if (Groups[0] == g) - { - var camera = Client.Game.Scene.Camera; - - MessageBoxGump messageBox = new MessageBoxGump(200, 125, ResGeneral.CannotDeleteThisGroup, null) - { - X = camera.Bounds.X + camera.Bounds.Width / 2 - 100, - Y = camera.Bounds.Y + camera.Bounds.Height / 2 - 62 - }; - - UIManager.Add(messageBox); - - return false; - } - - Groups.Remove(g); - g.TransferTo(Groups[0]); - - return true; - } - - public static void Load() - { - Groups.Clear(); - - string path = Path.Combine(ProfileManager.ProfilePath, "skillsgroups.xml"); - - if (!File.Exists(path)) - { - Log.Trace("No skillsgroups.xml file. Creating a default file."); - - MakeDefault(); - - return; - } - - XmlDocument doc = new XmlDocument(); - - try - { - doc.Load(path); - } - catch (Exception ex) - { - MakeDefault(); - - Log.Error(ex.ToString()); - - return; - } - - XmlElement root = doc["skillsgroups"]; - - if (root != null) - { - foreach (XmlElement xml in root.GetElementsByTagName("group")) - { - SkillsGroup g = new SkillsGroup(); - g.Name = xml.GetAttribute("name"); - - XmlElement xmlIdsRoot = xml["skillids"]; - - if (xmlIdsRoot != null) - { - foreach (XmlElement xmlIds in xmlIdsRoot.GetElementsByTagName("skill")) - { - g.Add(byte.Parse(xmlIds.GetAttribute("id"))); - } - } - - g.Sort(); - Add(g); - } - } - } - - - public static void Save() - { - string path = Path.Combine(ProfileManager.ProfilePath, "skillsgroups.xml"); - - using (XmlTextWriter xml = new XmlTextWriter(path, Encoding.UTF8) - { - Formatting = Formatting.Indented, - IndentChar = '\t', - Indentation = 1 - }) - { - xml.WriteStartDocument(true); - xml.WriteStartElement("skillsgroups"); - - foreach (SkillsGroup k in Groups) - { - k.Save(xml); - } - - xml.WriteEndElement(); - xml.WriteEndDocument(); - } - } - - - public static void MakeDefault() - { - Groups.Clear(); - - if (!LoadMULFile(UOFileManager.GetUOFilePath("skillgrp.mul"))) - { - MakeDefaultMiscellaneous(); - MakeDefaultCombat(); - MakeDefaultTradeSkills(); - MakeDefaultMagic(); - MakeDefaultWilderness(); - MakeDefaultThieving(); - MakeDefaultBard(); - } - - foreach (SkillsGroup g in Groups) - { - g.Sort(); - } - - Save(); - } - - private static void MakeDefaultMiscellaneous() - { - SkillsGroup g = new SkillsGroup(); - g.Name = ResGeneral.Miscellaneous; - g.Add(4); - g.Add(6); - g.Add(10); - g.Add(12); - g.Add(19); - g.Add(3); - g.Add(36); - - Add(g); - } - - private static void MakeDefaultCombat() - { - int count = SkillsLoader.Instance.SkillsCount; - - SkillsGroup g = new SkillsGroup(); - g.Name = ResGeneral.Combat; - g.Add(1); - g.Add(31); - g.Add(42); - g.Add(17); - g.Add(41); - g.Add(5); - g.Add(40); - g.Add(27); - - if (count > 57) - { - g.Add(57); - } - - g.Add(43); - - if (count > 50) - { - g.Add(50); - } - - if (count > 51) - { - g.Add(51); - } - - if (count > 52) - { - g.Add(52); - } - - if (count > 53) - { - g.Add(53); - } - - Add(g); - } - - private static void MakeDefaultTradeSkills() - { - SkillsGroup g = new SkillsGroup(); - g.Name = ResGeneral.TradeSkills; - g.Add(0); - g.Add(7); - g.Add(8); - g.Add(11); - g.Add(13); - g.Add(23); - g.Add(44); - g.Add(45); - g.Add(34); - g.Add(37); - - Add(g); - } - - private static void MakeDefaultMagic() - { - int count = SkillsLoader.Instance.SkillsCount; - - SkillsGroup g = new SkillsGroup(); - g.Name = ResGeneral.Magic; - g.Add(16); - - if (count > 56) - { - g.Add(56); - } - - g.Add(25); - g.Add(46); - - if (count > 55) - { - g.Add(55); - } - - g.Add(26); - - if (count > 54) - { - g.Add(54); - } - - g.Add(32); - - if (count > 49) - { - g.Add(49); - } - - Add(g); - } - - private static void MakeDefaultWilderness() - { - SkillsGroup g = new SkillsGroup(); - g.Name = ResGeneral.Wilderness; - g.Add(2); - g.Add(35); - g.Add(18); - g.Add(20); - g.Add(38); - g.Add(39); - - Add(g); - } - - private static void MakeDefaultThieving() - { - SkillsGroup g = new SkillsGroup(); - g.Name = ResGeneral.Thieving; - g.Add(14); - g.Add(21); - g.Add(24); - g.Add(30); - g.Add(48); - g.Add(28); - g.Add(33); - g.Add(47); - - Add(g); - } - - private static void MakeDefaultBard() - { - SkillsGroup g = new SkillsGroup(); - g.Name = ResGeneral.Bard; - g.Add(15); - g.Add(29); - g.Add(9); - g.Add(22); - - Add(g); - } - - private static bool LoadMULFile(string path) - { - FileInfo info = new FileInfo(path); - - if (!info.Exists) - { - return false; - } - - try - { - byte skillidx = 0; - bool unicode = false; - - using (BinaryReader bin = new BinaryReader(File.OpenRead(info.FullName))) - { - int start = 4; - int strlen = 17; - int count = bin.ReadInt32(); - - if (count == -1) - { - unicode = true; - count = bin.ReadInt32(); - start *= 2; - strlen *= 2; - } - - - StringBuilder sb = new StringBuilder(17); - - SkillsGroup g = new SkillsGroup(); - g.Name = ResGeneral.Miscellaneous; - - SkillsGroup[] groups = new SkillsGroup[count]; - groups[0] = g; - - for (int i = 0; i < count - 1; ++i) - { - short strbuild; - bin.BaseStream.Seek(start + i * strlen, SeekOrigin.Begin); - - if (unicode) - { - while ((strbuild = bin.ReadInt16()) != 0) - { - sb.Append((char) strbuild); - } - } - else - { - while ((strbuild = bin.ReadByte()) != 0) - { - sb.Append((char) strbuild); - } - } - - groups[i + 1] = new SkillsGroup - { - Name = sb.ToString() - }; - - sb.Clear(); - } - - bin.BaseStream.Seek(start + (count - 1) * strlen, SeekOrigin.Begin); - - while (bin.BaseStream.Length != bin.BaseStream.Position) - { - int grp = bin.ReadInt32(); - - if (grp < groups.Length && skillidx < SkillsLoader.Instance.SkillsCount) - { - groups[grp].Add(skillidx++); - } - } - - for (int i = 0; i < groups.Length; i++) - { - Add(groups[i]); - } - } - } - catch (Exception e) - { - Log.Error($"Error while reading skillgrp.mul, using CUO defaults! exception given is: {e}"); - - return false; - } - - return Groups.Count != 0; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/SpellVisualRangeManager.cs b/src/ClassicUO.Client/Game/Managers/SpellVisualRangeManager.cs deleted file mode 100644 index 729959fa6..000000000 --- a/src/ClassicUO.Client/Game/Managers/SpellVisualRangeManager.cs +++ /dev/null @@ -1,528 +0,0 @@ -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text.Json; -using System.Threading.Tasks; - -namespace ClassicUO.Game.Managers -{ - internal class SpellVisualRangeManager - { - public static SpellVisualRangeManager Instance => instance ??= new SpellVisualRangeManager(); - - public Vector2 LastCursorTileLoc { get; set; } = Vector2.Zero; - public DateTime LastSpellTime { get; private set; } = DateTime.Now; - - private string savePath = Path.Combine(CUOEnviroment.ExecutablePath ?? "", "Data", "Profiles", "SpellVisualRange.json"); - private string overridePath = Path.Combine(ProfileManager.ProfilePath ?? "", "SpellVisualRange.json"); - - private Dictionary spellRangeCache = new Dictionary(); - private Dictionary spellRangeOverrideCache = new Dictionary(); - private Dictionary spellRangePowerWordCache = new Dictionary(); - - private bool loaded = false; - private static SpellVisualRangeManager instance; - - private bool isCasting { get; set; } = false; - private SpellRangeInfo currentSpell { get; set; } - - //Taken from Dust client - private static readonly int[] stopAtClilocs = new int[] - { - 500641, // Your concentration is disturbed, thus ruining thy spell. - 502625, // Insufficient mana. You must have at least ~1_MANA_REQUIREMENT~ Mana to use this spell. - 502630, // More reagents are needed for this spell. - 500946, // You cannot cast this in town! - 500015, // You do not have that spell - 502643, // You can not cast a spell while frozen. - 1061091, // You cannot cast that spell in this form. - 502644, // You have not yet recovered from casting a spell. - 1072060, // You cannot cast a spell while calmed. - }; - - private SpellVisualRangeManager() - { - Load(); - } - - private void OnRawMessageReceived(object sender, MessageEventArgs e) - { - Task.Factory.StartNew(() => - { - if (loaded && e.Parent != null && ReferenceEquals(e.Parent, World.Player)) - { - if (spellRangePowerWordCache.TryGetValue(e.Text.Trim(), out SpellRangeInfo spell)) - { - SetCasting(spell); - } - } - }); - } - - public void OnClilocReceived(int cliloc) - { - Task.Factory.StartNew(() => - { - if (isCasting && stopAtClilocs.Contains(cliloc)) - { - ClearCasting(); - } - }); - } - - private void SetCasting(SpellRangeInfo spell) - { - LastSpellTime = DateTime.Now; - currentSpell = spell; - isCasting = true; - if (currentSpell != null && currentSpell.FreezeCharacterWhileCasting) - { - World.Player.Flags |= Flags.Frozen; - } - } - - public void ClearCasting() - { - isCasting = false; - currentSpell = null; - LastSpellTime = DateTime.MinValue; - World.Player.Flags &= ~Flags.Frozen; - } - - public SpellRangeInfo GetCurrentSpell() - { - return currentSpell; - } - - #region Load and unload - public void OnSceneLoad() - { - EventSink.RawMessageReceived += OnRawMessageReceived; - } - - public void OnSceneUnload() - { - EventSink.RawMessageReceived -= OnRawMessageReceived; - instance = null; - } - #endregion - - public bool IsTargetingAfterCasting() - { - if (!loaded || currentSpell == null || !isCasting || ProfileManager.CurrentProfile == null || !ProfileManager.CurrentProfile.EnableSpellIndicators) - { - return false; - } - - if (TargetManager.IsTargeting || (currentSpell.ShowCastRangeDuringCasting && IsCastingWithoutTarget())) - { - if (LastSpellTime + TimeSpan.FromSeconds(currentSpell.MaxDuration) > DateTime.Now) - { - return true; - } - } - - return false; - } - - public bool IsCastingWithoutTarget() - { - if (!loaded || currentSpell == null || !isCasting || currentSpell.CastTime <= 0 || TargetManager.IsTargeting || ProfileManager.CurrentProfile == null || !ProfileManager.CurrentProfile.EnableSpellIndicators) - { - return false; - } - - if (LastSpellTime + TimeSpan.FromSeconds(currentSpell.MaxDuration) > DateTime.Now) - { - if (LastSpellTime + TimeSpan.FromSeconds(currentSpell.CastTime) > DateTime.Now) - { - return true; - } - else if (currentSpell.FreezeCharacterWhileCasting) - { - World.Player.Flags &= ~Flags.Frozen; - } - } - else if (currentSpell.FreezeCharacterWhileCasting) - { - World.Player.Flags &= ~Flags.Frozen; - } - - return false; - } - - public ushort ProcessHueForTile(ushort hue, GameObject o) - { - if (!loaded || currentSpell == null) { return hue; } - - if (currentSpell.CastRange > 0 && o.Distance <= currentSpell.CastRange) - { - hue = currentSpell.Hue; - } - - int cDistance = o.DistanceFrom(LastCursorTileLoc); - - if (currentSpell.CursorSize > 0 && cDistance < currentSpell.CursorSize) - { - if (currentSpell.IsLinear) - { - if (GetDirection(new Vector2(World.Player.X, World.Player.Y), LastCursorTileLoc) == SpellDirection.EastWest) - { //X - if (o.Y == LastCursorTileLoc.Y) - { - hue = currentSpell.CursorHue; - } - } - else - { //Y - if (o.X == LastCursorTileLoc.X) - { - hue = currentSpell.CursorHue; - } - } - } - else - { - hue = currentSpell.CursorHue; - } - } - - return hue; - } - - private static SpellDirection GetDirection(Vector2 from, Vector2 to) - { - int dx = (int)(from.X - to.X); - int dy = (int)(from.Y - to.Y); - int rx = (dx - dy) * 44; - int ry = (dx + dy) * 44; - - if (rx >= 0 && ry >= 0) - { - return SpellDirection.SouthNorth; - } - else if (rx >= 0) - { - return SpellDirection.EastWest; - } - else if (ry >= 0) - { - return SpellDirection.EastWest; - } - else - { - return SpellDirection.SouthNorth; - } - } - - #region Save and load - private void Load() - { - spellRangeCache.Clear(); - Task.Factory.StartNew(() => - { - if (!File.Exists(savePath)) - { - CreateAndLoadDataFile(); - AfterLoad(); - loaded = true; - } - else - { - try - { - string data = File.ReadAllText(savePath); - SpellRangeInfo[] fileData = JsonSerializer.Deserialize(data); - - foreach (var entry in fileData) - { - spellRangeCache.Add(entry.ID, entry); - } - AfterLoad(); - loaded = true; - } - catch - { - CreateAndLoadDataFile(); - AfterLoad(); - loaded = true; - } - - } - }); - } - - private void LoadOverrides() - { - spellRangeOverrideCache.Clear(); - - if (File.Exists(overridePath)) - { - try - { - string data = File.ReadAllText(overridePath); - SpellRangeInfo[] fileData = JsonSerializer.Deserialize(data); - - foreach (var entry in fileData) - { - spellRangeOverrideCache.Add(entry.ID, entry); - } - - foreach (var entry in spellRangeOverrideCache.Values) - { - if (string.IsNullOrEmpty(entry.PowerWords)) - { - SpellDefinition spellD = SpellDefinition.FullIndexGetSpell(entry.ID); - if (spellD == SpellDefinition.EmptySpell) - { - SpellDefinition.TryGetSpellFromName(entry.Name, out spellD); - } - - if (spellD != SpellDefinition.EmptySpell) - { - entry.PowerWords = spellD.PowerWords; - } - } - if (!string.IsNullOrEmpty(entry.PowerWords)) - { - if (spellRangePowerWordCache.ContainsKey(entry.PowerWords)) - { - spellRangePowerWordCache[entry.PowerWords] = entry; - } - else - { - spellRangePowerWordCache.Add(entry.PowerWords, entry); - } - } - } - } - catch (Exception e) - { - Console.WriteLine(e.ToString()); - } - } - } - - public bool LoadFromString(string json) - { - try - { - SpellRangeInfo[] fileData = JsonSerializer.Deserialize(json); - - loaded = false; - spellRangeCache.Clear(); - - foreach (var entry in fileData) - { - spellRangeCache.Add(entry.ID, entry); - } - AfterLoad(); - LoadOverrides(); - loaded = true; - return true; - } - catch (Exception ex) - { - loaded = true; - Console.WriteLine(ex.ToString()); - return false; - } - } - - private void AfterLoad() - { - spellRangePowerWordCache.Clear(); - foreach (var entry in spellRangeCache.Values) - { - if (string.IsNullOrEmpty(entry.PowerWords)) - { - SpellDefinition spellD = SpellDefinition.FullIndexGetSpell(entry.ID); - if (spellD == SpellDefinition.EmptySpell) - { - SpellDefinition.TryGetSpellFromName(entry.Name, out spellD); - } - - if (spellD != SpellDefinition.EmptySpell) - { - entry.PowerWords = spellD.PowerWords; - } - } - if (!string.IsNullOrEmpty(entry.PowerWords)) - { - spellRangePowerWordCache.Add(entry.PowerWords, entry); - } - } - LoadOverrides(); - } - - private void CreateAndLoadDataFile() - { - foreach (var entry in SpellsMagery.GetAllSpells) - { - spellRangeCache.Add(entry.Value.ID, SpellRangeInfo.FromSpellDef(entry.Value)); - } - foreach (var entry in SpellsNecromancy.GetAllSpells) - { - spellRangeCache.Add(entry.Value.ID, SpellRangeInfo.FromSpellDef(entry.Value)); - } - foreach (var entry in SpellsChivalry.GetAllSpells) - { - spellRangeCache.Add(entry.Value.ID, SpellRangeInfo.FromSpellDef(entry.Value)); - } - foreach (var entry in SpellsBushido.GetAllSpells) - { - spellRangeCache.Add(entry.Value.ID, SpellRangeInfo.FromSpellDef(entry.Value)); - } - foreach (var entry in SpellsNinjitsu.GetAllSpells) - { - spellRangeCache.Add(entry.Value.ID, SpellRangeInfo.FromSpellDef(entry.Value)); - } - foreach (var entry in SpellsSpellweaving.GetAllSpells) - { - spellRangeCache.Add(entry.Value.ID, SpellRangeInfo.FromSpellDef(entry.Value)); - } - foreach (var entry in SpellsMysticism.GetAllSpells) - { - spellRangeCache.Add(entry.Value.ID, SpellRangeInfo.FromSpellDef(entry.Value)); - } - foreach (var entry in SpellsMastery.GetAllSpells) - { - spellRangeCache.Add(entry.Value.ID, SpellRangeInfo.FromSpellDef(entry.Value)); - } - - Task.Factory.StartNew(() => - { - Save(); - }); - } - - public void Save() - { - try - { - var options = new JsonSerializerOptions() { WriteIndented = true }; - string fileData = JsonSerializer.Serialize(spellRangeCache.Values.ToArray(), options); - File.WriteAllText(savePath, fileData); - } - catch (Exception e) { Console.WriteLine(e.ToString()); } - } - #endregion - - private enum SpellDirection - { - EastWest, - SouthNorth - } - - public class SpellRangeInfo - { - public int ID { get; set; } = -1; - public string Name { get; set; } = ""; - public string PowerWords { get; set; } = ""; - public int CursorSize { get; set; } = 0; - public int CastRange { get; set; } = 1; - public ushort Hue { get; set; } = 32; - public ushort CursorHue { get; set; } = 10; - public int MaxDuration { get; set; } = 10; - public bool IsLinear { get; set; } = false; - public double CastTime { get; set; } = 0.0; - public bool ShowCastRangeDuringCasting { get; set; } = false; - public bool FreezeCharacterWhileCasting { get; set; } = false; - - public static SpellRangeInfo FromSpellDef(SpellDefinition spell) - { - return new SpellRangeInfo() { ID = spell.ID, Name = spell.Name, PowerWords = spell.PowerWords }; - } - } - - #region Cast Timer Bar - - - public class CastTimerProgressBar : Gump - { - private Rectangle barBounds, barBoundsF; - private Texture2D background; - private Texture2D foreground; - private Vector3 hue = ShaderHueTranslator.GetHueVector(0); - - - public CastTimerProgressBar() : base(0, 0) - { - CanMove = false; - AcceptMouseInput = false; - CanCloseWithEsc = false; - CanCloseWithRightClick = false; - - ref readonly var gi = ref Client.Game.Gumps.GetGump(0x0805); - background = gi.Texture; - barBounds = gi.UV; - - gi = ref Client.Game.Gumps.GetGump(0x0806); - foreground = gi.Texture; - barBoundsF = gi.UV; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (SpellVisualRangeManager.Instance.IsCastingWithoutTarget()) - { - SpellRangeInfo i = SpellVisualRangeManager.Instance.GetCurrentSpell(); - if (i != null) - { - if (i.CastTime > 0) - { - if (background != null && foreground != null) - { - Mobile m = World.Player; - Client.Game.Animations.GetAnimationDimensions( - m.AnimIndex, - m.GetGraphicForAnimation(), - 0, - 0, - m.IsMounted, - 0, - out int centerX, - out int centerY, - out int width, - out int height - ); - - WorldViewportGump vp = UIManager.GetGump(); - - x = vp.Location.X + (int)(m.RealScreenPosition.X - (m.Offset.X + 22 + 5)); - y = vp.Location.Y + (int)(m.RealScreenPosition.Y - ((m.Offset.Y - m.Offset.Z) - (height + centerY + 15) + (m.IsGargoyle && m.IsFlying ? -22 : !m.IsMounted ? 22 : 0))); - - batcher.Draw(background, new Rectangle(x, y, barBounds.Width, barBounds.Height), barBounds, hue); - - double percent = (DateTime.Now - SpellVisualRangeManager.Instance.LastSpellTime).TotalSeconds / i.CastTime; - - int widthFromPercent = (int)(barBounds.Width * percent); - widthFromPercent = widthFromPercent > barBounds.Width ? barBounds.Width : widthFromPercent; //Max width is the bar width - - if (widthFromPercent > 0) - { - batcher.DrawTiled(foreground, new Rectangle(x, y, widthFromPercent, barBoundsF.Height), barBoundsF, hue); - } - - if (percent <= 0 && i.FreezeCharacterWhileCasting) - { - World.Player.Flags &= ~Flags.Frozen; - } - } - } - } - } - return base.Draw(batcher, x, y); - } - } - #endregion - } -} diff --git a/src/ClassicUO.Client/Game/Managers/Stitchin.cs b/src/ClassicUO.Client/Game/Managers/Stitchin.cs deleted file mode 100644 index 350641d2d..000000000 --- a/src/ClassicUO.Client/Game/Managers/Stitchin.cs +++ /dev/null @@ -1,146 +0,0 @@ -using ClassicUO.Assets; -using ClassicUO.Game.Data; -using ClassicUO.IO; -using ClassicUO.Utility.Logging; -using System; -using System.Collections.Generic; -using System.IO; - -namespace ClassicUO.Game.Managers -{ - sealed class Stitchin - { - private readonly static char[] _split = new char[] { ' ', '\t' }; - - public void Read() - { - var filePath = UOFileManager.GetUOFilePath("stitchin.def"); - - if (!File.Exists(filePath)) - { - return; - } - - const string END_DEF = "# enddef"; - - using (var reader = new StreamReader(File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) - { - var list = new List(); - var started = false; - - while (!reader.EndOfStream) - { - var line = reader.ReadLine(); - - if (string.IsNullOrWhiteSpace(line) || line.StartsWith("//")) - { - continue; - } - - if (!started && line.StartsWith("# ") && !line.StartsWith(END_DEF)) - { - started = true; - } - - if (started) - { - list.Add(line); - } - - if (started && line.StartsWith(END_DEF)) - { - Work(list); - - list.Clear(); - } - } - } - } - - private void Work(List list) - { - if (list == null || list.Count == 0) - { - return; - } - - foreach (var line in list) - { - var args = line.Split(_split, StringSplitOptions.RemoveEmptyEntries); - - BuildCommand(args); - } - } - - private void BuildCommand(string[] arguments) - { - if (arguments== null || arguments.Length == 0) - { - return; - } - - var cmd = arguments[0]; - - switch (cmd) - { - // coveredBy LAYER0 LAYER1 .... - case "coveredBy": - - for (int i = 1; i < arguments.Length; ++i) - { - var layer = GetLayer(arguments[i]); - } - - break; - - // covers LAYER0 LAYER1 .... - case "covers": - - for (int i = 1; i < arguments.Length; ++i) - { - var layer = GetLayer(arguments[i]); - } - - break; - - // replace XXX with YYY - case "replace" when arguments.Length == 4: - var item0 = arguments[1]; - var item1 = arguments[3]; - break; - - // remove XXX YYY ZZZ ... - case "remove": - - break; - } - } - - private Layer? GetLayer(string layerName) - { - switch (layerName.ToUpper()) - { - case "HEAD": return Layer.Helmet; - case "FACE": return Layer.Face; - case "EARS": return Layer.Earrings; - case "NECK": return Layer.Necklace; - case "TORSO": return Layer.Torso; - case "UPPER_ARMS_TOP": return Layer.Invalid; - case "UPPER_ARMS_BOTTOM": return Layer.Invalid; - case "LOWER_ARMS_TOP": return Layer.Invalid; - case "LOWER_ARMS_BOTTOM": return Layer.Invalid; - case "HANDS": return Layer.Gloves; - case "PELVIS": return Layer.Waist; - case "UPPER_LEGS_TOP": return Layer.Invalid; - case "UPPER_LEGS_BOTTOM": return Layer.Invalid; - case "LOWER_LEGS_TOP": return Layer.Invalid; - case "LOWER_LEGS_BOTTOM": return Layer.Invalid; - case "FEET": return Layer.Shoes; - } - - Log.Warn($"layer not handled: {layerName}"); - - return null; - } - } -} diff --git a/src/ClassicUO.Client/Game/Managers/TargetManager.cs b/src/ClassicUO.Client/Game/Managers/TargetManager.cs deleted file mode 100644 index 4852dbc42..000000000 --- a/src/ClassicUO.Client/Game/Managers/TargetManager.cs +++ /dev/null @@ -1,569 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Network; -using ClassicUO.Resources; -using ClassicUO.Utility; - -namespace ClassicUO.Game.Managers -{ - public enum CursorTarget - { - Invalid = -1, - Object = 0, - Position = 1, - MultiPlacement = 2, - SetTargetClientSide = 3, - Grab, - SetGrabBag, - HueCommandTarget, - IgnorePlayerTarget, - MoveItemContainer, - Internal - } - - public class CursorType - { - public static readonly uint Target = 6983686; - } - - public enum TargetType - { - Neutral, - Harmful, - Beneficial, - Cancel - } - - public class MultiTargetInfo - { - public MultiTargetInfo(ushort model, ushort x, ushort y, ushort z, ushort hue) - { - Model = model; - XOff = x; - YOff = y; - ZOff = z; - Hue = hue; - } - - public readonly ushort XOff, YOff, ZOff, Model, Hue; - } - - public class LastTargetInfo - { - public bool IsEntity => SerialHelper.IsValid(Serial); - public bool IsStatic => !IsEntity && Graphic != 0 && Graphic != 0xFFFF; - public bool IsLand => !IsStatic; - public ushort Graphic; - public uint Serial; - public ushort X, Y; - public sbyte Z; - - - public void SetEntity(uint serial) - { - Serial = serial; - Graphic = 0xFFFF; - X = Y = 0xFFFF; - Z = sbyte.MinValue; - } - - public void SetStatic(ushort graphic, ushort x, ushort y, sbyte z) - { - Serial = 0; - Graphic = graphic; - X = x; - Y = y; - Z = z; - } - - public void SetLand(ushort x, ushort y, sbyte z) - { - Serial = 0; - Graphic = 0xFFFF; - X = x; - Y = y; - Z = z; - } - - public void Clear() - { - Serial = 0; - Graphic = 0xFFFF; - X = Y = 0xFFFF; - Z = sbyte.MinValue; - } - } - - public static class TargetManager - { - private static uint _targetCursorId, _lastAttack; - private static readonly byte[] _lastDataBuffer = new byte[19]; - - public static uint SelectedTarget; - - public static uint LastAttack - { - get { return _lastAttack; } - set - { - _lastAttack = value; - if (ProfileManager.CurrentProfile != null && ProfileManager.CurrentProfile.OpenHealthBarForLastAttack) - { - if (ProfileManager.CurrentProfile.UseOneHPBarForLastAttack) - { - if (BaseHealthBarGump.LastAttackBar != null && !BaseHealthBarGump.LastAttackBar.IsDisposed) - { - if (BaseHealthBarGump.LastAttackBar.LocalSerial != value) - { - BaseHealthBarGump.LastAttackBar.SetNewMobile(value); - } - } - else - { - if (ProfileManager.CurrentProfile.CustomBarsToggled) - UIManager.Add(BaseHealthBarGump.LastAttackBar = new HealthBarGumpCustom(value) { Location = ProfileManager.CurrentProfile.LastTargetHealthBarPos, IsLastTarget = true }); - else - UIManager.Add(BaseHealthBarGump.LastAttackBar = new HealthBarGump(value) { Location = ProfileManager.CurrentProfile.LastTargetHealthBarPos, IsLastTarget = true }); - } - } - else - { - if (UIManager.GetGump(value) == null) - { - if (ProfileManager.CurrentProfile.CustomBarsToggled) - UIManager.Add(new HealthBarGumpCustom(value) { Location = ProfileManager.CurrentProfile.LastTargetHealthBarPos, IsLastTarget = true }); - else - UIManager.Add(new HealthBarGump(value) { Location = ProfileManager.CurrentProfile.LastTargetHealthBarPos, IsLastTarget = true }); - } - } - } - } - } - - public static readonly LastTargetInfo LastTargetInfo = new LastTargetInfo(); - - - public static MultiTargetInfo MultiTargetInfo { get; private set; } - - public static CursorTarget TargetingState { get; private set; } = CursorTarget.Invalid; - - public static bool IsTargeting { get; private set; } - - public static TargetType TargetingType { get; private set; } - - private static void ClearTargetingWithoutTargetCancelPacket() - { - if (TargetingState == CursorTarget.MultiPlacement) - { - MultiTargetInfo = null; - TargetingState = 0; - World.HouseManager.Remove(0); - } - - IsTargeting = false; - } - - public static void Reset() - { - ClearTargetingWithoutTargetCancelPacket(); - - TargetingState = 0; - _targetCursorId = 0; - MultiTargetInfo = null; - TargetingType = 0; - } - - public static void SetTargeting(CursorTarget targeting, uint cursorID, TargetType cursorType) - { - if (targeting == CursorTarget.Invalid) - { - return; - } - - bool lastTargetting = IsTargeting; - IsTargeting = cursorType < TargetType.Cancel; - TargetingState = targeting; - TargetingType = cursorType; - - if (IsTargeting) - { - //UIManager.RemoveTargetLineGump(LastTarget); - } - else if (lastTargetting) - { - CancelTarget(); - } - - // https://github.com/andreakarasho/ClassicUO/issues/1373 - // when receiving a cancellation target from the server we need - // to send the last active cursorID, so update cursor data later - - _targetCursorId = cursorID; - } - - - public static void CancelTarget() - { - if (TargetingState == CursorTarget.MultiPlacement) - { - World.HouseManager.Remove(0); - - if (World.CustomHouseManager != null) - { - World.CustomHouseManager.Erasing = false; - World.CustomHouseManager.SeekTile = false; - World.CustomHouseManager.SelectedGraphic = 0; - World.CustomHouseManager.CombinedStair = false; - - UIManager.GetGump()?.Update(); - } - } - - if (IsTargeting || TargetingType == TargetType.Cancel) - { - NetClient.Socket.Send_TargetCancel(TargetingState, _targetCursorId, (byte)TargetingType); - IsTargeting = false; - } - - Reset(); - } - - public static void SetTargetingMulti - ( - uint deedSerial, - ushort model, - ushort x, - ushort y, - ushort z, - ushort hue - ) - { - SetTargeting(CursorTarget.MultiPlacement, deedSerial, TargetType.Neutral); - - //if (model != 0) - MultiTargetInfo = new MultiTargetInfo - ( - model, - x, - y, - z, - hue - ); - } - - - public static void Target(uint serial) - { - if (!IsTargeting) - { - return; - } - - Entity entity = World.InGame ? World.Get(serial) : null; - - if (entity != null) - { - switch (TargetingState) - { - case CursorTarget.Invalid: return; - - case CursorTarget.Internal: - case CursorTarget.MultiPlacement: - case CursorTarget.Position: - case CursorTarget.Object: - case CursorTarget.HueCommandTarget: - case CursorTarget.SetTargetClientSide: - - if (TargetingState != CursorTarget.Internal && entity != World.Player) - { - LastTargetInfo.SetEntity(serial); - } - - if (SerialHelper.IsMobile(serial) && serial != World.Player && (World.Player.NotorietyFlag == NotorietyFlag.Innocent || World.Player.NotorietyFlag == NotorietyFlag.Ally)) - { - Mobile mobile = entity as Mobile; - - if (mobile != null) - { - bool showCriminalQuery = false; - - if (TargetingType == TargetType.Harmful && ProfileManager.CurrentProfile.EnabledCriminalActionQuery && mobile.NotorietyFlag == NotorietyFlag.Innocent) - { - showCriminalQuery = true; - } - else if (TargetingType == TargetType.Beneficial && ProfileManager.CurrentProfile.EnabledBeneficialCriminalActionQuery && (mobile.NotorietyFlag == NotorietyFlag.Criminal || mobile.NotorietyFlag == NotorietyFlag.Murderer || mobile.NotorietyFlag == NotorietyFlag.Gray)) - { - showCriminalQuery = true; - } - - if (showCriminalQuery && UIManager.GetGump() == null) - { - QuestionGump messageBox = new QuestionGump - ( - "This may flag\nyou criminal!", - s => - { - if (s) - { - NetClient.Socket.Send_TargetObject(entity, - entity.Graphic, - entity.X, - entity.Y, - entity.Z, - _targetCursorId, - (byte)TargetingType); - - ClearTargetingWithoutTargetCancelPacket(); - - if (LastTargetInfo.Serial != serial) - { - GameActions.RequestMobileStatus(serial); - } - } - } - ); - - UIManager.Add(messageBox); - - return; - } - } - } - - if (TargetingState != CursorTarget.SetTargetClientSide && TargetingState != CursorTarget.Internal) - { - _lastDataBuffer[0] = 0x6C; - - _lastDataBuffer[1] = 0x00; - - _lastDataBuffer[2] = (byte)(_targetCursorId >> 24); - _lastDataBuffer[3] = (byte)(_targetCursorId >> 16); - _lastDataBuffer[4] = (byte)(_targetCursorId >> 8); - _lastDataBuffer[5] = (byte)_targetCursorId; - - _lastDataBuffer[6] = (byte)TargetingType; - - _lastDataBuffer[7] = (byte)(entity.Serial >> 24); - _lastDataBuffer[8] = (byte)(entity.Serial >> 16); - _lastDataBuffer[9] = (byte)(entity.Serial >> 8); - _lastDataBuffer[10] = (byte)entity.Serial; - - _lastDataBuffer[11] = (byte)(entity.X >> 8); - _lastDataBuffer[12] = (byte)entity.X; - - _lastDataBuffer[13] = (byte)(entity.Y >> 8); - _lastDataBuffer[14] = (byte)entity.Y; - - _lastDataBuffer[15] = (byte)(entity.Z >> 8); - _lastDataBuffer[16] = (byte)entity.Z; - - _lastDataBuffer[17] = (byte)(entity.Graphic >> 8); - _lastDataBuffer[18] = (byte)entity.Graphic; - - - NetClient.Socket.Send_TargetObject(entity, - entity.Graphic, - entity.X, - entity.Y, - entity.Z, - _targetCursorId, - (byte)TargetingType); - - if (SerialHelper.IsMobile(serial) && LastTargetInfo.Serial != serial) - { - GameActions.RequestMobileStatus(serial); - } - } - - ClearTargetingWithoutTargetCancelPacket(); - - Mouse.CancelDoubleClick = true; - - break; - - case CursorTarget.Grab: - - if (SerialHelper.IsItem(serial)) - { - GameActions.GrabItem(serial, ((Item)entity).Amount); - } - - ClearTargetingWithoutTargetCancelPacket(); - - return; - - case CursorTarget.SetGrabBag: - - if (SerialHelper.IsItem(serial)) - { - ProfileManager.CurrentProfile.GrabBagSerial = serial; - GameActions.Print(string.Format(ResGeneral.GrabBagSet0, serial)); - } - - ClearTargetingWithoutTargetCancelPacket(); - - return; - case CursorTarget.IgnorePlayerTarget: - if (SelectedObject.Object is Entity pmEntity) - { - IgnoreManager.AddIgnoredTarget(pmEntity); - } - CancelTarget(); - return; - case CursorTarget.MoveItemContainer: - if (SerialHelper.IsItem(serial)) - { - MultiItemMoveGump.OnContainerTarget(serial); - } - ClearTargetingWithoutTargetCancelPacket(); - return; - } - } - } - - public static void Target(ushort graphic, ushort x, ushort y, short z, bool wet = false) - { - if (!IsTargeting) - { - return; - } - - if (graphic == 0) - { - if (TargetingState == CursorTarget.Object) - { - return; - } - } - else - { - if (graphic >= TileDataLoader.Instance.StaticData.Length) - { - return; - } - - ref StaticTiles itemData = ref TileDataLoader.Instance.StaticData[graphic]; - - if (Client.Version >= ClientVersion.CV_7090 && itemData.IsSurface) - { - z += itemData.Height; - } - } - - LastTargetInfo.SetStatic(graphic, x, y, (sbyte)z); - - TargetPacket(graphic, x, y, (sbyte)z); - } - - public static void SendMultiTarget(ushort x, ushort y, sbyte z) - { - TargetPacket(0, x, y, z); - MultiTargetInfo = null; - } - - public static void TargetLast() - { - if (!IsTargeting) - { - return; - } - - _lastDataBuffer[0] = 0x6C; - _lastDataBuffer[1] = (byte)TargetingState; - _lastDataBuffer[2] = (byte)(_targetCursorId >> 24); - _lastDataBuffer[3] = (byte)(_targetCursorId >> 16); - _lastDataBuffer[4] = (byte)(_targetCursorId >> 8); - _lastDataBuffer[5] = (byte)_targetCursorId; - _lastDataBuffer[6] = (byte)TargetingType; - - NetClient.Socket.Send(_lastDataBuffer); - Mouse.CancelDoubleClick = true; - ClearTargetingWithoutTargetCancelPacket(); - } - - private static void TargetPacket(ushort graphic, ushort x, ushort y, sbyte z) - { - if (!IsTargeting) - { - return; - } - - _lastDataBuffer[0] = 0x6C; - - _lastDataBuffer[1] = 0x01; - - _lastDataBuffer[2] = (byte)(_targetCursorId >> 24); - _lastDataBuffer[3] = (byte)(_targetCursorId >> 16); - _lastDataBuffer[4] = (byte)(_targetCursorId >> 8); - _lastDataBuffer[5] = (byte)_targetCursorId; - - _lastDataBuffer[6] = (byte)TargetingType; - - _lastDataBuffer[7] = (byte)(0 >> 24); - _lastDataBuffer[8] = (byte)(0 >> 16); - _lastDataBuffer[9] = (byte)(0 >> 8); - _lastDataBuffer[10] = (byte)0; - - _lastDataBuffer[11] = (byte)(x >> 8); - _lastDataBuffer[12] = (byte)x; - - _lastDataBuffer[13] = (byte)(y >> 8); - _lastDataBuffer[14] = (byte)y; - - _lastDataBuffer[15] = (byte)(z >> 8); - _lastDataBuffer[16] = (byte)z; - - _lastDataBuffer[17] = (byte)(graphic >> 8); - _lastDataBuffer[18] = (byte)graphic; - - - - NetClient.Socket.Send_TargetXYZ(graphic, - x, - y, - z, - _targetCursorId, - (byte)TargetingType); - - - Mouse.CancelDoubleClick = true; - ClearTargetingWithoutTargetCancelPacket(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/TextRenderer.cs b/src/ClassicUO.Client/Game/Managers/TextRenderer.cs deleted file mode 100644 index 153243633..000000000 --- a/src/ClassicUO.Client/Game/Managers/TextRenderer.cs +++ /dev/null @@ -1,321 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Configuration; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.Managers -{ - public class TextRenderer : TextObject - { - private readonly List _bounds = new List(); - - public TextRenderer() - { - FirstNode = this; - } - - protected TextObject FirstNode; - protected TextObject DrawPointer; - - public override void Destroy() - { - //Clear(); - } - - public virtual void Update() - { - ProcessWorldText(false); - } - - public virtual void Draw(UltimaBatcher2D batcher, int startX, int startY, bool isGump = false) - { - ProcessWorldText(false); - - int mouseX = Mouse.Position.X; - int mouseY = Mouse.Position.Y; - - for (TextObject o = DrawPointer; o != null; o = o.DLeft) - { - if (o.IsDestroyed || o.TextBox == null || o.TextBox.IsDisposed || o.Time < ClassicUO.Time.Ticks) - { - continue; - } - - ushort hue = 0; - - float alpha = o.Alpha / 255f; - - if (o.IsTransparent) - { - if (o.Alpha == 0xFF) - { - alpha = 0x7F / 255f; - } - } - - int x = o.RealScreenPosition.X; - int y = o.RealScreenPosition.Y; - - if (o.TextBox.PixelCheck(mouseX - x - startX, mouseY - y - startY)) - { - SelectedObject.Object = o; - } - bool highlight = false; - if (!isGump) - { - if (o.Owner is Entity && SelectedObject.Object == o) - { - highlight = true; - } - } - else - { - x += startX; - y += startY; - } - o.TextBox.Alpha = alpha; - if (highlight) - o.TextBox.Draw - ( - batcher, - x, - y, - Color.Yellow - ); - else - o.TextBox.Draw - ( - batcher, - x, - y - ); - } - } - - public void MoveToTop(TextObject obj) - { - if (obj == null) - { - return; - } - - obj.UnlinkD(); - - TextObject next = FirstNode.DRight; - FirstNode.DRight = obj; - obj.DLeft = FirstNode; - obj.DRight = next; - - if (next != null) - { - next.DLeft = obj; - } - } - - public void ProcessWorldText(bool doit) - { - if (doit) - { - if (_bounds.Count != 0) - { - _bounds.Clear(); - } - } - - for (DrawPointer = FirstNode; DrawPointer != null; DrawPointer = DrawPointer.DRight) - { - if (doit) - { - TextObject t = DrawPointer; - - if (t.Time >= ClassicUO.Time.Ticks && t.TextBox != null && !t.TextBox.IsDisposed) - { - if (t.Owner != null) - { - t.IsTransparent = Collides(t); - CalculateAlpha(t); - } - } - } - - if (DrawPointer.DRight == null) - { - break; - } - } - } - - private void CalculateAlpha(TextObject msg) - { - if (ProfileManager.CurrentProfile != null && ProfileManager.CurrentProfile.TextFading) - { - int delta = (int)(msg.Time - ClassicUO.Time.Ticks); - - if (delta >= 0 && delta <= 1000) - { - delta /= 10; - - if (delta > 100) - { - delta = 100; - } - else if (delta < 1) - { - delta = 0; - } - - delta = 255 * delta / 100; - - if (!msg.IsTransparent || delta <= 0x7F) - { - msg.Alpha = (byte)delta; - } - - msg.IsTransparent = true; - } - } - } - - private bool Collides(TextObject msg) - { - bool result = false; - - Rectangle rect = new Rectangle - { - X = msg.RealScreenPosition.X, - Y = msg.RealScreenPosition.Y, - Width = msg.TextBox.Width, - Height = msg.TextBox.Height - }; - - for (int i = 0; i < _bounds.Count; i++) - { - if (_bounds[i].Intersects(rect)) - { - result = true; - - break; - } - } - - _bounds.Add(rect); - - return result; - } - - public void AddMessage(TextObject obj) - { - if (obj == null) - { - return; - } - - obj.UnlinkD(); - - TextObject item = FirstNode; - - if (item != null) - { - if (item.DRight != null) - { - TextObject next = item.DRight; - - item.DRight = obj; - obj.DLeft = item; - obj.DRight = next; - next.DLeft = obj; - } - else - { - item.DRight = obj; - obj.DLeft = item; - obj.DRight = null; - } - } - } - - - public new virtual void Clear() - { - if (FirstNode != null) - { - TextObject first = FirstNode; - - while (first?.DLeft != null) - { - first = first.DLeft; - } - - while (first != null) - { - TextObject next = first.DRight; - - first.Destroy(); - first.Clear(); - - first = next; - } - } - - if (DrawPointer != null) - { - TextObject first = DrawPointer; - - while (first?.DLeft != null) - { - first = first.DLeft; - } - - while (first != null) - { - TextObject next = first.DRight; - - first.Destroy(); - first.Clear(); - - first = next; - } - } - - FirstNode = this; - FirstNode.DLeft = null; - FirstNode.DRight = null; - DrawPointer = null; - } - } -} diff --git a/src/ClassicUO.Client/Game/Managers/TileMarkerManager.cs b/src/ClassicUO.Client/Game/Managers/TileMarkerManager.cs deleted file mode 100644 index 3182dcdd3..000000000 --- a/src/ClassicUO.Client/Game/Managers/TileMarkerManager.cs +++ /dev/null @@ -1,68 +0,0 @@ -using ClassicUO.Configuration; -using System; -using System.Collections.Generic; -using System.IO; -using System.Runtime.Serialization.Formatters.Binary; - -namespace ClassicUO.Game.Managers -{ - internal class TileMarkerManager - { - public static TileMarkerManager Instance { get; private set; } = new TileMarkerManager(); - - private Dictionary markedTiles = new Dictionary(); - - private TileMarkerManager() { Load(); } - - private string savePath = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Profiles", "TileMarkers.bin"); - - public void AddTile(int x, int y, int map, ushort hue) - { - markedTiles.Add(FormatLocKey(x, y, map), hue); - } - - public void RemoveTile(int x, int y, int map) - { - if (markedTiles.ContainsKey(FormatLocKey(x, y, map))) - markedTiles.Remove(FormatLocKey(x, y, map)); - } - - public bool IsTileMarked(int x, int y, int map, out ushort hue) - { - if (markedTiles.TryGetValue(FormatLocKey(x, y, map), out hue)) return true; - return false; - } - - private string FormatLocKey(int x, int y, int map) - { - return $"{x}.{y}.{map}"; - } - - public void Save() - { - try - { - using (FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write)) - { - BinaryFormatter bf = new BinaryFormatter(); - bf.Serialize(fs, markedTiles); - } - } - catch { Console.WriteLine("Failed to save marked tile data."); } - } - - private void Load() - { - if(File.Exists(savePath)) - try - { - using (FileStream fs = File.OpenRead(savePath)) - { - BinaryFormatter bf = new BinaryFormatter(); - markedTiles = (Dictionary)bf.Deserialize(fs); - } - } - catch { } - } - } -} diff --git a/src/ClassicUO.Client/Game/Managers/ToolTipOverrideManager.cs b/src/ClassicUO.Client/Game/Managers/ToolTipOverrideManager.cs deleted file mode 100644 index 964bc3ae5..000000000 --- a/src/ClassicUO.Client/Game/Managers/ToolTipOverrideManager.cs +++ /dev/null @@ -1,384 +0,0 @@ -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Gumps; -using System; -using System.IO; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Threading; - -namespace ClassicUO.Game.Managers -{ - [JsonSerializable(typeof(ToolTipOverrideData))] - internal class ToolTipOverrideData - { - public ToolTipOverrideData() { } - public ToolTipOverrideData(int index, string searchText, string formattedText, int min1, int max1, int min2, int max2, byte layer) - { - Index = index; - SearchText = searchText; - FormattedText = formattedText; - Min1 = min1; - Max1 = max1; - Min2 = min2; - Max2 = max2; - ItemLayer = (TooltipLayers)layer; - } - - private string searchText, formattedText; - - public int Index { get; } - public string SearchText { get { return searchText.Replace(@"\u002B", @"+"); } set { searchText = value; } } - public string FormattedText { get { return formattedText.Replace(@"\u002B", @"+"); } set { formattedText = value; } } - public int Min1 { get; set; } - public int Max1 { get; set; } - public int Min2 { get; set; } - public int Max2 { get; set; } - public TooltipLayers ItemLayer { get; set; } - - public bool IsNew { get; set; } = false; - - public static ToolTipOverrideData Get(int index) - { - bool isNew = false; - if (ProfileManager.CurrentProfile != null) - { - string searchText = "Weapon Damage", formattedText = "DMG /c[orange]{1} /cd- /c[red]{2}"; - int min1 = -1, max1 = 99, min2 = -1, max2 = 99; - byte layer = (byte)TooltipLayers.Any; - - if (ProfileManager.CurrentProfile.ToolTipOverride_SearchText.Count > index) - searchText = ProfileManager.CurrentProfile.ToolTipOverride_SearchText[index]; - else isNew = true; - - if (ProfileManager.CurrentProfile.ToolTipOverride_NewFormat.Count > index) - formattedText = ProfileManager.CurrentProfile.ToolTipOverride_NewFormat[index]; - else isNew = true; - - if (ProfileManager.CurrentProfile.ToolTipOverride_MinVal1.Count > index) - min1 = ProfileManager.CurrentProfile.ToolTipOverride_MinVal1[index]; - else isNew = true; - - if (ProfileManager.CurrentProfile.ToolTipOverride_MinVal2.Count > index) - min2 = ProfileManager.CurrentProfile.ToolTipOverride_MinVal2[index]; - else isNew = true; - - if (ProfileManager.CurrentProfile.ToolTipOverride_MaxVal1.Count > index) - max1 = ProfileManager.CurrentProfile.ToolTipOverride_MaxVal1[index]; - else isNew = true; - - if (ProfileManager.CurrentProfile.ToolTipOverride_MaxVal2.Count > index) - max2 = ProfileManager.CurrentProfile.ToolTipOverride_MaxVal2[index]; - else isNew = true; - - if (ProfileManager.CurrentProfile.ToolTipOverride_Layer.Count > index) - layer = ProfileManager.CurrentProfile.ToolTipOverride_Layer[index]; - else isNew = true; - - ToolTipOverrideData data = new ToolTipOverrideData(index, searchText, formattedText, min1, max1, min2, max2, layer); - - if (isNew) - { - data.IsNew = true; - data.Save(); - } - return data; - } - return null; - } - - public void Save() - { - if (ProfileManager.CurrentProfile.ToolTipOverride_SearchText.Count > Index) - ProfileManager.CurrentProfile.ToolTipOverride_SearchText[Index] = SearchText; - else ProfileManager.CurrentProfile.ToolTipOverride_SearchText.Add(SearchText); - - if (ProfileManager.CurrentProfile.ToolTipOverride_NewFormat.Count > Index) - ProfileManager.CurrentProfile.ToolTipOverride_NewFormat[Index] = FormattedText; - else ProfileManager.CurrentProfile.ToolTipOverride_NewFormat.Add(FormattedText); - - if (ProfileManager.CurrentProfile.ToolTipOverride_MinVal1.Count > Index) - ProfileManager.CurrentProfile.ToolTipOverride_MinVal1[Index] = Min1; - else ProfileManager.CurrentProfile.ToolTipOverride_MinVal1.Add(Min1); - - if (ProfileManager.CurrentProfile.ToolTipOverride_MinVal2.Count > Index) - ProfileManager.CurrentProfile.ToolTipOverride_MinVal2[Index] = Min2; - else ProfileManager.CurrentProfile.ToolTipOverride_MinVal2.Add(Min2); - - if (ProfileManager.CurrentProfile.ToolTipOverride_MaxVal1.Count > Index) - ProfileManager.CurrentProfile.ToolTipOverride_MaxVal1[Index] = Max1; - else ProfileManager.CurrentProfile.ToolTipOverride_MaxVal1.Add(Max1); - - if (ProfileManager.CurrentProfile.ToolTipOverride_MaxVal2.Count > Index) - ProfileManager.CurrentProfile.ToolTipOverride_MaxVal2[Index] = Max2; - else ProfileManager.CurrentProfile.ToolTipOverride_MaxVal2.Add(Max2); - - if (ProfileManager.CurrentProfile.ToolTipOverride_Layer.Count > Index) - ProfileManager.CurrentProfile.ToolTipOverride_Layer[Index] = (byte)ItemLayer; - else ProfileManager.CurrentProfile.ToolTipOverride_Layer.Add((byte)ItemLayer); - } - - public void Delete() - { - ProfileManager.CurrentProfile.ToolTipOverride_SearchText.RemoveAt(Index); - ProfileManager.CurrentProfile.ToolTipOverride_NewFormat.RemoveAt(Index); - ProfileManager.CurrentProfile.ToolTipOverride_MinVal1.RemoveAt(Index); - ProfileManager.CurrentProfile.ToolTipOverride_MinVal2.RemoveAt(Index); - ProfileManager.CurrentProfile.ToolTipOverride_MaxVal1.RemoveAt(Index); - ProfileManager.CurrentProfile.ToolTipOverride_MaxVal2.RemoveAt(Index); - ProfileManager.CurrentProfile.ToolTipOverride_Layer.RemoveAt(Index); - } - - public static ToolTipOverrideData[] GetAllToolTipOverrides() - { - if (ProfileManager.CurrentProfile == null) - return null; - - ToolTipOverrideData[] result = new ToolTipOverrideData[ProfileManager.CurrentProfile.ToolTipOverride_SearchText.Count]; - - for (int i = 0; i < ProfileManager.CurrentProfile.ToolTipOverride_SearchText.Count; i++) - { - result[i] = Get(i); - } - - return result; - } - - public static void ExportOverrideSettings() - { - ToolTipOverrideData[] allData = GetAllToolTipOverrides(); - - if (!CUOEnviroment.IsUnix) - { - Thread t = new Thread(() => - { - System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog(); - saveFileDialog1.Filter = "Json|*.json"; - saveFileDialog1.Title = "Save tooltip override settings"; - saveFileDialog1.ShowDialog(); - - string result = JsonSerializer.Serialize(allData); - - // If the file name is not an empty string open it for saving. - if (saveFileDialog1.FileName != "") - { - System.IO.FileStream fs = - (System.IO.FileStream)saveFileDialog1.OpenFile(); - // NOTE that the FilterIndex property is one-based. - switch (saveFileDialog1.FilterIndex) - { - default: - byte[] data = Encoding.UTF8.GetBytes(result); - fs.Write(data, 0, data.Length); - break; - } - - fs.Close(); - } - }); - t.SetApartmentState(ApartmentState.STA); - t.Start(); - } - } - - public static void ImportOverrideSettings() - { - if (!CUOEnviroment.IsUnix) - { - Thread t = new Thread(() => - { - System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog(); - openFileDialog.Filter = "Json|*.json"; - openFileDialog.Title = "Import tooltip override settings"; - openFileDialog.ShowDialog(); - - // If the file name is not an empty string open it for saving. - if (openFileDialog.FileName != "") - { - // NOTE that the FilterIndex property is one-based. - switch (openFileDialog.FilterIndex) - { - default: - try - { - string result = File.ReadAllText(openFileDialog.FileName); - - ToolTipOverrideData[] imported = JsonSerializer.Deserialize(result); - - foreach (ToolTipOverrideData importedData in imported) - //GameActions.Print(importedData.searchText); - new ToolTipOverrideData(ProfileManager.CurrentProfile.ToolTipOverride_SearchText.Count, importedData.searchText, importedData.FormattedText, importedData.Min1, importedData.Max1, importedData.Min2, importedData.Max2, (byte)importedData.ItemLayer).Save(); - - ToolTipOverideMenu.Reopen = true; - - } - catch (System.Exception e) - { - GameActions.Print("It looks like there was an error trying to import your override settings.", 32); - } - break; - } - } - }); - t.SetApartmentState(ApartmentState.STA); - t.Start(); - } - } - - public static string ProcessTooltipText(uint serial, uint compareTo = uint.MinValue) - { - string tooltip = ""; - ItemPropertiesData itemPropertiesData; - - if (compareTo != uint.MinValue) - { - itemPropertiesData = new ItemPropertiesData(World.Items.Get(serial), World.Items.Get(compareTo)); - } - else - { - itemPropertiesData = new ItemPropertiesData(World.Items.Get(serial)); - } - - ToolTipOverrideData[] result = GetAllToolTipOverrides(); - - if (itemPropertiesData.HasData) - { - if (EventSink.PreProcessTooltip != null) - { - EventSink.PreProcessTooltip(ref itemPropertiesData); - } - - tooltip += ProfileManager.CurrentProfile == null ? $"/c[yellow]{itemPropertiesData.Name}\n" : string.Format(ProfileManager.CurrentProfile.TooltipHeaderFormat + "\n", itemPropertiesData.Name); - - //Loop through each property - foreach (ItemPropertiesData.SinglePropertyData property in itemPropertiesData.singlePropertyData) - { - bool handled = false; - //Loop though each override setting player created - foreach (ToolTipOverrideData overrideData in result) - { - if (overrideData != null) - if (overrideData.ItemLayer == TooltipLayers.Any || checkLayers(overrideData.ItemLayer, itemPropertiesData.item.ItemData.Layer)) - { - if (property.OriginalString.ToLower().Contains(overrideData.SearchText.ToLower())) - if (property.FirstValue == -1 || (property.FirstValue >= overrideData.Min1 && property.FirstValue <= overrideData.Max1)) - if (property.SecondValue == -1 || (property.SecondValue >= overrideData.Min2 && property.SecondValue <= overrideData.Max2)) - { - try - { - if (compareTo != uint.MinValue) - { - tooltip += string.Format( - overrideData.FormattedText, - property.Name, - property.FirstValue.ToString(), - property.SecondValue.ToString(), - property.OriginalString, - property.FirstDiff != 0 ? "("+property.FirstDiff.ToString()+")" : "", - property.SecondDiff != 0 ? "("+property.SecondDiff.ToString()+")" : "" - ) + "\n"; - } - else - { - tooltip += string.Format( - overrideData.FormattedText, - property.Name, - property.FirstValue.ToString(), - property.SecondValue.ToString(), - property.OriginalString, "", "" - ) + "\n"; - } - handled = true; - break; - } - catch (System.FormatException e) { Console.WriteLine(e.ToString()); } - } - } - } - if (!handled) //Did not find a matching override, need to add the plain tooltip line still - tooltip += $"{property.OriginalString}\n"; - } - - if (EventSink.PostProcessTooltip != null) - { - EventSink.PostProcessTooltip(ref tooltip); - } - - return tooltip; - } - return null; - } - - public static string ProcessTooltipText(string text) - { - string tooltip = ""; - - ItemPropertiesData itemPropertiesData = new ItemPropertiesData(text); - - ToolTipOverrideData[] result = GetAllToolTipOverrides(); - - if (itemPropertiesData.HasData && result != null && result.Length > 0) - { - tooltip += ProfileManager.CurrentProfile == null ? $"/c[yellow]{itemPropertiesData.Name}\n" : string.Format(ProfileManager.CurrentProfile.TooltipHeaderFormat + "\n", itemPropertiesData.Name); - - //Loop through each property - foreach (ItemPropertiesData.SinglePropertyData property in itemPropertiesData.singlePropertyData) - { - bool handled = false; - //Loop though each override setting player created - foreach (ToolTipOverrideData overrideData in result) - { - if (overrideData != null) - if (overrideData.ItemLayer == TooltipLayers.Any) - { - if (property.OriginalString.ToLower().Contains(overrideData.SearchText.ToLower())) - if (property.FirstValue == -1 || (property.FirstValue >= overrideData.Min1 && property.FirstValue <= overrideData.Max1)) - if (property.SecondValue == -1 || (property.SecondValue >= overrideData.Min2 && property.SecondValue <= overrideData.Max2)) - { - try - { - tooltip += string.Format(overrideData.FormattedText, property.Name, property.FirstValue.ToString(), property.SecondValue.ToString()) + "\n"; - handled = true; - break; - } - catch (System.FormatException e) { } - } - } - } - if (!handled) //Did not find a matching override, need to add the plain tooltip line still - tooltip += $"{property.OriginalString}\n"; - - } - - return tooltip; - } - return null; - } - - private static bool checkLayers(TooltipLayers overrideLayer, byte itemLayer) - { - if ((byte)overrideLayer == itemLayer) - return true; - - if (overrideLayer == TooltipLayers.Body_Group) - { - if (itemLayer == (byte)Layer.Shoes || itemLayer == (byte)Layer.Pants || itemLayer == (byte)Layer.Shirt || itemLayer == (byte)Layer.Helmet || itemLayer == (byte)Layer.Necklace || itemLayer == (byte)Layer.Arms || itemLayer == (byte)Layer.Gloves || itemLayer == (byte)Layer.Waist || itemLayer == (byte)Layer.Torso || itemLayer == (byte)Layer.Tunic || itemLayer == (byte)Layer.Legs || itemLayer == (byte)Layer.Skirt || itemLayer == (byte)Layer.Cloak || itemLayer == (byte)Layer.Robe) - return true; - } - else if (overrideLayer == TooltipLayers.Jewelry_Group) - { - if (itemLayer == (byte)Layer.Talisman || itemLayer == (byte)Layer.Bracelet || itemLayer == (byte)Layer.Ring || itemLayer == (byte)Layer.Earrings) - return true; - } - else if (overrideLayer == TooltipLayers.Weapon_Group) - { - if (itemLayer == (byte)Layer.OneHanded || itemLayer == (byte)Layer.TwoHanded) - return true; - } - - return false; - } - } -} diff --git a/src/ClassicUO.Client/Game/Managers/UIManager.cs b/src/ClassicUO.Client/Game/Managers/UIManager.cs deleted file mode 100644 index 4831d96e8..000000000 --- a/src/ClassicUO.Client/Game/Managers/UIManager.cs +++ /dev/null @@ -1,691 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using System.Collections.Generic; - -namespace ClassicUO.Game.Managers -{ - public static class UIManager - { - private static readonly Dictionary _gumpPositionCache = new Dictionary(); - private static readonly Control[] _mouseDownControls = new Control[0xFF]; - - - //private static readonly Dictionary _targetLineGumps = new Dictionary(); - private static Point _dragOrigin; - private static bool _isDraggingControl; - private static Control _keyboardFocusControl, _lastFocus; - private static bool _needSort; - - - public static float ContainerScale { get; set; } = 1f; - - public static AnchorManager AnchorManager { get; } = new AnchorManager(); - - public static LinkedList Gumps { get; } = new LinkedList(); - - public static Control MouseOverControl { get; private set; } - - public static bool IsModalOpen { get; private set; } - - public static bool IsMouseOverWorld - { - get - { - Point mouse = Mouse.Position; - Profile profile = ProfileManager.CurrentProfile; - - return profile != null && - Client.Game.GameCursor.AllowDrawSDLCursor && - DraggingControl == null && - MouseOverControl == null && - !IsModalOpen && - Client.Game.Scene.Camera.Bounds.Contains(mouse); - } - } - - public static Control DraggingControl { get; private set; } - - public static SystemChatControl SystemChat { get; set; } - - public static PopupMenuGump PopupMenu { get; private set; } - - public static Control KeyboardFocusControl - { - get => _keyboardFocusControl; - set - { - if (_keyboardFocusControl != value) - { - _keyboardFocusControl?.OnFocusLost(); - _keyboardFocusControl = value; - - if (value != null && value.AcceptKeyboardInput) - { - if (!value.IsFocused) - { - value.OnFocusEnter(); - } - } - } - } - } - - public static bool IsDragging => _isDraggingControl && DraggingControl != null; - - public static ContextMenuShowMenu ContextMenu { get; private set; } - - public static void ShowGamePopup(PopupMenuGump popup) - { - PopupMenu?.Dispose(); - PopupMenu = popup; - - if (popup == null || popup.IsDisposed) - { - return; - } - - Add(PopupMenu); - } - - - public static bool IsModalControlOpen() - { - for (LinkedListNode last = Gumps.Last; last != null; last = last.Previous) - { - if (last.Value.IsModal) - { - return true; - } - } - - return false; - } - - - public static void OnMouseDragging() - { - HandleMouseInput(); - - if (_mouseDownControls[(int)MouseButtonType.Left] != null) - { - if (ProfileManager.CurrentProfile == null || !ProfileManager.CurrentProfile.HoldAltToMoveGumps || Keyboard.Alt) - { - AttemptDragControl(_mouseDownControls[(int)MouseButtonType.Left], true); - } - } - - if (_isDraggingControl) - { - DoDragControl(); - } - } - - public static void OnMouseButtonDown(MouseButtonType button) - { - HandleMouseInput(); - - if (MouseOverControl != null) - { - if (MouseOverControl.IsEnabled && MouseOverControl.IsVisible) - { - if (_lastFocus != MouseOverControl) - { - _lastFocus?.OnFocusLost(); - MouseOverControl.OnFocusEnter(); - _lastFocus = MouseOverControl; - } - } - - MakeTopMostGump(MouseOverControl); - MouseOverControl.InvokeMouseDown(Mouse.Position, button); - - if (MouseOverControl.AcceptKeyboardInput) - { - _keyboardFocusControl = MouseOverControl; - } - - _mouseDownControls[(int)button] = MouseOverControl; - } - else - { - foreach (Gump s in Gumps) - { - if (s.IsModal && s.ModalClickOutsideAreaClosesThisControl) - { - s.Dispose(); - Mouse.CancelDoubleClick = true; - } - } - } - - if (PopupMenu != null && !PopupMenu.Bounds.Contains(Mouse.Position.X, Mouse.Position.Y)) - { - ShowGamePopup(null); - } - } - - public static void OnMouseButtonUp(MouseButtonType button) - { - EndDragControl(Mouse.Position); - HandleMouseInput(); - - int index = (int)button; - - if (MouseOverControl != null) - { - if (_mouseDownControls[index] != null && MouseOverControl == _mouseDownControls[index] || Client.Game.GameCursor.ItemHold.Enabled) - { - MouseOverControl.InvokeMouseUp(Mouse.Position, button); - } - else if (_mouseDownControls[index] != null && MouseOverControl != _mouseDownControls[index]) - { - if (!_mouseDownControls[index].IsDisposed) - { - _mouseDownControls[index].InvokeMouseUp(Mouse.Position, button); - } - } - } - else if (_mouseDownControls[index] != null && !_mouseDownControls[index].IsDisposed) - { - _mouseDownControls[index].InvokeMouseUp(Mouse.Position, button); - } - - if (button == MouseButtonType.Right) - { - var mouseDownControl = _mouseDownControls[index]; - // only attempt to close the gump if the mouse is still on the gump when right click mouse up occurs - if (mouseDownControl != null && MouseOverControl == mouseDownControl) - { - mouseDownControl.InvokeMouseCloseGumpWithRClick(); - } - } - - _mouseDownControls[index] = null; - } - - public static bool OnMouseDoubleClick(MouseButtonType button) - { - HandleMouseInput(); - - if (MouseOverControl != null) - { - if (MouseOverControl.InvokeMouseDoubleClick(Mouse.Position, button)) - { - if (button == MouseButtonType.Left) - { - DelayedObjectClickManager.Clear(); - } - - return true; - } - } - - return false; - } - - public static void OnMouseWheel(bool isup) - { - if (MouseOverControl != null && MouseOverControl.AcceptMouseInput) - { - MouseOverControl.InvokeMouseWheel(isup ? MouseEventType.WheelScrollUp : MouseEventType.WheelScrollDown); - } - } - - public static Control LastControlMouseDown(MouseButtonType button) - { - return _mouseDownControls[(int)button]; - } - - public static void SavePosition(uint serverSerial, Point point) - { - _gumpPositionCache[serverSerial] = point; - } - - public static bool RemovePosition(uint serverSerial) - { - return _gumpPositionCache.Remove(serverSerial); - } - - public static bool GetGumpCachePosition(uint id, out Point pos) - { - return _gumpPositionCache.TryGetValue(id, out pos); - } - - public static void ShowContextMenu(ContextMenuShowMenu menu) - { - ContextMenu?.Dispose(); - - ContextMenu = menu; - - if (ContextMenu == null || menu.IsDisposed) - { - return; - } - - Add(ContextMenu); - } - - public static T GetGump(uint? serial = null) where T : Control - { - if (serial.HasValue) - { - for (LinkedListNode last = Gumps.Last; last != null; last = last.Previous) - { - Control c = last.Value; - - if (!c.IsDisposed && c.LocalSerial == serial.Value && c is T t) - { - return t; - } - } - } - else - { - for (LinkedListNode first = Gumps.First; first != null; first = first.Next) - { - Control c = first.Value; - - if (!c.IsDisposed && c is T t) - { - return t; - } - } - } - - return null; - } - - public static Gump GetGump(uint serial) - { - for (LinkedListNode last = Gumps.Last; last != null; last = last.Previous) - { - Control c = last.Value; - - if (!c.IsDisposed && c.LocalSerial == serial) - { - return c as Gump; - } - } - - return null; - } - - public static TradingGump GetTradingGump(uint serial) - { - for (LinkedListNode g = Gumps.Last; g != null; g = g.Previous) - { - if (g.Value != null && !g.Value.IsDisposed && g.Value is TradingGump trading && (trading.ID1 == serial || trading.ID2 == serial || trading.LocalSerial == serial)) - { - return trading; - } - } - - return null; - } - - public static void Update() - { - SortControlsByInfo(); - - LinkedListNode first = Gumps.First; - - while (first != null) - { - LinkedListNode next = first.Next; - - Control g = first.Value; - - g.Update(); - - if (g.IsDisposed) - { - Gumps.Remove(first); - } - - first = next; - } - - HandleKeyboardInput(); - HandleMouseInput(); - } - - public static void Draw(UltimaBatcher2D batcher) - { - SortControlsByInfo(); - - batcher.Begin(); - - for (LinkedListNode last = Gumps.Last; last != null; last = last.Previous) - { - Control g = last.Value; - g.Draw(batcher, g.X, g.Y); - } - - batcher.End(); - } - - public static void Add(Gump gump, bool front = true) - { - if (!gump.IsDisposed) - { - if (front) - { - Gumps.AddFirst(gump); - } - else - { - Gumps.AddLast(gump); - } - - _needSort = Gumps.Count > 1; - } - } - - public static void Clear() - { - foreach (Gump s in Gumps) - { - s.Dispose(); - } - } - - - private static void HandleKeyboardInput() - { - if (_keyboardFocusControl != null && _keyboardFocusControl.IsDisposed) - { - _keyboardFocusControl = null; - } - - if (_keyboardFocusControl == null) - { - if (SystemChat != null && !SystemChat.IsDisposed) - { - _keyboardFocusControl = SystemChat.TextBoxControl; - _keyboardFocusControl.OnFocusEnter(); - } - else - { - for (LinkedListNode first = Gumps.First; first != null; first = first.Next) - { - Control c = first.Value; - - if (!c.IsDisposed && c.IsVisible && c.IsEnabled) - { - _keyboardFocusControl = c.GetFirstControlAcceptKeyboardInput(); - - if (_keyboardFocusControl != null) - { - _keyboardFocusControl.OnFocusEnter(); - - break; - } - } - } - } - } - } - - private static void HandleMouseInput() - { - Control gump = GetMouseOverControl(Mouse.Position); - - if (MouseOverControl != null && gump != MouseOverControl) - { - MouseOverControl.InvokeMouseExit(Mouse.Position); - - if (MouseOverControl.RootParent != null) - { - if (gump == null || gump.RootParent != MouseOverControl.RootParent) - { - MouseOverControl.RootParent.InvokeMouseExit(Mouse.Position); - } - } - } - - if (gump != null) - { - if (gump != MouseOverControl) - { - gump.InvokeMouseEnter(Mouse.Position); - - if (gump.RootParent != null) - { - if (MouseOverControl == null || gump.RootParent != MouseOverControl.RootParent) - { - gump.RootParent.InvokeMouseEnter(Mouse.Position); - } - } - } - - gump.InvokeMouseOver(Mouse.Position); - } - - MouseOverControl = gump; - - //for (int i = 0; i < (int) MouseButtonType.Size; i++) - //{ - // if (_mouseDownControls[i] != null && _mouseDownControls[i] != gump) - // { - // _mouseDownControls[i].InvokeMouseOver(Mouse.Position); - // } - //} - } - - private static Control GetMouseOverControl(Point position) - { - if (_isDraggingControl) - { - return DraggingControl; - } - - Control control = null; - - IsModalOpen = IsModalControlOpen(); - - for (LinkedListNode first = Gumps.First; first != null; first = first.Next) - { - Control c = first.Value; - - if (IsModalOpen && !c.IsModal || !c.IsVisible || !c.IsEnabled) - { - continue; - } - - c.HitTest(position, ref control); - - if (control != null) - { - return control; - } - } - - return null; - } - - public static void MakeTopMostGump(Control control) - { - Gump gump = control as Gump; - if (gump == null && control?.RootParent is Gump) - { - gump = control.RootParent as Gump; - } - - if (gump != null) - { - for (LinkedListNode start = Gumps.First; start != null; start = start.Next) - { - if (start.Value == gump) - { - if (gump.LayerOrder == UILayer.Under) - { - if (start != Gumps.Last) - { - Gumps.Remove(gump); - Gumps.AddBefore(Gumps.Last, start); - } - } - else - { - Gumps.Remove(gump); - Gumps.AddFirst(start); - } - - break; - } - } - - _needSort = Gumps.Count > 1; - } - } - - private static void SortControlsByInfo() - { - if (_needSort) - { - for (LinkedListNode el = Gumps.First; el != null; el = el.Next) - { - Gump c = el.Value; - - if (c.LayerOrder == UILayer.Default) - { - continue; - } - - if (c.LayerOrder == UILayer.Under) - { - for (LinkedListNode first = Gumps.First; first != null; first = first.Next) - { - if (first.Value == c) - { - if (c != Gumps.Last.Value) - { - Gumps.Remove(first); - Gumps.AddBefore(Gumps.Last, first); - } - } - } - } - else if (c.LayerOrder == UILayer.Over) - { - for (LinkedListNode first = Gumps.First; first != null; first = first.Next) - { - if (first.Value == c) - { - Gumps.Remove(first); - Gumps.AddFirst(c); - } - } - } - } - - _needSort = false; - } - } - - public static void AttemptDragControl(Control control, bool attemptAlwaysSuccessful = false) - { - if ((_isDraggingControl && !attemptAlwaysSuccessful) || Client.Game.GameCursor.ItemHold.Enabled && !Client.Game.GameCursor.ItemHold.IsFixedPosition) - { - return; - } - - Control dragTarget = control; - - if (!dragTarget.CanMove) - { - return; - } - - while (dragTarget.Parent != null) - { - dragTarget = dragTarget.Parent; - } - - if (dragTarget.CanMove) - { - if (attemptAlwaysSuccessful || !_isDraggingControl) - { - DraggingControl = dragTarget; - _dragOrigin = Mouse.LClickPosition; - - for (int i = 0; i < (int)MouseButtonType.Size; i++) - { - _mouseDownControls[i] = null; - } - } - - Point delta = Mouse.Position - _dragOrigin; - - if (attemptAlwaysSuccessful || delta != Point.Zero) - { - _isDraggingControl = true; - dragTarget.InvokeDragBegin(delta); - } - } - } - - private static void DoDragControl() - { - if (DraggingControl == null) - { - return; - } - - Point delta = Mouse.Position - _dragOrigin; - - DraggingControl.X += delta.X; - DraggingControl.Y += delta.Y; - DraggingControl.InvokeMove(delta.X, delta.Y); - _dragOrigin = Mouse.Position; - } - - private static void EndDragControl(Point mousePosition) - { - if (_isDraggingControl) - { - DoDragControl(); - } - - DraggingControl?.InvokeDragEnd(mousePosition); - DraggingControl = null; - _isDraggingControl = false; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/UpdateManager.cs b/src/ClassicUO.Client/Game/Managers/UpdateManager.cs deleted file mode 100644 index 5bef7785d..000000000 --- a/src/ClassicUO.Client/Game/Managers/UpdateManager.cs +++ /dev/null @@ -1,150 +0,0 @@ -using System; -using System.Net.Http; -using System.Text.Json; -using System.Threading.Tasks; - -namespace ClassicUO.Game.Managers -{ - internal static class UpdateManager - { - public static bool SkipUpdateCheck { get; set; } = false; - public static event EventHandler UpdateStatusChanged; - public static bool HasUpdate { get; private set; } = false; - public static GitHubReleaseData MainReleaseData; - - public static void CheckForUpdates() - { - if (!SkipUpdateCheck) - { - Task.Factory.StartNew(() => - { - try - { - HttpRequestMessage restApi = new HttpRequestMessage() - { - Method = HttpMethod.Get, - RequestUri = new Uri("https://api.github.com/repos/bittiez/TazUO/releases/latest"), - }; - restApi.Headers.Add("X-GitHub-Api-Version", "2022-11-28"); - restApi.Headers.Add("User-Agent", "Public"); - string jsonResponse = new HttpClient().SendAsync(restApi).Result.Content.ReadAsStringAsync().Result; - - MainReleaseData = JsonSerializer.Deserialize(jsonResponse); - - if (MainReleaseData != null) - { - if (MainReleaseData.tag_name.StartsWith("v")) - { - MainReleaseData.tag_name = MainReleaseData.tag_name.Substring(1); - } - - if (Version.TryParse(MainReleaseData.tag_name, out var version)) - { - if(version > CUOEnviroment.Version) - { - HasUpdate = true; - UpdateStatusChanged?.Invoke(null, EventArgs.Empty); - } - } - } - } - catch { } - }); - } - } - - public static void SendDelayedUpdateMessage() - { - Task.Factory.StartNew(() => - { - Task.Delay(30000).Wait(); - GameActions.Print("TazUO has an update available, please visit https://github.com/bittiez/TazUO to get the most recent version.", 32); - }); - } - } - - internal class GitHubReleaseData - { - public string url { get; set; } - public string assets_url { get; set; } - public string upload_url { get; set; } - public string html_url { get; set; } - public int id { get; set; } - public Author author { get; set; } - public string node_id { get; set; } - public string tag_name { get; set; } - public string target_commitish { get; set; } - public string name { get; set; } - public bool draft { get; set; } - public bool prerelease { get; set; } - public DateTime created_at { get; set; } - public DateTime published_at { get; set; } - public Asset[] assets { get; set; } - public string tarball_url { get; set; } - public string zipball_url { get; set; } - public string body { get; set; } - public int mentions_count { get; set; } - - public class Author - { - public string login { get; set; } - public int id { get; set; } - public string node_id { get; set; } - public string avatar_url { get; set; } - public string gravatar_id { get; set; } - public string url { get; set; } - public string html_url { get; set; } - public string followers_url { get; set; } - public string following_url { get; set; } - public string gists_url { get; set; } - public string starred_url { get; set; } - public string subscriptions_url { get; set; } - public string organizations_url { get; set; } - public string repos_url { get; set; } - public string events_url { get; set; } - public string received_events_url { get; set; } - public string type { get; set; } - public bool site_admin { get; set; } - } - - public class Asset - { - public string url { get; set; } - public int id { get; set; } - public string node_id { get; set; } - public string name { get; set; } - public object label { get; set; } - public Uploader uploader { get; set; } - public string content_type { get; set; } - public string state { get; set; } - public int size { get; set; } - public int download_count { get; set; } - public DateTime created_at { get; set; } - public DateTime updated_at { get; set; } - public string browser_download_url { get; set; } - } - - public class Uploader - { - public string login { get; set; } - public int id { get; set; } - public string node_id { get; set; } - public string avatar_url { get; set; } - public string gravatar_id { get; set; } - public string url { get; set; } - public string html_url { get; set; } - public string followers_url { get; set; } - public string following_url { get; set; } - public string gists_url { get; set; } - public string starred_url { get; set; } - public string subscriptions_url { get; set; } - public string organizations_url { get; set; } - public string repos_url { get; set; } - public string events_url { get; set; } - public string received_events_url { get; set; } - public string type { get; set; } - public bool site_admin { get; set; } - } - - } -} diff --git a/src/ClassicUO.Client/Game/Managers/UseItemQueue.cs b/src/ClassicUO.Client/Game/Managers/UseItemQueue.cs deleted file mode 100644 index ee1ad6b85..000000000 --- a/src/ClassicUO.Client/Game/Managers/UseItemQueue.cs +++ /dev/null @@ -1,110 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.GameObjects; -using ClassicUO.Utility.Collections; - -namespace ClassicUO.Game.Managers -{ - internal class UseItemQueue - { - private readonly Deque _actions = new Deque(); - private long _timer; - - - public UseItemQueue() - { - _timer = Time.Ticks + 1000; - } - - public void Update() - { - if (_timer < Time.Ticks) - { - _timer = Time.Ticks + 1000; - - if (_actions.Count == 0) - { - return; - } - - uint serial = _actions.RemoveFromFront(); - - if (World.Get(serial) != null) - { - if (SerialHelper.IsMobile(serial)) - { - serial |= 0x8000_0000; - } - - GameActions.DoubleClick(serial); - } - } - } - - public void Add(uint serial) - { - foreach (uint s in _actions) - { - if (serial == s) - { - return; - } - } - - _actions.AddToBack(serial); - } - - public void Clear() - { - _actions.Clear(); - } - - public void ClearCorpses() - { - for (int i = 0; i < _actions.Count; i++) - { - Entity entity = World.Get(_actions[i]); - - if (entity == null) - { - continue; - } - - if (entity is Item it && it.IsCorpse) - { - _actions.RemoveAt(i--); - } - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/WalkerManager.cs b/src/ClassicUO.Client/Game/Managers/WalkerManager.cs deleted file mode 100644 index 7f4a7120a..000000000 --- a/src/ClassicUO.Client/Game/Managers/WalkerManager.cs +++ /dev/null @@ -1,198 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Network; - -namespace ClassicUO.Game.Managers -{ - internal struct StepInfo - { - public byte Direction; - public byte OldDirection; - public byte Sequence; - public bool Accepted; - public bool Running; - public bool NoRotation; - public long Timer; - public ushort X, Y; - public sbyte Z; - } - - internal class FastWalkStack - { - private readonly uint[] _keys = new uint[Constants.MAX_FAST_WALK_STACK_SIZE]; - - public void SetValue(int index, uint value) - { - if (index >= 0 && index < Constants.MAX_FAST_WALK_STACK_SIZE) - { - _keys[index] = value; - } - } - - public void AddValue(uint value) - { - for (int i = 0; i < Constants.MAX_FAST_WALK_STACK_SIZE; i++) - { - if (_keys[i] == 0) - { - _keys[i] = value; - - break; - } - } - } - - public uint GetValue() - { - for (int i = 0; i < Constants.MAX_FAST_WALK_STACK_SIZE; i++) - { - uint key = _keys[i]; - - if (key != 0) - { - _keys[i] = 0; - - return key; - } - } - - return 0; - } - } - - internal class WalkerManager - { - public FastWalkStack FastWalkStack { get; } = new FastWalkStack(); - public ushort CurrentPlayerZ; - public byte CurrentWalkSequence; - public long LastStepRequestTime; - public ushort NewPlayerZ; - public bool ResendPacketResync; - public readonly StepInfo[] StepInfos = new StepInfo[Constants.MAX_STEP_COUNT]; - public int StepsCount; - public int UnacceptedPacketsCount; - public bool WalkingFailed; - public byte WalkSequence; - public bool WantChangeCoordinates; - - public void DenyWalk(byte sequence, int x, int y, sbyte z) - { - World.Player.ClearSteps(); - - Reset(); - - if (x != -1) - { - World.RangeSize.X = x; - World.RangeSize.Y = y; - - World.Player.SetInWorldTile((ushort) x, (ushort) y, z); - } - } - - public void ConfirmWalk(byte sequence) - { - if (UnacceptedPacketsCount != 0) - { - UnacceptedPacketsCount--; - } - - int stepIndex = 0; - - for (int i = 0; i < StepsCount; i++) - { - if (StepInfos[i].Sequence == sequence) - { - break; - } - - stepIndex++; - } - - bool isBadStep = stepIndex == StepsCount; - - - if (!isBadStep) - { - if (stepIndex >= CurrentWalkSequence) - { - StepInfos[stepIndex].Accepted = true; - - World.RangeSize.X = StepInfos[stepIndex].X; - World.RangeSize.Y = StepInfos[stepIndex].Y; - } - else if (stepIndex == 0) - { - World.RangeSize.X = StepInfos[0].X; - World.RangeSize.Y = StepInfos[0].Y; - - for (int i = 1; i < StepsCount; i++) - { - StepInfos[i - 1] = StepInfos[i]; - } - - StepsCount--; - CurrentWalkSequence--; - } - else - { - isBadStep = true; - } - } - - if (isBadStep) - { - if (!ResendPacketResync) - { - NetClient.Socket.Send_Resync(); - ResendPacketResync = true; - } - - WalkingFailed = true; - StepsCount = 0; - CurrentWalkSequence = 0; - } - } - - public void Reset() - { - UnacceptedPacketsCount = 0; - StepsCount = 0; - WalkSequence = 0; - CurrentWalkSequence = 0; - WalkingFailed = false; - ResendPacketResync = false; - LastStepRequestTime = 0; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/WorldMapEntityManager.cs b/src/ClassicUO.Client/Game/Managers/WorldMapEntityManager.cs deleted file mode 100644 index 77df5619f..000000000 --- a/src/ClassicUO.Client/Game/Managers/WorldMapEntityManager.cs +++ /dev/null @@ -1,279 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Network; -using ClassicUO.Network.Encryption; -using ClassicUO.Utility.Logging; - -namespace ClassicUO.Game.Managers -{ - public class WMapEntity - { - public WMapEntity(uint serial) - { - Serial = serial; - - //var mob = World.Mobiles.Get(serial); - - //if (mob != null) - // GetName(); - } - - public bool IsGuild; - public uint LastUpdate; - public string Name; - public readonly uint Serial; - public int X, Y, HP, Map; - - //public string GetName() - //{ - // Entity e = World.Get(Serial); - - // if (e != null && !e.IsDestroyed && !string.IsNullOrEmpty(e.Name) && Name != e.Name) - // { - // Name = e.Name; - // } - - // return string.IsNullOrEmpty(Name) ? "" : Name; - //} - } - - public class WorldMapEntityManager - { - private bool _ackReceived; - private uint _lastUpdate, _lastPacketSend, _lastPacketRecv; - private readonly List _toRemove = new List(); - public WMapEntity _corpse; - - public bool Enabled - { - get - { - return ((World.ClientFeatures.Flags & CharacterListFlags.CLF_NEW_MOVEMENT_SYSTEM) == 0 || _ackReceived) && - EncryptionHelper.Type == 0 && - ProfileManager.CurrentProfile != null && ProfileManager.CurrentProfile.WorldMapShowParty && - UIManager.GetGump() != null; // horrible, but works - } - } - - public readonly Dictionary Entities = new Dictionary(); - - public void SetACKReceived() - { - _ackReceived = true; - } - - public void SetEnable(bool v) - { - if ((World.ClientFeatures.Flags & CharacterListFlags.CLF_NEW_MOVEMENT_SYSTEM) != 0 && !_ackReceived) - { - Log.Warn("Server support new movement system. Can't use the 0xF0 packet to query guild/party position"); - v = false; - } - else if (EncryptionHelper.Type != 0 && !_ackReceived) - { - Log.Warn("Server has encryption. Can't use the 0xF0 packet to query guild/party position"); - v = false; - } - - if (v) - { - RequestServerPartyGuildInfo(true); - } - } - - public void AddOrUpdate - ( - uint serial, - int x, - int y, - int hp, - int map, - bool isguild, - string name = null, - bool from_packet = false - ) - { - if (from_packet) - { - _lastPacketRecv = Time.Ticks + 10000; - } - else if (_lastPacketRecv < Time.Ticks) - { - return; - } - - if (!Enabled) - { - return; - } - - if (string.IsNullOrEmpty(name)) - { - Entity ent = World.Get(serial); - - if (ent != null && !string.IsNullOrEmpty(ent.Name)) - { - name = ent.Name; - } - } - - if (!Entities.TryGetValue(serial, out WMapEntity entity) || entity == null) - { - entity = new WMapEntity(serial) - { - X = x, Y = y, HP = hp, Map = map, - LastUpdate = Time.Ticks + 1000, - IsGuild = isguild, - Name = name - }; - - Entities[serial] = entity; - } - else - { - entity.X = x; - entity.Y = y; - entity.HP = hp; - entity.Map = map; - entity.IsGuild = isguild; - entity.LastUpdate = Time.Ticks + 1000; - - if (string.IsNullOrEmpty(entity.Name) && !string.IsNullOrEmpty(name)) - { - entity.Name = name; - } - } - } - - public void Remove(uint serial) - { - if (Entities.ContainsKey(serial)) - { - Entities.Remove(serial); - } - } - - public void RemoveUnupdatedWEntity() - { - if (_corpse != null && _corpse.LastUpdate < Time.Ticks - 1000) - { - _corpse = null; - } - if (_lastUpdate > Time.Ticks) - { - return; - } - - _lastUpdate = Time.Ticks + 1000; - - long ticks = Time.Ticks - 1000; - - foreach (WMapEntity entity in Entities.Values) - { - if (entity.LastUpdate < ticks) - { - _toRemove.Add(entity); - } - } - - if (_toRemove.Count != 0) - { - foreach (WMapEntity entity in _toRemove) - { - Entities.Remove(entity.Serial); - } - - _toRemove.Clear(); - } - } - - public WMapEntity GetEntity(uint serial) - { - Entities.TryGetValue(serial, out WMapEntity entity); - - return entity; - } - - public void RequestServerPartyGuildInfo(bool force = false) - { - if (!force && !Enabled) - { - return; - } - - if (World.InGame && _lastPacketSend < Time.Ticks) - { - //GameActions.Print($"SENDING PACKET! {Time.Ticks}"); - - _lastPacketSend = Time.Ticks + 250; - - //if (!force && !_can_send) - //{ - // return; - //} - - NetClient.Socket.Send_QueryGuildPosition(); - - if (World.Party != null && World.Party.Leader != 0) - { - foreach (PartyMember e in World.Party.Members) - { - if (e != null && SerialHelper.IsValid(e.Serial)) - { - Mobile mob = World.Mobiles.Get(e.Serial); - - if (mob == null || mob.Distance > World.ClientViewRange) - { - NetClient.Socket.Send_QueryPartyPosition(); - - break; - } - } - } - } - } - } - - public void Clear() - { - Entities.Clear(); - _ackReceived = false; - SetEnable(false); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Managers/WorldTextManager.cs b/src/ClassicUO.Client/Game/Managers/WorldTextManager.cs deleted file mode 100644 index c7342da4e..000000000 --- a/src/ClassicUO.Client/Game/Managers/WorldTextManager.cs +++ /dev/null @@ -1,162 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Game.GameObjects; -using ClassicUO.Renderer; - -namespace ClassicUO.Game.Managers -{ - public class WorldTextManager : TextRenderer - { - private readonly Dictionary _damages = new Dictionary(); - private readonly List> _subst = new List>(); - private readonly List _toRemoveDamages = new List(); - - - public override void Update() - { - base.Update(); - - - UpdateDamageOverhead(); - - if (_toRemoveDamages.Count > 0) - { - foreach (uint s in _toRemoveDamages) - { - _damages.Remove(s); - } - - _toRemoveDamages.Clear(); - } - } - - - public override void Draw(UltimaBatcher2D batcher, int startX, int startY, bool isGump = false) - { - base.Draw - ( - batcher, - startX, - startY, - isGump - ); - - foreach (KeyValuePair overheadDamage in _damages) - { - Entity mob = World.Get(overheadDamage.Key); - - if (mob == null || mob.IsDestroyed) - { - uint ser = overheadDamage.Key | 0x8000_0000; - - if (World.CorpseManager.Exists(0, ser)) - { - Item item = World.CorpseManager.GetCorpseObject(ser); - - if (item != null && !ReferenceEquals(item, overheadDamage.Value.Parent)) - { - _subst.Add(Tuple.Create(overheadDamage.Key, item.Serial)); - overheadDamage.Value.SetParent(item); - } - } - else - { - continue; - } - } - - overheadDamage.Value.Draw(batcher); - } - } - - private void UpdateDamageOverhead() - { - if (_subst.Count != 0) - { - foreach (Tuple tuple in _subst) - { - if (_damages.TryGetValue(tuple.Item1, out OverheadDamage dmg)) - { - _damages.Remove(tuple.Item1); - _damages[tuple.Item2] = dmg; - } - } - - _subst.Clear(); - } - - foreach (KeyValuePair overheadDamage in _damages) - { - overheadDamage.Value.Update(); - - if (overheadDamage.Value.IsEmpty) - { - _toRemoveDamages.Add(overheadDamage.Key); - } - } - } - - - internal void AddDamage(uint obj, int dmg) - { - if (!_damages.TryGetValue(obj, out OverheadDamage dm) || dm == null) - { - dm = new OverheadDamage(World.Get(obj)); - _damages[obj] = dm; - } - - dm.Add(dmg); - } - - public override void Clear() - { - if (_toRemoveDamages.Count > 0) - { - foreach (uint s in _toRemoveDamages) - { - _damages.Remove(s); - } - - _toRemoveDamages.Clear(); - } - - _subst.Clear(); - - //_staticToUpdate.Clear(); - - base.Clear(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Map/Chunk.cs b/src/ClassicUO.Client/Game/Map/Chunk.cs deleted file mode 100644 index b8e8f88aa..000000000 --- a/src/ClassicUO.Client/Game/Map/Chunk.cs +++ /dev/null @@ -1,475 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Assets; -using ClassicUO.Utility; - -namespace ClassicUO.Game.Map -{ - public sealed class Chunk - { - private static readonly QueuedPool _pool = new QueuedPool - ( - Constants.PREDICTABLE_CHUNKS, - c => - { - c.LastAccessTime = Time.Ticks + Constants.CLEAR_TEXTURES_DELAY; - c.IsDestroyed = false; - } - ); - - public GameObject[,] Tiles { get; } = new GameObject[8, 8]; - public bool IsDestroyed; - public long LastAccessTime; - public LinkedListNode Node; - - - public int X; - public int Y; - - - public static Chunk Create(int x, int y) - { - Chunk c = _pool.GetOne(); - c.X = x; - c.Y = y; - - return c; - } - - - public unsafe void Load(int index) - { - IsDestroyed = false; - - Map map = World.Map; - - ref IndexMap im = ref GetIndex(index); - - if (im.MapAddress != 0) - { - MapBlock* block = (MapBlock*) im.MapAddress; - MapCells* cells = (MapCells*) &block->Cells; - int bx = X << 3; - int by = Y << 3; - - for (int y = 0; y < 8; ++y) - { - int pos = y << 3; - ushort tileY = (ushort) (by + y); - - for (int x = 0; x < 8; ++x, ++pos) - { - ushort tileID = (ushort) (cells[pos].TileID & 0x3FFF); - - sbyte z = cells[pos].Z; - - Land land = Land.Create(tileID); - - ushort tileX = (ushort) (bx + x); - - land.ApplyStretch(map, tileX, tileY, z); - land.X = tileX; - land.Y = tileY; - land.Z = z; - land.UpdateScreenPosition(); - - AddGameObject(land, x, y); - } - } - - if (im.StaticAddress != 0) - { - StaticsBlock* sb = (StaticsBlock*) im.StaticAddress; - - if (sb != null) - { - for (int i = 0, count = (int) im.StaticCount; i < count; ++i, ++sb) - { - if (sb->Color != 0 && sb->Color != 0xFFFF) - { - int pos = (sb->Y << 3) + sb->X; - - if (pos >= 64) - { - continue; - } - - Static staticObject = Static.Create(sb->Color, sb->Hue, pos); - staticObject.X = (ushort) (bx + sb->X); - staticObject.Y = (ushort) (by + sb->Y); - staticObject.Z = sb->Z; - staticObject.UpdateScreenPosition(); - - AddGameObject(staticObject, sb->X, sb->Y); - } - } - } - } - } - } - - - private ref IndexMap GetIndex(int map) - { - MapLoader.Instance.SanitizeMapIndex(ref map); - - return ref MapLoader.Instance.GetIndex(map, X, Y); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public GameObject GetHeadObject(int x, int y) - { - GameObject obj = Tiles[x, y]; - - while (obj?.TPrevious != null) - { - obj = obj.TPrevious; - } - - return obj; - } - - public void AddGameObject(GameObject obj, int x, int y) - { - obj.RemoveFromTile(); - - short priorityZ = obj.Z; - sbyte state = -1; - - ushort graphic = obj.Graphic; - - switch (obj) - { - case Land tile: - - if (tile.IsStretched) - { - priorityZ = (short) (tile.AverageZ - 1); - } - else - { - priorityZ--; - } - - priorityZ -= 1; - - state = 0; - - break; - - case Mobile _: - priorityZ++; - - break; - - case Item item: - - if (item.IsCorpse) - { - priorityZ++; - - break; - } - else if (item.IsMulti) - { - graphic = item.MultiGraphic; - } - - goto default; - - case GameEffect _: - priorityZ += 2; - - break; - - case Multi m: - - state = 1; - - if ((m.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_GENERIC_INTERNAL) != 0) - { - priorityZ--; - - break; - } - - if ((m.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_PREVIEW) != 0) - { - state = 2; - priorityZ++; - } - //else if ((m.ItemData.Flags & TileFlag.StairRight) != 0) - //{ - // priorityZ++; - //} - - //if (m.IsMovable) - //{ - // priorityZ += 1; - //} - - goto default; - - default: - ref StaticTiles data = ref TileDataLoader.Instance.StaticData[graphic]; - - if (data.IsBackground) - { - priorityZ--; - } - - //if (data.IsSurface) - //{ - // priorityZ--; - //} - - if (data.Height != 0) - { - priorityZ++; - } - - if (data.IsMultiMovable) - { - priorityZ++; - } - - break; - } - - obj.PriorityZ = priorityZ; - - if (Tiles[x, y] == null) - { - Tiles[x, y] = obj; - obj.TPrevious = null; - obj.TNext = null; - - return; - } - - - GameObject o = Tiles[x, y]; - - if (o == obj) - { - if (o.Previous != null) - { - o = (GameObject) o.Previous; - } - else if (o.Next != null) - { - o = (GameObject) o.Next; - } - else - { - return; - } - } - - while (o?.TPrevious != null) - { - o = o.TPrevious; - } - - GameObject found = null; - GameObject start = o; - - while (o != null) - { - int testPriorityZ = o.PriorityZ; - - if (testPriorityZ > priorityZ || testPriorityZ == priorityZ && (state == 0 || state == 1 && !(o is Land))) - { - break; - } - - found = o; - o = o.TNext; - } - - if (found != null) - { - obj.TPrevious = found; - GameObject next = found.TNext; - obj.TNext = next; - found.TNext = obj; - - if (next != null) - { - next.TPrevious = obj; - } - } - else if (start != null) - { - obj.TNext = start; - start.TPrevious = obj; - obj.TPrevious = null; - } - } - - public void RemoveGameObject(GameObject obj, int x, int y) - { - ref GameObject firstNode = ref Tiles[x, y]; - - if (firstNode == null || obj == null) - { - return; - } - - if (firstNode == obj) - { - firstNode = obj.TNext; - } - - if (obj.TNext != null) - { - obj.TNext.TPrevious = obj.TPrevious; - } - - if (obj.TPrevious != null) - { - obj.TPrevious.TNext = obj.TNext; - } - - obj.TPrevious = null; - obj.TNext = null; - } - - - public void Destroy() - { - for (int i = 0; i < 8; i++) - { - for (int j = 0; j < 8; j++) - { - GameObject obj = Tiles[i, j]; - - if (obj == null) - { - continue; - } - - GameObject first = GetHeadObject(i, j); - - while (first != null) - { - GameObject next = first.TNext; - - if (!ReferenceEquals(first, World.Player)) - { - first.Destroy(); - } - - first.TPrevious = null; - first.TNext = null; - first = next; - } - - Tiles[i, j] = null; - } - } - - if (Node.Next != null || Node.Previous != null) - { - Node.List?.Remove(Node); - } - - IsDestroyed = true; - _pool.ReturnOne(this); - } - - public void Clear() - { - for (int i = 0; i < 8; i++) - { - for (int j = 0; j < 8; j++) - { - GameObject obj = Tiles[i, j]; - - if (obj == null) - { - continue; - } - - GameObject first = GetHeadObject(i, j); - - while (first != null) - { - GameObject next = first.TNext; - - if (!ReferenceEquals(first, World.Player)) - { - first.Destroy(); - } - - first.TPrevious = null; - first.TNext = null; - first = next; - } - - Tiles[i, j] = null; - } - } - - if (Node.Next != null || Node.Previous != null) - { - Node.List?.Remove(Node); - } - - IsDestroyed = true; - } - - public bool HasNoExternalData() - { - for (int i = 0; i < 8; i++) - { - for (int j = 0; j < 8; j++) - { - for (GameObject obj = GetHeadObject(i, j); obj != null; obj = obj.TNext) - { - if (!(obj is Land) && !(obj is Static) /*&& !(obj is Multi)*/) - { - return false; - } - } - } - } - - return true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Map/Map.cs b/src/ClassicUO.Client/Game/Map/Map.cs deleted file mode 100644 index 4c3099cbc..000000000 --- a/src/ClassicUO.Client/Game/Map/Map.cs +++ /dev/null @@ -1,333 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using ClassicUO.Game.GameObjects; -using ClassicUO.Assets; - -namespace ClassicUO.Game.Map -{ - public sealed class Map - { - private static readonly Chunk[] _terrainChunks; - private static readonly bool[] _blockAccessList = new bool[0x1000]; - private readonly LinkedList _usedIndices = new LinkedList(); - - static Map() - { - int maxX = -1, maxY = -1; - - for (int i = 0; i < MapLoader.Instance.MapBlocksSize.GetLength(0); i++) - { - if (maxX < MapLoader.Instance.MapBlocksSize[i, 0]) - { - maxX = MapLoader.Instance.MapBlocksSize[i, 0]; - } - - if (maxY < MapLoader.Instance.MapBlocksSize[i, 1]) - { - maxY = MapLoader.Instance.MapBlocksSize[i, 1]; - } - } - - - _terrainChunks = new Chunk[maxX * maxY]; - } - - public Map(int index) - { - Index = index; - BlocksCount = MapLoader.Instance.MapBlocksSize[Index, 0] * MapLoader.Instance.MapBlocksSize[Index, 1]; - ClearBockAccess(); - } - - public readonly int BlocksCount; - public readonly int Index; - - - - - public Chunk GetChunk(int block) - { - if (block >= 0 && block < BlocksCount) - { - return _terrainChunks[block]; - } - - return null; - } - - public Chunk GetChunk(int x, int y, bool load = true) - { - if (x < 0 || y < 0) - { - return null; - } - - int cellX = x >> 3; - int cellY = y >> 3; - int block = GetBlock(cellX, cellY); - - if (block >= BlocksCount) - { - return null; - } - - ref Chunk chunk = ref _terrainChunks[block]; - - if (chunk == null) - { - if (!load) - { - return null; - } - - LinkedListNode node = _usedIndices.AddLast(block); - chunk = Chunk.Create(cellX, cellY); - chunk.Load(Index); - chunk.Node = node; - } - else if (chunk.IsDestroyed) - { - // make sure node is clear - if (chunk.Node != null && (chunk.Node.Previous != null || chunk.Node.Next != null)) - { - chunk.Node.List?.Remove(chunk.Node); - } - - LinkedListNode node = _usedIndices.AddLast(block); - chunk.X = cellX; - chunk.Y = cellY; - chunk.Load(Index); - chunk.Node = node; - } - - chunk.LastAccessTime = Time.Ticks; - - return chunk; - } - - - public GameObject GetTile(int x, int y, bool load = true) - { - return GetChunk(x, y, load)?.GetHeadObject(x % 8, y % 8); - } - - public sbyte GetTileZ(int x, int y) - { - if (x < 0 || y < 0) - { - return -125; - } - - ref IndexMap blockIndex = ref GetIndex(x >> 3, y >> 3); - - if (blockIndex.MapAddress == 0) - { - return -125; - } - - int mx = x % 8; - int my = y % 8; - - unsafe - { - MapBlock* mp = (MapBlock*) blockIndex.MapAddress; - MapCells* cells = (MapCells*) &mp->Cells; - - return cells[(my << 3) + mx].Z; - } - } - - public void GetMapZ(int x, int y, out sbyte groundZ, out sbyte staticZ) - { - Chunk chunk = GetChunk(x, y); - //var obj = GetTile(x, y); - groundZ = staticZ = 0; - - if (chunk == null) - { - return; - } - - GameObject obj = chunk.Tiles[x % 8, y % 8]; - - while (obj != null) - { - if (obj is Land) - { - groundZ = obj.Z; - } - else if (staticZ < obj.Z) - { - staticZ = obj.Z; - } - - obj = obj.TNext; - } - } - - public void ClearBockAccess() - { - _blockAccessList.AsSpan().Fill(false); - } - - public sbyte CalculateNearZ(sbyte defaultZ, int x, int y, int z) - { - ref bool access = ref _blockAccessList[(x & 0x3F) + ((y & 0x3F) << 6)]; - - if (access) - { - return defaultZ; - } - - access = true; - Chunk chunk = GetChunk(x, y, false); - - if (chunk != null) - { - GameObject obj = chunk.Tiles[x % 8, y % 8]; - - for (; obj != null; obj = obj.TNext) - { - if (!(obj is Static) && !(obj is Multi)) - { - continue; - } - - if (obj.Graphic >= TileDataLoader.Instance.StaticData.Length) - { - continue; - } - - if (!TileDataLoader.Instance.StaticData[obj.Graphic].IsRoof || Math.Abs(z - obj.Z) > 6) - { - continue; - } - - break; - } - - if (obj == null) - { - return defaultZ; - } - - sbyte tileZ = obj.Z; - - if (tileZ < defaultZ) - { - defaultZ = tileZ; - } - - defaultZ = CalculateNearZ(defaultZ, x - 1, y, tileZ); - defaultZ = CalculateNearZ(defaultZ, x + 1, y, tileZ); - defaultZ = CalculateNearZ(defaultZ, x, y - 1, tileZ); - defaultZ = CalculateNearZ(defaultZ, x, y + 1, tileZ); - } - - return defaultZ; - } - - - public ref IndexMap GetIndex(int blockX, int blockY) - { - int block = GetBlock(blockX, blockY); - int map = Index; - MapLoader.Instance.SanitizeMapIndex(ref map); - IndexMap[] list = MapLoader.Instance.BlockData[map]; - - return ref block >= list.Length ? ref IndexMap.Invalid : ref list[block]; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private int GetBlock(int blockX, int blockY) - { - return blockX * MapLoader.Instance.MapBlocksSize[Index, 1] + blockY; - } - - public IEnumerable GetUsedChunks() - { - foreach (int i in _usedIndices) - { - yield return GetChunk(i); - } - } - - - public void ClearUnusedBlocks() - { - int count = 0; - long ticks = Time.Ticks - Constants.CLEAR_TEXTURES_DELAY; - - LinkedListNode first = _usedIndices.First; - - while (first != null) - { - LinkedListNode next = first.Next; - - ref Chunk block = ref _terrainChunks[first.Value]; - - if (block != null && block.LastAccessTime < ticks && block.HasNoExternalData()) - { - block.Destroy(); - block = null; - - if (++count >= Constants.MAX_MAP_OBJECT_REMOVED_BY_GARBAGE_COLLECTOR) - { - break; - } - } - - first = next; - } - } - - public void Destroy() - { - LinkedListNode first = _usedIndices.First; - - while (first != null) - { - LinkedListNode next = first.Next; - ref Chunk c = ref _terrainChunks[first.Value]; - c?.Destroy(); - c = null; - first = next; - } - - _usedIndices.Clear(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Pathfinder.cs b/src/ClassicUO.Client/Game/Pathfinder.cs deleted file mode 100644 index 55c4162dd..000000000 --- a/src/ClassicUO.Client/Game/Pathfinder.cs +++ /dev/null @@ -1,1131 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Assets; -using Microsoft.Xna.Framework; -using MathHelper = ClassicUO.Utility.MathHelper; - -namespace ClassicUO.Game -{ - public static class Pathfinder - { - private const int PATHFINDER_MAX_NODES = 15000; - private static int _goalNode; - private static bool _goalFound; - private static int _activeOpenNodes, _activeCloseNodes, _pathfindDistance; - private static readonly PathNode[] _openList = new PathNode[PATHFINDER_MAX_NODES]; - private static readonly PathNode[] _closedList = new PathNode[PATHFINDER_MAX_NODES]; - private static readonly PathNode[] _path = new PathNode[PATHFINDER_MAX_NODES]; - private static int _pointIndex, _pathSize; - private static bool _run; - private static readonly int[] _offsetX = - { - 0, 1, 1, 1, 0, -1, -1, -1, 0, 1 - }; - private static readonly int[] _offsetY = - { - -1, -1, 0, 1, 1, 1, 0, -1, -1, -1 - }; - private static readonly sbyte[] _dirOffset = - { - 1, -1 - }; - private static Point _startPoint, _endPoint; - - public static Point StartPoint => _startPoint; - public static Point EndPoint => _endPoint; - public static int PathSize => _pathSize; - - public static bool AutoWalking { get; set; } - - public static bool PathindingCanBeCancelled { get; set; } - - public static bool BlockMoving { get; set; } - - public static bool FastRotation { get; set; } - - - private static bool CreateItemList(List list, int x, int y, int stepState) - { - GameObject tile = World.Map.GetTile(x, y, false); - - if (tile == null) - { - return false; - } - - bool ignoreGameCharacters = ProfileManager.CurrentProfile.IgnoreStaminaCheck || stepState == (int) PATH_STEP_STATE.PSS_DEAD_OR_GM || World.Player.IgnoreCharacters || !(World.Player.Stamina < World.Player.StaminaMax && World.Map.Index == 0); - - bool isGM = World.Player.Graphic == 0x03DB; - - GameObject obj = tile; - - while (obj.TPrevious != null) - { - obj = obj.TPrevious; - } - - for (; obj != null; obj = obj.TNext) - { - if (World.CustomHouseManager != null && obj.Z < World.Player.Z) - { - continue; - } - - ushort graphicHelper = obj.Graphic; - - switch (obj) - { - case Land tile1: - - if (graphicHelper < 0x01AE && graphicHelper != 2 || graphicHelper > 0x01B5 && graphicHelper != 0x01DB) - { - uint flags = (uint) PATH_OBJECT_FLAGS.POF_IMPASSABLE_OR_SURFACE; - - if (stepState == (int) PATH_STEP_STATE.PSS_ON_SEA_HORSE) - { - if (tile1.TileData.IsWet) - { - flags = (uint) (PATH_OBJECT_FLAGS.POF_IMPASSABLE_OR_SURFACE | PATH_OBJECT_FLAGS.POF_SURFACE | PATH_OBJECT_FLAGS.POF_BRIDGE); - } - } - else - { - if (!tile1.TileData.IsImpassable) - { - flags = (uint) (PATH_OBJECT_FLAGS.POF_IMPASSABLE_OR_SURFACE | PATH_OBJECT_FLAGS.POF_SURFACE | PATH_OBJECT_FLAGS.POF_BRIDGE); - } - - if (stepState == (int) PATH_STEP_STATE.PSS_FLYING && tile1.TileData.IsNoDiagonal) - { - flags |= (uint) PATH_OBJECT_FLAGS.POF_NO_DIAGONAL; - } - } - - int landMinZ = tile1.MinZ; - int landAverageZ = tile1.AverageZ; - int landHeight = landAverageZ - landMinZ; - - list.Add - ( - new PathObject - ( - flags, - landMinZ, - landAverageZ, - landHeight, - obj - ) - ); - } - - break; - - case GameEffect _: break; - - default: - bool canBeAdd = true; - bool dropFlags = false; - - switch (obj) - { - case Mobile mobile: - { - if (!ignoreGameCharacters && !mobile.IsDead && !mobile.IgnoreCharacters) - { - list.Add - ( - new PathObject - ( - (uint) PATH_OBJECT_FLAGS.POF_IMPASSABLE_OR_SURFACE, - mobile.Z, - mobile.Z + Constants.DEFAULT_CHARACTER_HEIGHT, - Constants.DEFAULT_CHARACTER_HEIGHT, - mobile - ) - ); - } - - canBeAdd = false; - - break; - } - - case Item item when item.IsMulti || item.ItemData.IsInternal: - { - //canBeAdd = false; - - break; - } - - case Item item2: - if (stepState == (int) PATH_STEP_STATE.PSS_DEAD_OR_GM && (item2.ItemData.IsDoor || item2.ItemData.Weight <= 0x5A || isGM && !item2.IsLocked)) - { - dropFlags = true; - } - else if (ProfileManager.CurrentProfile.SmoothDoors && item2.ItemData.IsDoor) - { - dropFlags = true; - } - else - { - dropFlags = graphicHelper >= 0x3946 && graphicHelper <= 0x3964 || graphicHelper == 0x0082; - } - - break; - - case Multi m: - - if ((World.CustomHouseManager != null && m.IsCustom && (m.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_GENERIC_INTERNAL) == 0) || m.IsHousePreview) - { - canBeAdd = false; - } - - if ((m.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_IGNORE_IN_RENDER) != 0) - { - dropFlags = true; - } - - break; - } - - if (canBeAdd) - { - uint flags = 0; - - if (!(obj is Mobile)) - { - var graphic = obj is Item it && it.IsMulti ? it.MultiGraphic : obj.Graphic; - ref StaticTiles itemdata = ref TileDataLoader.Instance.StaticData[graphic]; - - if (stepState == (int) PATH_STEP_STATE.PSS_ON_SEA_HORSE) - { - if (itemdata.IsWet) - { - flags = (uint) (PATH_OBJECT_FLAGS.POF_SURFACE | PATH_OBJECT_FLAGS.POF_BRIDGE); - } - } - else - { - if (itemdata.IsImpassable || itemdata.IsSurface) - { - flags = (uint) PATH_OBJECT_FLAGS.POF_IMPASSABLE_OR_SURFACE; - } - - if (!itemdata.IsImpassable) - { - if (itemdata.IsSurface) - { - flags |= (uint) PATH_OBJECT_FLAGS.POF_SURFACE; - } - - if (itemdata.IsBridge) - { - flags |= (uint) PATH_OBJECT_FLAGS.POF_BRIDGE; - } - } - - if (stepState == (int) PATH_STEP_STATE.PSS_DEAD_OR_GM) - { - if (graphicHelper <= 0x0846) - { - if (!(graphicHelper != 0x0846 && graphicHelper != 0x0692 && (graphicHelper <= 0x06F4 || graphicHelper > 0x06F6))) - { - dropFlags = true; - } - } - else if (graphicHelper == 0x0873) - { - dropFlags = true; - } - } - - if (dropFlags) - { - flags &= 0xFFFFFFFE; - } - - if (stepState == (int) PATH_STEP_STATE.PSS_FLYING && itemdata.IsNoDiagonal) - { - flags |= (uint) PATH_OBJECT_FLAGS.POF_NO_DIAGONAL; - } - } - - if (flags != 0) - { - int objZ = obj.Z; - int staticHeight = itemdata.Height; - int staticAverageZ = staticHeight; - - if (itemdata.IsBridge) - { - staticAverageZ /= 2; - // revert fix from fwiffo because it causes unwalkable stairs [down --> up] - //staticAverageZ += staticHeight % 2; - } - - list.Add - ( - new PathObject - ( - flags, - objZ, - staticAverageZ + objZ, - staticHeight, - obj - ) - ); - } - } - } - - break; - } - } - - return list.Count != 0; - } - - private static int CalculateMinMaxZ - ( - ref int minZ, - ref int maxZ, - int newX, - int newY, - int currentZ, - int newDirection, - int stepState - ) - { - minZ = -128; - maxZ = currentZ; - newDirection &= 7; - int direction = newDirection ^ 4; - newX += _offsetX[direction]; - newY += _offsetY[direction]; - List list = new List(); - - if (!CreateItemList(list, newX, newY, stepState) || list.Count == 0) - { - return 0; - } - - foreach (PathObject obj in list) - { - GameObject o = obj.Object; - int averageZ = obj.AverageZ; - - if (averageZ <= currentZ && o is Land tile && tile.IsStretched) - { - int avgZ = tile.CalculateCurrentAverageZ(newDirection); - - if (minZ < avgZ) - { - minZ = avgZ; - } - - if (maxZ < avgZ) - { - maxZ = avgZ; - } - } - else - { - if ((obj.Flags & (uint) PATH_OBJECT_FLAGS.POF_IMPASSABLE_OR_SURFACE) != 0 && averageZ <= currentZ && minZ < averageZ) - { - minZ = averageZ; - } - - if ((obj.Flags & (uint) PATH_OBJECT_FLAGS.POF_BRIDGE) != 0 && currentZ == averageZ) - { - int z = obj.Z; - int height = z + obj.Height; - - if (maxZ < height) - { - maxZ = height; - } - - if (minZ > z) - { - minZ = z; - } - } - } - } - - maxZ += 2; - - return maxZ; - } - - public static bool CalculateNewZ(int x, int y, ref sbyte z, int direction) - { - int stepState = (int) PATH_STEP_STATE.PSS_NORMAL; - - if (World.Player.IsDead || World.Player.Graphic == 0x03DB) - { - stepState = (int) PATH_STEP_STATE.PSS_DEAD_OR_GM; - } - else - { - if (World.Player.IsGargoyle && World.Player.IsFlying) - { - stepState = (int) PATH_STEP_STATE.PSS_FLYING; - } - else - { - Item mount = World.Player.FindItemByLayer(Layer.Mount); - - if (mount != null && mount.Graphic == 0x3EB3) // sea horse - { - stepState = (int) PATH_STEP_STATE.PSS_ON_SEA_HORSE; - } - } - } - - int minZ = -128; - int maxZ = z; - - CalculateMinMaxZ - ( - ref minZ, - ref maxZ, - x, - y, - z, - direction, - stepState - ); - - List list = new List(); - - if (World.CustomHouseManager != null) - { - Rectangle rect = new Rectangle(World.CustomHouseManager.StartPos.X, World.CustomHouseManager.StartPos.Y, World.CustomHouseManager.EndPos.X, World.CustomHouseManager.EndPos.Y); - - if (!rect.Contains(x, y)) - { - return false; - } - } - - if (!CreateItemList(list, x, y, stepState) || list.Count == 0) - { - return false; - } - - list.Sort(); - - list.Add - ( - new PathObject - ( - (uint) PATH_OBJECT_FLAGS.POF_IMPASSABLE_OR_SURFACE, - 128, - 128, - 128, - null - ) - ); - - int resultZ = -128; - - if (z < minZ) - { - z = (sbyte) minZ; - } - - int currentTempObjZ = 1000000; - int currentZ = -128; - - for (int i = 0; i < list.Count; i++) - { - PathObject obj = list[i]; - - if ((obj.Flags & (uint) PATH_OBJECT_FLAGS.POF_NO_DIAGONAL) != 0 && stepState == (int) PATH_STEP_STATE.PSS_FLYING) - { - int objAverageZ = obj.AverageZ; - int delta = Math.Abs(objAverageZ - z); - - if (delta <= 25) - { - resultZ = objAverageZ != -128 ? objAverageZ : currentZ; - - break; - } - } - - if ((obj.Flags & (uint) PATH_OBJECT_FLAGS.POF_IMPASSABLE_OR_SURFACE) != 0) - { - int objZ = obj.Z; - - if (objZ - minZ >= Constants.DEFAULT_BLOCK_HEIGHT) - { - for (int j = i - 1; j >= 0; j--) - { - PathObject tempObj = list[j]; - - if ((tempObj.Flags & (uint) (PATH_OBJECT_FLAGS.POF_SURFACE | PATH_OBJECT_FLAGS.POF_BRIDGE)) != 0) - { - int tempAverageZ = tempObj.AverageZ; - - if (tempAverageZ >= currentZ && objZ - tempAverageZ >= Constants.DEFAULT_BLOCK_HEIGHT && (tempAverageZ <= maxZ && (tempObj.Flags & (uint) PATH_OBJECT_FLAGS.POF_SURFACE) != 0 || (tempObj.Flags & (uint) PATH_OBJECT_FLAGS.POF_BRIDGE) != 0 && tempObj.Z <= maxZ)) - { - int delta = Math.Abs(z - tempAverageZ); - - if (delta < currentTempObjZ) - { - currentTempObjZ = delta; - resultZ = tempAverageZ; - } - } - } - } - } - - int averageZ = obj.AverageZ; - - if (minZ < averageZ) - { - minZ = averageZ; - } - - if (currentZ < averageZ) - { - currentZ = averageZ; - } - } - } - - z = (sbyte) resultZ; - - return resultZ != -128; - } - - public static void GetNewXY(byte direction, ref int x, ref int y) - { - switch (direction & 7) - { - case 0: - - { - y--; - - break; - } - - case 1: - - { - x++; - y--; - - break; - } - - case 2: - - { - x++; - - break; - } - - case 3: - - { - x++; - y++; - - break; - } - - case 4: - - { - y++; - - break; - } - - case 5: - - { - x--; - y++; - - break; - } - - case 6: - - { - x--; - - break; - } - - case 7: - - { - x--; - y--; - - break; - } - } - } - - public static bool CanWalk(ref Direction direction, ref int x, ref int y, ref sbyte z) - { - int newX = x; - int newY = y; - sbyte newZ = z; - byte newDirection = (byte) direction; - GetNewXY((byte) direction, ref newX, ref newY); - bool passed = CalculateNewZ(newX, newY, ref newZ, (byte) direction); - - if ((sbyte) direction % 2 != 0) - { - if (passed) - { - for (int i = 0; i < 2 && passed; i++) - { - int testX = x; - int testY = y; - sbyte testZ = z; - byte testDir = (byte) (((byte) direction + _dirOffset[i]) % 8); - GetNewXY(testDir, ref testX, ref testY); - passed = CalculateNewZ(testX, testY, ref testZ, testDir); - } - } - - if (!passed) - { - for (int i = 0; i < 2 && !passed; i++) - { - newX = x; - newY = y; - newZ = z; - newDirection = (byte) (((byte) direction + _dirOffset[i]) % 8); - GetNewXY(newDirection, ref newX, ref newY); - passed = CalculateNewZ(newX, newY, ref newZ, newDirection); - } - } - } - - if (passed) - { - x = newX; - y = newY; - z = newZ; - direction = (Direction) newDirection; - } - - return passed; - } - - private static int GetGoalDistCost(Point point, int cost) - { - //return (Math.Abs(_endPoint.X - point.X) + Math.Abs(_endPoint.Y - point.Y)) * cost; - return Math.Max(Math.Abs(_endPoint.X - point.X), Math.Abs(_endPoint.Y - point.Y)); - } - - private static bool DoesNotExistOnOpenList(int x, int y, int z) - { - for (int i = 0; i < PATHFINDER_MAX_NODES; i++) - { - PathNode node = _openList[i]; - - if (node.Used && node.X == x && node.Y == y && node.Z == z) - { - return true; - } - } - - return false; - } - - private static bool DoesNotExistOnClosedList(int x, int y, int z) - { - for (int i = 0; i < PATHFINDER_MAX_NODES; i++) - { - PathNode node = _closedList[i]; - - if (node.Used && node.X == x && node.Y == y && node.Z == z) - { - return true; - } - } - - return false; - } - - private static int AddNodeToList - ( - int list, - int direction, - int x, - int y, - int z, - PathNode parent, - int cost - ) - { - if (list == 0) - { - if (!DoesNotExistOnClosedList(x, y, z)) - { - if (!DoesNotExistOnOpenList(x, y, z)) - { - for (int i = 0; i < PATHFINDER_MAX_NODES; i++) - { - PathNode node = _openList[i]; - - if (!node.Used) - { - node.Used = true; - node.Direction = direction; - node.X = x; - node.Y = y; - node.Z = z; - Point p = new Point(x, y); - node.DistFromGoalCost = GetGoalDistCost(p, cost); - node.DistFromStartCost = parent.DistFromStartCost + cost; - node.Cost = node.DistFromGoalCost + node.DistFromStartCost; - node.Parent = parent; - - if (MathHelper.GetDistance(_endPoint, p) <= _pathfindDistance) - { - _goalFound = true; - _goalNode = i; - } - - _activeOpenNodes++; - - return i; - } - } - } - else - { - for (int i = 0; i < PATHFINDER_MAX_NODES; i++) - { - PathNode node = _openList[i]; - - if (node.Used) - { - if (node.X == x && node.Y == y && node.Z == z) - { - int startCost = parent.DistFromStartCost + cost; - - if (node.DistFromStartCost > startCost) - { - node.Parent = parent; - node.DistFromStartCost = startCost + cost; - node.Cost = node.DistFromGoalCost + node.DistFromStartCost; - } - - return i; - } - } - } - } - } - else - { - return 0; - } - } - else - { - parent.Used = false; - - for (int i = 0; i < PATHFINDER_MAX_NODES; i++) - { - PathNode node = _closedList[i]; - - if (!node.Used) - { - node.Used = true; - node.DistFromGoalCost = parent.DistFromGoalCost; - node.DistFromStartCost = parent.DistFromStartCost; - node.Cost = node.DistFromGoalCost + node.DistFromStartCost; - node.Direction = parent.Direction; - node.X = parent.X; - node.Y = parent.Y; - node.Z = parent.Z; - node.Parent = parent.Parent; - _activeOpenNodes--; - _activeCloseNodes++; - - return i; - } - } - } - - return -1; - } - - private static bool OpenNodes(PathNode node) - { - bool found = false; - - for (int i = 0; i < 8; i++) - { - Direction direction = (Direction) i; - int x = node.X; - int y = node.Y; - sbyte z = (sbyte) node.Z; - Direction oldDirection = direction; - - if (CanWalk(ref direction, ref x, ref y, ref z)) - { - if (direction != oldDirection) - { - continue; - } - - int diagonal = i % 2; - - if (diagonal != 0) - { - Direction wantDirection = (Direction) i; - int wantX = node.X; - int wantY = node.Y; - GetNewXY((byte) wantDirection, ref wantX, ref wantY); - - if (x != wantX || y != wantY) - { - diagonal = -1; - } - } - - if (diagonal >= 0 && AddNodeToList - ( - 0, - (int) direction, - x, - y, - z, - node, - diagonal == 0 ? 1 : 2 - ) != -1) - { - found = true; - } - } - } - - return found; - } - - private static int FindCheapestNode() - { - int cheapestCost = 9999999; - int cheapestNode = -1; - - for (int i = 0; i < PATHFINDER_MAX_NODES; i++) - { - if (_openList[i].Used) - { - if (_openList[i].Cost < cheapestCost) - { - cheapestNode = i; - - cheapestCost = _openList[i].Cost; - } - } - } - - int result = -1; - - if (cheapestNode != -1) - { - result = AddNodeToList - ( - 1, - 0, - 0, - 0, - 0, - _openList[cheapestNode], - 2 - ); - } - - return result; - } - - private static bool FindPath(int maxNodes) - { - int curNode = 0; - - _closedList[0].Used = true; - _closedList[0].X = _startPoint.X; - _closedList[0].Y = _startPoint.Y; - _closedList[0].Z = World.Player.Z; - _closedList[0].Parent = null; - _closedList[0].DistFromGoalCost = GetGoalDistCost(_startPoint, 0); - _closedList[0].Cost = _closedList[0].DistFromGoalCost; - - if (GetGoalDistCost(_startPoint, 0) > 14) - { - _run = true; - } - - while (AutoWalking) - { - OpenNodes(_closedList[curNode]); - - if (_goalFound) - { - int totalNodes = 0; - PathNode goalNode = _openList[_goalNode]; - - while (goalNode.Parent != null && goalNode != goalNode.Parent) - { - goalNode = goalNode.Parent; - totalNodes++; - } - - totalNodes++; - _pathSize = totalNodes; - goalNode = _openList[_goalNode]; - - while (totalNodes > 0) - { - totalNodes--; - _path[totalNodes] = goalNode; - goalNode = goalNode.Parent; - } - - break; - } - - curNode = FindCheapestNode(); - - if (curNode == -1) - { - return false; - } - - if (_activeCloseNodes >= maxNodes) - { - return false; - } - } - - return true; - } - - public static bool WalkTo(int x, int y, int z, int distance) - { - if (World.Player == null /*|| World.Player.Stamina == 0*/ || World.Player.IsParalyzed) - { - return false; - } - - EventSink.InvokeOnPathFinding(null, new Vector4(x, y, z, distance)); - - for (int i = 0; i < PATHFINDER_MAX_NODES; i++) - { - if (_openList[i] == null) - { - _openList[i] = new PathNode(); - } - - _openList[i].Reset(); - - if (_closedList[i] == null) - { - _closedList[i] = new PathNode(); - } - - _closedList[i].Reset(); - } - - - int playerX = World.Player.X; - int playerY = World.Player.Y; - //sbyte playerZ = 0; - //Direction playerDir = Direction.None; - - //World.Player.GetEndPosition(ref playerX, ref playerY, ref playerZ, ref playerDir); - _startPoint.X = playerX; - _startPoint.Y = playerY; - _endPoint.X = x; - _endPoint.Y = y; - _goalNode = 0; - _goalFound = false; - _activeOpenNodes = 0; - _activeCloseNodes = 0; - _pathfindDistance = distance; - _pathSize = 0; - PathindingCanBeCancelled = true; - StopAutoWalk(); - AutoWalking = true; - - if (FindPath(PATHFINDER_MAX_NODES)) - { - _pointIndex = 1; - ProcessAutoWalk(); - } - else - { - AutoWalking = false; - } - - return _pathSize != 0; - } - - public static void ProcessAutoWalk() - { - if (AutoWalking && World.InGame && World.Player.Walker.StepsCount < Constants.MAX_STEP_COUNT && World.Player.Walker.LastStepRequestTime <= Time.Ticks) - { - if (_pointIndex >= 0 && _pointIndex < _pathSize) - { - PathNode p = _path[_pointIndex]; - - World.Player.GetEndPosition(out int x, out int y, out sbyte z, out Direction dir); - - if (dir == (Direction) p.Direction) - { - _pointIndex++; - } - - if (!World.Player.Walk((Direction) p.Direction, _run)) - { - StopAutoWalk(); - } - } - else - { - StopAutoWalk(); - } - } - } - - public static void StopAutoWalk() - { - AutoWalking = false; - _run = false; - _pathSize = 0; - } - - private enum PATH_STEP_STATE - { - PSS_NORMAL = 0, - PSS_DEAD_OR_GM, - PSS_ON_SEA_HORSE, - PSS_FLYING - } - - [Flags] - private enum PATH_OBJECT_FLAGS : uint - { - POF_IMPASSABLE_OR_SURFACE = 0x00000001, - POF_SURFACE = 0x00000002, - POF_BRIDGE = 0x00000004, - POF_NO_DIAGONAL = 0x00000008 - } - - private class PathObject : IComparable - { - public PathObject(uint flags, int z, int avgZ, int h, GameObject obj) - { - Flags = flags; - Z = z; - AverageZ = avgZ; - Height = h; - Object = obj; - } - - public uint Flags { get; } - - public int Z { get; } - - public int AverageZ { get; } - - public int Height { get; } - - public GameObject Object { get; } - - public int CompareTo(PathObject other) - { - int comparision = Z - other.Z; - - if (comparision == 0) - { - comparision = Height - other.Height; - } - - return comparision; - } - } - - private class PathNode - { - public int X { get; set; } - - public int Y { get; set; } - - public int Z { get; set; } - - public int Direction { get; set; } - - public bool Used { get; set; } - - public int Cost { get; set; } - - public int DistFromStartCost { get; set; } - - public int DistFromGoalCost { get; set; } - - public PathNode Parent { get; set; } - - public void Reset() - { - Parent = null; - Used = false; - X = Y = Z = Direction = Cost = DistFromGoalCost = DistFromStartCost = 0; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/ScanModeObject.cs b/src/ClassicUO.Client/Game/ScanModeObject.cs deleted file mode 100644 index eca7c8e5e..000000000 --- a/src/ClassicUO.Client/Game/ScanModeObject.cs +++ /dev/null @@ -1,41 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game -{ - internal enum ScanModeObject - { - Next = 0, - Previous, - Nearest - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/ScanTypeObject.cs b/src/ClassicUO.Client/Game/ScanTypeObject.cs deleted file mode 100644 index 2b26a2933..000000000 --- a/src/ClassicUO.Client/Game/ScanTypeObject.cs +++ /dev/null @@ -1,43 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game -{ - public enum ScanTypeObject - { - Hostile = 0, - Party, - Followers, - Objects, - Mobiles - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Scenes/GameScene.cs b/src/ClassicUO.Client/Game/Scenes/GameScene.cs deleted file mode 100644 index 7adb1ded3..000000000 --- a/src/ClassicUO.Client/Game/Scenes/GameScene.cs +++ /dev/null @@ -1,1457 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Net.Sockets; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Network; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using SDL2; -using ClassicUO.Game.UI; - -namespace ClassicUO.Game.Scenes -{ - internal partial class GameScene : Scene - { - private static readonly Lazy _darknessBlend = new Lazy(() => - { - BlendState state = new BlendState(); - state.ColorSourceBlend = Blend.Zero; - state.ColorDestinationBlend = Blend.SourceColor; - state.ColorBlendFunction = BlendFunction.Add; - - return state; - }); - - private static readonly Lazy _altLightsBlend = new Lazy(() => - { - BlendState state = new BlendState(); - state.ColorSourceBlend = Blend.DestinationColor; - state.ColorDestinationBlend = Blend.One; - state.ColorBlendFunction = BlendFunction.Add; - - return state; - }); - - private uint _time_cleanup = Time.Ticks + 5000; - private static XBREffect _xbr; - private bool _alphaChanged; - private long _alphaTimer; - private bool _forceStopScene; - private HealthLinesManager _healthLinesManager; - - private Point _lastSelectedMultiPositionInHouseCustomization; - private int _lightCount; - private readonly LightData[] _lights = new LightData[ - LightsLoader.MAX_LIGHTS_DATA_INDEX_COUNT - ]; - private Item _multi; - private Rectangle _rectangleObj = Rectangle.Empty, - _rectanglePlayer; - private long _timePing; - - private uint _timeToPlaceMultiInHouseCustomization; - private readonly bool _use_render_target = false; - private UseItemQueue _useItemQueue = new UseItemQueue(); - private bool _useObjectHandles; - private RenderTarget2D _world_render_target, - _lightRenderTarget; - private AnimatedStaticsManager _animatedStaticsManager; - - public bool UpdateDrawPosition { get; set; } - public HotkeysManager Hotkeys { get; private set; } - public MacroManager Macros { get; private set; } - public InfoBarManager InfoBars { get; private set; } - public Weather Weather { get; private set; } - public bool DisconnectionRequested { get; set; } - public bool UseLights => - ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.UseCustomLightLevel - ? World.Light.Personal < World.Light.Overall - : World.Light.RealPersonal < World.Light.RealOverall; - public bool UseAltLights => - ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.UseAlternativeLights; - - private bool _followingMode - { - get { return ProfileManager.CurrentProfile.FollowingMode; } - set { ProfileManager.CurrentProfile.FollowingMode = value; } - } - private uint _followingTarget - { - get { return ProfileManager.CurrentProfile.FollowingTarget; } - set { ProfileManager.CurrentProfile.FollowingTarget = value; } - } - - private uint _lastResync = Time.Ticks; - - public void DoubleClickDelayed(uint serial) - { - _useItemQueue.Add(serial); - } - - public override void Load() - { - base.Load(); - - UISettings.Preload(); - - Client.Game.Window.AllowUserResizing = true; - - Camera.Zoom = ProfileManager.CurrentProfile.DefaultScale; - Camera.Bounds.X = Math.Max(0, ProfileManager.CurrentProfile.GameWindowPosition.X); - Camera.Bounds.Y = Math.Max(0, ProfileManager.CurrentProfile.GameWindowPosition.Y); - Camera.Bounds.Width = Math.Max(0, ProfileManager.CurrentProfile.GameWindowSize.X); - Camera.Bounds.Height = Math.Max(0, ProfileManager.CurrentProfile.GameWindowSize.Y); - - Client.Game.GameCursor.ItemHold.Clear(); - Hotkeys = new HotkeysManager(); - Macros = new MacroManager(); - Macros.Load(); - - NameOverHeadManager.Load(); - - _animatedStaticsManager = new AnimatedStaticsManager(); - _animatedStaticsManager.Initialize(); - InfoBars = new InfoBarManager(); - InfoBars.Load(); - _healthLinesManager = new HealthLinesManager(); - Weather = new Weather(); - - WorldViewportGump viewport = new WorldViewportGump(this); - UIManager.Add(viewport, false); - - if (!ProfileManager.CurrentProfile.TopbarGumpIsDisabled) - { - TopBarGump.Create(); - } - - CommandManager.Initialize(); - NetClient.Socket.Disconnected += SocketOnDisconnected; - EventSink.MessageReceived += ChatOnMessageReceived; - UIManager.ContainerScale = ProfileManager.CurrentProfile.ContainersScale / 100f; - - SDL.SDL_SetWindowMinimumSize(Client.Game.Window.Handle, 640, 480); - - if (ProfileManager.CurrentProfile.WindowBorderless) - { - Client.Game.SetWindowBorderless(true); - } - else if (Settings.GlobalSettings.IsWindowMaximized) - { - Client.Game.MaximizeWindow(); - } - else if (Settings.GlobalSettings.WindowSize.HasValue) - { - int w = Settings.GlobalSettings.WindowSize.Value.X; - int h = Settings.GlobalSettings.WindowSize.Value.Y; - - w = Math.Max(640, w); - h = Math.Max(480, h); - - Client.Game.SetWindowSize(w, h); - } - - CircleOfTransparency.Create(ProfileManager.CurrentProfile.CircleOfTransparencyRadius); - Plugin.OnConnected(); - EventSink.InvokeOnConnected(null); - GameController.UpdateBackgroundHueShader(); - SpellVisualRangeManager.Instance.OnSceneLoad(); - AutoLootManager.Instance.OnSceneLoad(); - if (!UpdateManager.SkipUpdateCheck && UpdateManager.HasUpdate) - { - UpdateManager.SendDelayedUpdateMessage(); - } - else if (!UpdateManager.SkipUpdateCheck) - { - UpdateManager.UpdateStatusChanged += (s, e) => - { - if (UpdateManager.HasUpdate) - { - UpdateManager.SendDelayedUpdateMessage(); - } - }; - } - - foreach(var xml in ProfileManager.CurrentProfile.AutoOpenXmlGumps) - { - XmlGumpHandler.TryAutoOpenByName(xml); - } - } - - private void ChatOnMessageReceived(object sender, MessageEventArgs e) - { - if (e.Type == MessageType.Command) - { - return; - } - - string name; - string text; - - ushort hue = e.Hue; - - switch (e.Type) - { - case MessageType.ChatSystem: - name = e.Name; - text = e.Text; - break; - case MessageType.Regular: - case MessageType.Limit3Spell: - - if (e.Parent == null || !SerialHelper.IsValid(e.Parent.Serial)) - { - name = ResGeneral.System; - } - else - { - name = e.Name; - } - - text = e.Text; - - break; - - case MessageType.System: - name = - string.IsNullOrEmpty(e.Name) - || string.Equals( - e.Name, - "system", - StringComparison.InvariantCultureIgnoreCase - ) - ? ResGeneral.System - : e.Name; - - text = e.Text; - - break; - - case MessageType.Emote: - name = e.Name; - text = $"{e.Text}"; - - if (e.Hue == 0) - { - hue = ProfileManager.CurrentProfile.EmoteHue; - } - - break; - - case MessageType.Label: - - if (e.Parent == null || !SerialHelper.IsValid(e.Parent.Serial)) - { - name = string.Empty; - } - else if (string.IsNullOrEmpty(e.Name)) - { - name = ResGeneral.YouSee; - } - else - { - name = e.Name; - } - - text = e.Text; - - break; - - case MessageType.Spell: - name = e.Name; - text = e.Text; - - break; - - case MessageType.Party: - text = e.Text; - name = string.Format(ResGeneral.Party0, e.Name); - hue = ProfileManager.CurrentProfile.PartyMessageHue; - - break; - - case MessageType.Alliance: - text = e.Text; - name = string.Format(ResGeneral.Alliance0, e.Name); - hue = ProfileManager.CurrentProfile.AllyMessageHue; - - break; - - case MessageType.Guild: - text = e.Text; - name = string.Format(ResGeneral.Guild0, e.Name); - hue = ProfileManager.CurrentProfile.GuildMessageHue; - - break; - - default: - text = e.Text; - name = e.Name; - hue = e.Hue; - - Log.Warn($"Unhandled text type {e.Type} - text: '{e.Text}'"); - - break; - } - - if (!string.IsNullOrEmpty(text)) - { - World.Journal.Add - ( - text, - hue, - name, - e.TextType, - e.IsUnicode, - e.Type - ); - } - } - - public override void Unload() - { - if (IsDestroyed) - { - return; - } - - ProfileManager.CurrentProfile.GameWindowPosition = new Point( - Camera.Bounds.X, - Camera.Bounds.Y - ); - ProfileManager.CurrentProfile.GameWindowSize = new Point( - Camera.Bounds.Width, - Camera.Bounds.Height - ); - ProfileManager.CurrentProfile.DefaultScale = Camera.Zoom; - - Client.Game.Audio?.StopMusic(); - Client.Game.Audio?.StopSounds(); - - Client.Game.SetWindowTitle(string.Empty); - Client.Game.GameCursor.ItemHold.Clear(); - - try - { - Plugin.OnDisconnected(); - } - catch { } - - EventSink.InvokeOnDisconnected(null); - - TargetManager.Reset(); - - // special case for wmap. this allow us to save settings - UIManager.GetGump()?.SaveSettings(); - - ProfileManager.CurrentProfile?.Save(ProfileManager.ProfilePath); - TileMarkerManager.Instance.Save(); - SpellVisualRangeManager.Instance.Save(); - SpellVisualRangeManager.Instance.OnSceneUnload(); - AutoLootManager.Instance.Save(); - - NameOverHeadManager.Save(); - - Macros.Save(); - InfoBars.Save(); - ProfileManager.UnLoadProfile(); - - StaticFilters.CleanCaveTextures(); - StaticFilters.CleanTreeTextures(); - - NetClient.Socket.Disconnected -= SocketOnDisconnected; - NetClient.Socket.Disconnect(); - _lightRenderTarget?.Dispose(); - _world_render_target?.Dispose(); - - CommandManager.UnRegisterAll(); - Weather.Reset(); - UIManager.Clear(); - World.Clear(); - ChatManager.Clear(); - DelayedObjectClickManager.Clear(); - - _useItemQueue?.Clear(); - _useItemQueue = null; - Hotkeys = null; - Macros = null; - EventSink.MessageReceived -= ChatOnMessageReceived; - - Settings.GlobalSettings.WindowSize = new Point( - Client.Game.Window.ClientBounds.Width, - Client.Game.Window.ClientBounds.Height - ); - - Settings.GlobalSettings.IsWindowMaximized = Client.Game.IsWindowMaximized(); - Client.Game.SetWindowBorderless(false); - - base.Unload(); - } - - private void SocketOnDisconnected(object sender, SocketError e) - { - if (Settings.GlobalSettings.Reconnect) - { - _forceStopScene = true; - } - else - { - UIManager.Add( - new MessageBoxGump( - 200, - 200, - string.Format( - ResGeneral.ConnectionLost0, - StringHelper.AddSpaceBeforeCapital(e.ToString()) - ), - s => - { - if (s) - { - Client.Game.SetScene(new LoginScene()); - } - } - ) - ); - } - } - - public void RequestQuitGame() - { - UIManager.Add( - new QuestionGump( - ResGeneral.QuitPrompt, - s => - { - if (s) - { - if ( - ( - World.ClientFeatures.Flags - & CharacterListFlags.CLF_OWERWRITE_CONFIGURATION_BUTTON - ) != 0 - ) - { - DisconnectionRequested = true; - NetClient.Socket.Send_LogoutNotification(); - } - else - { - NetClient.Socket.Disconnect(); - Client.Game.SetScene(new LoginScene()); - } - } - } - ) - ); - } - - public void AddLight(GameObject obj, GameObject lightObject, int x, int y) - { - if ( - _lightCount >= LightsLoader.MAX_LIGHTS_DATA_INDEX_COUNT - || !UseLights && !UseAltLights - || obj == null - ) - { - return; - } - - bool canBeAdded = true; - - int testX = obj.X + 1; - int testY = obj.Y + 1; - - GameObject tile = World.Map.GetTile(testX, testY); - - if (tile != null) - { - sbyte z5 = (sbyte)(obj.Z + 5); - - for (GameObject o = tile; o != null; o = o.TNext) - { - if ( - (!(o is Static s) || s.ItemData.IsTransparent) - && (!(o is Multi m) || m.ItemData.IsTransparent) - || !o.AllowedToDraw - ) - { - continue; - } - - if (o.Z < _maxZ && o.Z >= z5) - { - canBeAdded = false; - - break; - } - } - } - - if (canBeAdded) - { - ref LightData light = ref _lights[_lightCount]; - - ushort graphic = lightObject.Graphic; - - if ( - graphic >= 0x3E02 && graphic <= 0x3E0B - || graphic >= 0x3914 && graphic <= 0x3929 - || graphic == 0x0B1D - ) - { - light.ID = 2; - } - else - { - if (obj == lightObject && obj is Item item) - { - light.ID = item.LightID; - } - else if (lightObject is Item it) - { - light.ID = (byte)it.ItemData.LightIndex; - - if (obj is Mobile mob) - { - switch (mob.Direction) - { - case Direction.Right: - y += 33; - x += 22; - - break; - - case Direction.Left: - y += 33; - x -= 22; - - break; - - case Direction.East: - x += 22; - y += 55; - - break; - - case Direction.Down: - y += 55; - - break; - - case Direction.South: - x -= 22; - y += 55; - - break; - } - } - } - else if (obj is Mobile _) - { - light.ID = 1; - } - else - { - ref StaticTiles data = ref TileDataLoader.Instance.StaticData[obj.Graphic]; - light.ID = data.Layer; - } - } - - light.Color = 0; - light.IsHue = false; - - if (ProfileManager.CurrentProfile.UseColoredLights) - { - if (light.ID > 200) - { - light.Color = (ushort)(light.ID - 200); - light.ID = 1; - } - - if (LightColors.GetHue(graphic, out ushort color, out bool ishue)) - { - light.Color = color; - light.IsHue = ishue; - } - } - - if (light.ID >= LightsLoader.MAX_LIGHTS_DATA_INDEX_COUNT) - { - return; - } - - if (light.Color != 0) - { - light.Color++; - } - - light.DrawX = x; - light.DrawY = y; - _lightCount++; - } - } - - private void FillGameObjectList() - { - _renderListStaticsHead = null; - _renderList = null; - _renderListStaticsCount = 0; - - _renderListTransparentObjectsHead = null; - _renderListTransparentObjects = null; - _renderListTransparentObjectsCount = 0; - - _renderListAnimationsHead = null; - _renderListAnimations = null; - _renderListAnimationCount = 0; - - _renderListEffectsHead = null; - _renderListEffects = null; - _renderListEffectCount = 0; - - _foliageCount = 0; - - if (!World.InGame) - { - return; - } - - _alphaChanged = _alphaTimer < Time.Ticks; - - if (_alphaChanged) - { - _alphaTimer = Time.Ticks + Constants.ALPHA_TIME; - } - - FoliageIndex++; - - if (FoliageIndex >= 100) - { - FoliageIndex = 1; - } - - GetViewPort(); - - var useObjectHandles = NameOverHeadManager.IsShowing; - if (useObjectHandles != _useObjectHandles) - { - _useObjectHandles = useObjectHandles; - if (_useObjectHandles) - { - NameOverHeadManager.Open(); - - } - else - { - NameOverHeadManager.Close(); - } - } - - _rectanglePlayer.X = (int)( - World.Player.RealScreenPosition.X - - World.Player.FrameInfo.X - + 22 - + World.Player.Offset.X - ); - _rectanglePlayer.Y = (int)( - World.Player.RealScreenPosition.Y - - World.Player.FrameInfo.Y - + 22 - + (World.Player.Offset.Y - World.Player.Offset.Z) - ); - _rectanglePlayer.Width = World.Player.FrameInfo.Width; - _rectanglePlayer.Height = World.Player.FrameInfo.Height; - - int minX = _minTile.X; - int minY = _minTile.Y; - int maxX = _maxTile.X; - int maxY = _maxTile.Y; - Map.Map map = World.Map; - bool use_handles = _useObjectHandles; - int maxCotZ = World.Player.Z + 5; - Vector2 playerPos = World.Player.GetScreenPosition(); - - for (int i = 0; i < 2; ++i) - { - int minValue = minY; - int maxValue = maxY; - - if (i != 0) - { - minValue = minX; - maxValue = maxX; - } - - for (int lead = minValue; lead < maxValue; ++lead) - { - int x = minX; - int y = lead; - - if (i != 0) - { - x = lead; - y = maxY; - } - - while (x >= minX && x <= maxX && y >= minY && y <= maxY) - { - AddTileToRenderList( - map.GetTile(x, y), - x, - y, - use_handles, - 150, - maxCotZ, - ref playerPos - ); - - ++x; - --y; - } - } - } - - if (_alphaChanged) - { - for (int i = 0; i < _foliageCount; i++) - { - GameObject f = _foliages[i]; - - if (f.FoliageIndex == FoliageIndex) - { - CalculateAlpha(ref f.AlphaHue, Constants.FOLIAGE_ALPHA); - } - else if (f.Z < _maxZ) - { - CalculateAlpha(ref f.AlphaHue, 0xFF); - } - } - } - - UpdateTextServerEntities(World.Mobiles.Values, true); - UpdateTextServerEntities(World.Items.Values, false); - - UpdateDrawPosition = false; - } - - private void UpdateTextServerEntities(IEnumerable entities, bool force) - where T : Entity - { - foreach (T e in entities) - { - if ( - e.TextContainer != null - && !e.TextContainer.IsEmpty - && (force || e.Graphic == 0x2006) - ) - { - e.UpdateRealScreenPosition(_offset.X, _offset.Y); - } - } - } - - public override void Update() - { - Profile currentProfile = ProfileManager.CurrentProfile; - - SelectedObject.TranslatedMousePositionByViewport = Camera.MouseToWorldPosition(); - - base.Update(); - - if (_time_cleanup < Time.Ticks) - { - World.Map?.ClearUnusedBlocks(); - _time_cleanup = Time.Ticks + 500; - } - - PacketHandlers.SendMegaClilocRequests(); - - if (_forceStopScene) - { - LoginScene loginScene = new LoginScene(); - Client.Game.SetScene(loginScene); - loginScene.Reconnect = true; - - return; - } - - if (!World.InGame) - { - return; - } - - if (Time.Ticks > _timePing) - { - NetClient.Socket.Statistics.SendPing(); - _timePing = (long)Time.Ticks + 1000; - } - - if (currentProfile.ForceResyncOnHang && Time.Ticks - NetClient.Socket.Statistics.LastPingReceived > 5000 && Time.Ticks - _lastResync > 5000) - { - //Last ping > ~5 seconds - NetClient.Socket.Send_Resync(); - _lastResync = Time.Ticks; - GameActions.Print("Possible connection hang, resync attempted", 32, MessageType.System); - } - - World.Update(); - _animatedStaticsManager.Process(); - BoatMovingManager.Update(); - Pathfinder.ProcessAutoWalk(); - DelayedObjectClickManager.Update(); - - if (!MoveCharacterByMouseInput() && !currentProfile.DisableArrowBtn && !MoveCharByController()) - { - Direction dir = DirectionHelper.DirectionFromKeyboardArrows( - _flags[0], - _flags[2], - _flags[1], - _flags[3] - ); - - if (World.InGame && !Pathfinder.AutoWalking && dir != Direction.NONE) - { - World.Player.Walk(dir, currentProfile.AlwaysRun); - } - } - - if (currentProfile.FollowingMode && SerialHelper.IsMobile(currentProfile.FollowingTarget) && !Pathfinder.AutoWalking) - { - Mobile follow = World.Mobiles.Get(currentProfile.FollowingTarget); - - if (follow != null) - { - int distance = follow.Distance; - - if (distance > World.ClientViewRange) - { - StopFollowing(); - } - else if (distance > currentProfile.AutoFollowDistance) - { - if(!Pathfinder.WalkTo(follow.X, follow.Y, follow.Z, currentProfile.AutoFollowDistance)) - { - StopFollowing(); //Can't get there - } - } - } - else - { - StopFollowing(); - } - } - - Macros.Update(); - - if ( - (currentProfile.CorpseOpenOptions == 1 || currentProfile.CorpseOpenOptions == 3) - && TargetManager.IsTargeting - || (currentProfile.CorpseOpenOptions == 2 || currentProfile.CorpseOpenOptions == 3) - && World.Player.IsHidden - ) - { - _useItemQueue.ClearCorpses(); - } - - _useItemQueue.Update(); - - if (!UIManager.IsMouseOverWorld) - { - SelectedObject.Object = null; - } - - if ( - TargetManager.IsTargeting - && TargetManager.TargetingState == CursorTarget.MultiPlacement - && World.CustomHouseManager == null - && TargetManager.MultiTargetInfo != null - ) - { - if (_multi == null) - { - _multi = Item.Create(0); - _multi.Graphic = TargetManager.MultiTargetInfo.Model; - _multi.Hue = TargetManager.MultiTargetInfo.Hue; - _multi.IsMulti = true; - } - - if (SelectedObject.Object is GameObject gobj) - { - ushort x, - y; - sbyte z; - - int cellX = gobj.X % 8; - int cellY = gobj.Y % 8; - - GameObject o = World.Map.GetChunk(gobj.X, gobj.Y)?.Tiles[cellX, cellY]; - - if (o != null) - { - x = o.X; - y = o.Y; - z = o.Z; - } - else - { - x = gobj.X; - y = gobj.Y; - z = gobj.Z; - } - - World.Map.GetMapZ(x, y, out sbyte groundZ, out sbyte _); - - if (gobj is Static st && st.ItemData.IsWet) - { - groundZ = gobj.Z; - } - - x = (ushort)(x - TargetManager.MultiTargetInfo.XOff); - y = (ushort)(y - TargetManager.MultiTargetInfo.YOff); - z = (sbyte)(groundZ - TargetManager.MultiTargetInfo.ZOff); - - _multi.SetInWorldTile(x, y, z); - _multi.CheckGraphicChange(); - - World.HouseManager.TryGetHouse(_multi.Serial, out House house); - - foreach (Multi s in house.Components) - { - s.IsHousePreview = true; - s.SetInWorldTile( - (ushort)(_multi.X + s.MultiOffsetX), - (ushort)(_multi.Y + s.MultiOffsetY), - (sbyte)(_multi.Z + s.MultiOffsetZ) - ); - } - } - } - else if (_multi != null) - { - World.HouseManager.RemoveMultiTargetHouse(); - _multi.Destroy(); - _multi = null; - } - - if (_isMouseLeftDown && !Client.Game.GameCursor.ItemHold.Enabled) - { - if ( - World.CustomHouseManager != null - && World.CustomHouseManager.SelectedGraphic != 0 - && !World.CustomHouseManager.SeekTile - && !World.CustomHouseManager.Erasing - && Time.Ticks > _timeToPlaceMultiInHouseCustomization - ) - { - if ( - SelectedObject.Object is GameObject obj - && ( - obj.X != _lastSelectedMultiPositionInHouseCustomization.X - || obj.Y != _lastSelectedMultiPositionInHouseCustomization.Y - ) - ) - { - World.CustomHouseManager.OnTargetWorld(obj); - _timeToPlaceMultiInHouseCustomization = Time.Ticks + 50; - _lastSelectedMultiPositionInHouseCustomization.X = obj.X; - _lastSelectedMultiPositionInHouseCustomization.Y = obj.Y; - } - } - else if (Time.Ticks - _holdMouse2secOverItemTime >= 1000) - { - if (SelectedObject.Object is Item it && GameActions.PickUp(it.Serial, 0, 0)) - { - _isMouseLeftDown = false; - _holdMouse2secOverItemTime = 0; - } - } - } - } - - public override bool Draw(UltimaBatcher2D batcher) - { - if (!World.InGame) - { - return false; - } - - if (CheckDeathScreen(batcher)) - { - return true; - } - - Viewport r_viewport = batcher.GraphicsDevice.Viewport; - Viewport camera_viewport = Camera.GetViewport(); - Matrix matrix = _use_render_target ? Matrix.Identity : Camera.ViewTransformMatrix; - - bool can_draw_lights = false; - - if (!_use_render_target) - { - can_draw_lights = PrepareLightsRendering(batcher, ref matrix); - batcher.GraphicsDevice.Viewport = camera_viewport; - } - - DrawWorld(batcher, ref matrix, _use_render_target); - - if (_use_render_target) - { - can_draw_lights = PrepareLightsRendering(batcher, ref matrix); - batcher.GraphicsDevice.Viewport = camera_viewport; - } - - // draw world rt - Vector3 hue = Vector3.Zero; - hue.Z = 1f; - - if (_use_render_target) - { - //switch (ProfileManager.CurrentProfile.FilterType) - //{ - // default: - // case 0: - // batcher.SetSampler(SamplerState.PointClamp); - // break; - // case 1: - // batcher.SetSampler(SamplerState.AnisotropicClamp); - // break; - // case 2: - // batcher.SetSampler(SamplerState.LinearClamp); - // break; - //} - - if (_xbr == null) - { - _xbr = new XBREffect(batcher.GraphicsDevice); - } - - _xbr.TextureSize.SetValue(new Vector2(Camera.Bounds.Width, Camera.Bounds.Height)); - - //Point p = Point.Zero; - - //p = Camera.ScreenToWorld(p); - //int minPixelsX = p.X; - //int minPixelsY = p.Y; - - //p.X = Camera.Bounds.Width; - //p.Y = Camera.Bounds.Height; - //p = Camera.ScreenToWorld(p); - //int maxPixelsX = p.X; - //int maxPixelsY = p.Y; - - batcher.Begin(null, Camera.ViewTransformMatrix); - - batcher.Draw( - _world_render_target, - new Rectangle(0, 0, Camera.Bounds.Width, Camera.Bounds.Height), - hue - ); - - batcher.End(); - - //batcher.SetSampler(null); - } - - // draw lights - if (can_draw_lights) - { - batcher.Begin(); - - if (UseAltLights) - { - hue.Z = .5f; - batcher.SetBlendState(_altLightsBlend.Value); - } - else - { - batcher.SetBlendState(_darknessBlend.Value); - } - - batcher.Draw( - _lightRenderTarget, - new Rectangle(0, 0, Camera.Bounds.Width, Camera.Bounds.Height), - hue - ); - - batcher.SetBlendState(null); - batcher.End(); - - hue.Z = 1f; - } - - batcher.Begin(); - DrawOverheads(batcher); - DrawSelection(batcher); - batcher.End(); - - batcher.GraphicsDevice.Viewport = r_viewport; - - return base.Draw(batcher); - } - - private void DrawWorld(UltimaBatcher2D batcher, ref Matrix matrix, bool use_render_target) - { - SelectedObject.Object = null; - FillGameObjectList(); - - if (use_render_target) - { - batcher.GraphicsDevice.SetRenderTarget(_world_render_target); - batcher.GraphicsDevice.Clear(ClearOptions.Target, Color.Black, 0f, 0); - } - else - { - batcher.SetSampler(SamplerState.PointClamp); - } - - batcher.Begin(null, matrix); - batcher.SetBrightlight(ProfileManager.CurrentProfile.TerrainShadowsLevel * 0.1f); - - // https://shawnhargreaves.com/blog/depth-sorting-alpha-blended-objects.html - batcher.SetStencil(DepthStencilState.Default); - - RenderedObjectsCount = 0; - RenderedObjectsCount += DrawRenderList( - batcher, - _renderListStaticsHead, - _renderListStaticsCount - ); - RenderedObjectsCount += DrawRenderList( - batcher, - _renderListAnimationsHead, - _renderListAnimationCount - ); - RenderedObjectsCount += DrawRenderList( - batcher, - _renderListEffectsHead, - _renderListEffectCount - ); - - if (_renderListTransparentObjectsCount > 0) - { - batcher.SetStencil(DepthStencilState.DepthRead); - RenderedObjectsCount += DrawRenderList( - batcher, - _renderListTransparentObjectsHead, - _renderListTransparentObjectsCount - ); - } - - batcher.SetStencil(null); - - //var worldPoint = Camera.MouseToWorldPosition() + _offset; - //worldPoint.X += 22; - //worldPoint.Y += 22; - - //var isoX = (int)(0.5f * (worldPoint.X / 22f + worldPoint.Y / 22f)); - //var isoY = (int)(0.5f * (-worldPoint.X / 22f + worldPoint.Y / 22f)); - - //GameObject selectedObject = World.Map.GetTile(isoX, isoY, false); - - //if (selectedObject != null) - //{ - // selectedObject.Hue = 0x44; - //} - - - if ( - _multi != null - && TargetManager.IsTargeting - && TargetManager.TargetingState == CursorTarget.MultiPlacement - ) - { - _multi.Draw( - batcher, - _multi.RealScreenPosition.X, - _multi.RealScreenPosition.Y, - _multi.CalculateDepthZ() - ); - } - - batcher.SetSampler(null); - batcher.SetStencil(null); - - // draw weather - Weather.Draw(batcher, 0, 0); // TODO: fix the depth - - batcher.End(); - - int flushes = batcher.FlushesDone; - int switches = batcher.TextureSwitches; - - if (use_render_target) - { - batcher.GraphicsDevice.SetRenderTarget(null); - } - - //batcher.Begin(); - //hueVec.X = 0; - //hueVec.Y = 1; - //hueVec.Z = 1; - //string s = $"Flushes: {flushes}\nSwitches: {switches}\nArt texture count: {TextureAtlas.Shared.TexturesCount}\nMaxZ: {_maxZ}\nMaxGround: {_maxGroundZ}"; - //batcher.DrawString(Fonts.Bold, s, 200, 200, ref hueVec); - //hueVec = Vector3.Zero; - //batcher.DrawString(Fonts.Bold, s, 200 + 1, 200 - 1, ref hueVec); - //batcher.End(); - } - - private int DrawRenderList(UltimaBatcher2D batcher, GameObject obj, int count) - { - int done = 0; - - for (int i = 0; i < count; obj = obj.RenderListNext, ++i) - { - if (obj.Z <= _maxGroundZ) - { - float depth = obj.CalculateDepthZ(); - - if ( - obj.Draw(batcher, obj.RealScreenPosition.X, obj.RealScreenPosition.Y, depth) - ) - { - ++done; - } - } - } - - return done; - } - - private bool PrepareLightsRendering(UltimaBatcher2D batcher, ref Matrix matrix) - { - if ( - !UseLights && !UseAltLights - || World.Player.IsDead && ProfileManager.CurrentProfile.EnableBlackWhiteEffect - || _lightRenderTarget == null - ) - { - return false; - } - - batcher.GraphicsDevice.SetRenderTarget(_lightRenderTarget); - batcher.GraphicsDevice.Clear(ClearOptions.Target, Color.Black, 0f, 0); - - if (!UseAltLights) - { - float lightColor = World.Light.IsometricLevel; - - if (ProfileManager.CurrentProfile.UseDarkNights) - { - lightColor -= 0.04f; - } - - batcher.GraphicsDevice.Clear( - ClearOptions.Target, - new Vector4(lightColor, lightColor, lightColor, 1), - 0f, - 0 - ); - } - - batcher.Begin(null, matrix); - batcher.SetBlendState(BlendState.Additive); - - Vector3 hue = Vector3.Zero; - - hue.Z = 1f; - - for (int i = 0; i < _lightCount; i++) - { - ref LightData l = ref _lights[i]; - ref readonly var lightInfo = ref Client.Game.Lights.GetLight(l.ID); - - if (lightInfo.Texture == null) - { - continue; - } - - hue.X = l.Color; - hue.Y = - hue.X > 1.0f - ? l.IsHue - ? ShaderHueTranslator.SHADER_HUED - : ShaderHueTranslator.SHADER_LIGHTS - : ShaderHueTranslator.SHADER_NONE; - - batcher.Draw( - lightInfo.Texture, - new Vector2( - l.DrawX - lightInfo.UV.Width * 0.5f, - l.DrawY - lightInfo.UV.Height * 0.5f - ), - lightInfo.UV, - hue - ); - } - - _lightCount = 0; - - batcher.SetBlendState(null); - batcher.End(); - - batcher.GraphicsDevice.SetRenderTarget(null); - - return true; - } - - public void DrawOverheads(UltimaBatcher2D batcher) - { - _healthLinesManager.Draw(batcher); - - if (!UIManager.IsMouseOverWorld) - { - SelectedObject.Object = null; - } - - World.WorldTextManager.ProcessWorldText(true); - World.WorldTextManager.Draw(batcher, Camera.Bounds.X, Camera.Bounds.Y); - } - - public void DrawSelection(UltimaBatcher2D batcher) - { - if (_isSelectionActive) - { - Vector3 selectionHue = new Vector3(); - selectionHue.Z = 0.7f; - - int minX = Math.Min(_selectionStart.X, Mouse.Position.X); - int maxX = Math.Max(_selectionStart.X, Mouse.Position.X); - int minY = Math.Min(_selectionStart.Y, Mouse.Position.Y); - int maxY = Math.Max(_selectionStart.Y, Mouse.Position.Y); - - Rectangle selectionRect = new Rectangle( - minX - Camera.Bounds.X, - minY - Camera.Bounds.Y, - maxX - minX, - maxY - minY - ); - - batcher.Draw( - SolidColorTextureCache.GetTexture(Color.Black), - selectionRect, - selectionHue - ); - - selectionHue.Z = 0.3f; - - batcher.DrawRectangle( - SolidColorTextureCache.GetTexture(Color.DeepSkyBlue), - selectionRect.X, - selectionRect.Y, - selectionRect.Width, - selectionRect.Height, - selectionHue - ); - } - } - - private static readonly RenderedText _youAreDeadText = RenderedText.Create( - ResGeneral.YouAreDead, - 0xFFFF, - 3, - false, - FontStyle.BlackBorder, - TEXT_ALIGN_TYPE.TS_LEFT - ); - - private bool CheckDeathScreen(UltimaBatcher2D batcher) - { - if ( - ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.EnableDeathScreen - ) - { - if (World.InGame) - { - if (World.Player.IsDead && World.Player.DeathScreenTimer > Time.Ticks) - { - batcher.Begin(); - _youAreDeadText.Draw( - batcher, - Camera.Bounds.X + (Camera.Bounds.Width / 2 - _youAreDeadText.Width / 2), - Camera.Bounds.Bottom / 2 - ); - batcher.End(); - - return true; - } - } - } - - return false; - } - - private void StopFollowing() - { - if (ProfileManager.CurrentProfile.FollowingMode) - { - ProfileManager.CurrentProfile.FollowingMode = false; - ProfileManager.CurrentProfile.FollowingTarget = 0; - Pathfinder.StopAutoWalk(); - - MessageManager.HandleMessage( - World.Player, - ResGeneral.StoppedFollowing, - string.Empty, - 0, - MessageType.Regular, - 3, - TextType.CLIENT - ); - } - } - - private struct LightData - { - public byte ID; - public ushort Color; - public bool IsHue; - public int DrawX, - DrawY; - } - } -} diff --git a/src/ClassicUO.Client/Game/Scenes/GameSceneDrawingSorting.cs b/src/ClassicUO.Client/Game/Scenes/GameSceneDrawingSorting.cs deleted file mode 100644 index 29fd6b285..000000000 --- a/src/ClassicUO.Client/Game/Scenes/GameSceneDrawingSorting.cs +++ /dev/null @@ -1,1298 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Map; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.Scenes -{ - internal partial class GameScene - { - private static GameObject[] _foliages = new GameObject[100]; - private static readonly TreeUnion[] _treeInfos = - { - new TreeUnion(0x0D45, 0x0D4C), - new TreeUnion(0x0D5C, 0x0D62), - new TreeUnion(0x0D73, 0x0D79), - new TreeUnion(0x0D87, 0x0D8B), - new TreeUnion(0x12BE, 0x12C7), - new TreeUnion(0x0D4D, 0x0D53), - new TreeUnion(0x0D63, 0x0D69), - new TreeUnion(0x0D7A, 0x0D7F), - new TreeUnion(0x0D8C, 0x0D90) - }; - - private sbyte _maxGroundZ; - private int _maxZ; - private Vector2 _minPixel, - _maxPixel, - _lastCamOffset; - private bool _noDrawRoofs; - private Point _offset, - _maxTile, - _minTile, - _last_scaled_offset; - private int _oldPlayerX, - _oldPlayerY, - _oldPlayerZ; - private int _foliageCount; - - // statics - private GameObject _renderListStaticsHead, - _renderList; - private int _renderListStaticsCount; - - // lands - private GameObject _renderListTransparentObjectsHead, - _renderListTransparentObjects; - private int _renderListTransparentObjectsCount; - - // animations - private GameObject _renderListAnimationsHead, - _renderListAnimations; - private int _renderListAnimationCount; - - private GameObject _renderListEffectsHead, - _renderListEffects; - private int _renderListEffectCount; - - public sbyte FoliageIndex { get; private set; } - - public void UpdateMaxDrawZ(bool force = false) - { - int playerX = World.Player.X; - int playerY = World.Player.Y; - int playerZ = World.Player.Z; - - if ( - playerX == _oldPlayerX && playerY == _oldPlayerY && playerZ == _oldPlayerZ && !force - ) - { - return; - } - - _oldPlayerX = playerX; - _oldPlayerY = playerY; - _oldPlayerZ = playerZ; - - sbyte maxGroundZ = 127; - _maxGroundZ = 127; - _maxZ = 127; - _noDrawRoofs = !ProfileManager.CurrentProfile.DrawRoofs; - int bx = playerX; - int by = playerY; - Chunk chunk = World.Map.GetChunk(bx, by, false); - - if (chunk != null) - { - int x = playerX % 8; - int y = playerY % 8; - - int pz14 = playerZ + 14; - int pz16 = playerZ + 16; - - for (GameObject obj = chunk.GetHeadObject(x, y); obj != null; obj = obj.TNext) - { - sbyte tileZ = obj.Z; - - if (obj is Land l) - { - if (l.IsStretched) - { - tileZ = l.AverageZ; - } - - if (pz16 <= tileZ) - { - maxGroundZ = (sbyte)pz16; - _maxGroundZ = (sbyte)pz16; - _maxZ = _maxGroundZ; - - break; - } - - continue; - } - - if (obj is Mobile) - { - continue; - } - - //if (obj is Item it && !it.ItemData.IsRoof || !(obj is Static) && !(obj is Multi)) - // continue; - - if (tileZ > pz14 && _maxZ > tileZ) - { - ref StaticTiles itemdata = ref TileDataLoader.Instance.StaticData[ - obj.Graphic - ]; - - //if (GameObjectHelper.TryGetStaticData(obj, out var itemdata) && ((ulong) itemdata.Flags & 0x20004) == 0 && (!itemdata.IsRoof || itemdata.IsSurface)) - if ( - ((ulong)itemdata.Flags & 0x20004) == 0 - && (!itemdata.IsRoof || itemdata.IsSurface) - ) - { - _maxZ = tileZ; - _noDrawRoofs = true; - } - } - } - - int tempZ = _maxZ; - _maxGroundZ = (sbyte)_maxZ; - playerX++; - playerY++; - bx = playerX; - by = playerY; - chunk = World.Map.GetChunk(bx, by, false); - - if (chunk != null) - { - x = playerX % 8; - y = playerY % 8; - - for ( - GameObject obj2 = chunk.GetHeadObject(x, y); - obj2 != null; - obj2 = obj2.TNext - ) - { - //if (obj is Item it && !it.ItemData.IsRoof || !(obj is Static) && !(obj is Multi)) - // continue; - - if (obj2 is Mobile) - { - continue; - } - - sbyte tileZ = obj2.Z; - - if (tileZ > pz14 && _maxZ > tileZ) - { - if (!(obj2 is Land)) - { - ref StaticTiles itemdata = ref TileDataLoader.Instance.StaticData[ - obj2.Graphic - ]; - - if (((ulong)itemdata.Flags & 0x204) == 0 && itemdata.IsRoof) - { - _maxZ = tileZ; - World.Map.ClearBockAccess(); - _maxGroundZ = World.Map.CalculateNearZ( - tileZ, - playerX, - playerY, - tileZ - ); - _noDrawRoofs = true; - } - } - - //if (GameObjectHelper.TryGetStaticData(obj2, out var itemdata) && ((ulong) itemdata.Flags & 0x204) == 0 && itemdata.IsRoof) - //{ - // _maxZ = tileZ; - // World.Map.ClearBockAccess(); - // _maxGroundZ = World.Map.CalculateNearZ(tileZ, playerX, playerY, tileZ); - // _noDrawRoofs = true; - //} - } - } - - tempZ = _maxGroundZ; - } - - _maxZ = _maxGroundZ; - - if (tempZ < pz16) - { - _maxZ = pz16; - _maxGroundZ = (sbyte)pz16; - } - - _maxGroundZ = maxGroundZ; - } - } - - private void IsFoliageUnion(ushort graphic, int x, int y, int z) - { - for (int i = 0; i < _treeInfos.Length; i++) - { - ref TreeUnion info = ref _treeInfos[i]; - - if (info.Start <= graphic && graphic <= info.End) - { - while (graphic > info.Start) - { - graphic--; - x--; - y++; - } - - for (graphic = info.Start; graphic <= info.End; graphic++, x++, y--) - { - ApplyFoliageTransparency(graphic, x, y, z); - } - - break; - } - } - } - - private void ApplyFoliageTransparency(ushort graphic, int x, int y, int z) - { - GameObject tile = World.Map.GetTile(x, y); - - if (tile != null) - { - for (GameObject obj = tile; obj != null; obj = obj.TNext) - { - ushort testGraphic = obj.Graphic; - - if (testGraphic == graphic && obj.Z == z) - { - obj.FoliageIndex = FoliageIndex; - } - } - } - } - - private void UpdateObjectHandles(Entity obj, bool useObjectHandles) - { - if (useObjectHandles && NameOverHeadManager.IsAllowed(obj)) - { - if (obj.ObjectHandlesStatus != ObjectHandlesStatus.CLOSED) - { - if (obj.ObjectHandlesStatus == ObjectHandlesStatus.NONE) - { - obj.ObjectHandlesStatus = ObjectHandlesStatus.OPEN; - } - - obj.UpdateTextCoordsV(); - } - } - else if (obj.ObjectHandlesStatus != ObjectHandlesStatus.NONE) - { - obj.ObjectHandlesStatus = ObjectHandlesStatus.NONE; - obj.UpdateTextCoordsV(); - } - } - - private void CheckIfBehindATree( - GameObject obj, - int worldX, - int worldY, - ref StaticTiles itemData - ) - { - if (obj.Z < _maxZ && itemData.IsFoliage) - { - if (obj.FoliageIndex != FoliageIndex) - { - sbyte index = 0; - - bool check = World.Player.X <= worldX && World.Player.Y <= worldY; - - if (!check) - { - check = World.Player.Y <= worldY && World.Player.X <= worldX + 1; - - if (!check) - { - check = World.Player.X <= worldX && World.Player.Y <= worldY + 1; - } - } - - if (check) - { - var rect = Client.Game.Arts.GetRealArtBounds(obj.Graphic); - - rect.X = obj.RealScreenPosition.X - (rect.Width >> 1) + rect.X; - rect.Y = obj.RealScreenPosition.Y - rect.Height + rect.Y; - - check = Exstentions.InRect(ref rect, ref _rectanglePlayer); - - if (check) - { - index = FoliageIndex; - IsFoliageUnion(obj.Graphic, obj.X, obj.Y, obj.Z); - } - } - - obj.FoliageIndex = index; - } - - if (_foliageCount >= _foliages.Length) - { - int newsize = _foliages.Length + 50; - Array.Resize(ref _foliages, newsize); - } - - _foliages[_foliageCount++] = obj; - } - } - - private bool ProcessAlpha( - GameObject obj, - ref StaticTiles itemData, - bool useCoT, - ref Vector2 playerPos, - int cotZ, - out bool allowSelection - ) - { - allowSelection = true; - if (ProfileManager.CurrentProfile.UseCircleOfTransparency && ProfileManager.CurrentProfile.CircleOfTransparencyType == 2) - { - if (Vector2.Distance(new Vector2(obj.RealScreenPosition.X, obj.RealScreenPosition.Y), playerPos) < ProfileManager.CurrentProfile.CircleOfTransparencyRadius) - { - if (obj.Z >= _maxZ) - { - CalculateAlpha(ref obj.AlphaHue, 0); - } - else - { - if (itemData.IsWall || itemData.IsWindow) - { - obj.AlphaHue = 65; - allowSelection = false; - return true; - } - if (itemData.IsDoor || itemData.IsRoof) - { - obj.AlphaHue = 65; - allowSelection = true; - return true; - } - if (itemData.IsRoof && _noDrawRoofs) - { - return false; - } - if (itemData.IsFoliage || obj.Graphic == Constants.TREE_REPLACE_GRAPHIC || StaticFilters.IsTree(obj.Graphic, out var _) || (!itemData.IsMultiMovable && obj is Static stat && stat.IsVegetation) || (!itemData.IsMultiMovable && obj is Multi multi && multi.IsVegetation)) - { - obj.AlphaHue = 65; - allowSelection = true; - return true; - } - } - } - } - if (obj.Z >= _maxZ) - { - bool changed; - - if (_alphaChanged) - { - changed = CalculateAlpha(ref obj.AlphaHue, 0); - } - else - { - changed = obj.AlphaHue != 0; - } - - if (!changed) - { - return false; - } - } - else if (_noDrawRoofs && itemData.IsRoof) - { - if (_alphaChanged) - { - if (!CalculateAlpha(ref obj.AlphaHue, 0)) - { - return false; - } - } - - return obj.AlphaHue != 0; - } - else if (itemData.IsTranslucent) - { - if (_alphaChanged) - { - CalculateAlpha(ref obj.AlphaHue, 178); - } - } - else if (!itemData.IsFoliage) - { - if ( - useCoT - && CheckCircleOfTransparencyRadius(obj, cotZ, ref playerPos, ref allowSelection) - ) { } - else if (_alphaChanged && obj.AlphaHue != 0xFF) - { - CalculateAlpha(ref obj.AlphaHue, 0xFF); - } - } - - return true; - } - - private bool CheckCircleOfTransparencyRadius( - GameObject obj, - int maxZ, - ref Vector2 playerPos, - ref bool allowSelection - ) - { - if (ProfileManager.CurrentProfile.UseCircleOfTransparency && obj.TransparentTest(maxZ)) - { - int maxDist = ProfileManager.CurrentProfile.CircleOfTransparencyRadius + 0; - Vector2 pos = new Vector2(obj.RealScreenPosition.X, obj.RealScreenPosition.Y - 44); - Vector2.Distance(ref playerPos, ref pos, out float dist); - - if (dist <= maxDist) - { - float delta = (maxDist - 44) * 0.5f; - float fraction = (dist - delta) / (maxDist - delta); - - obj.AlphaHue = (byte) - Microsoft.Xna.Framework.MathHelper.Clamp( - fraction * 255f, - byte.MinValue, - byte.MaxValue - ); - - //const byte ALPHA_ERROR = 44; - - //if (obj.AlphaHue > ALPHA_ERROR && obj.AlphaHue >= byte.MaxValue - ALPHA_ERROR) - //{ - // obj.AlphaHue = 255; - - // return false; - //} - - allowSelection = obj.AlphaHue >= 127; - - return true; - } - } - - return false; - } - - private static bool CalculateAlpha(ref byte alphaHue, int maxAlpha) - { - if ( - ProfileManager.CurrentProfile != null - && !ProfileManager.CurrentProfile.UseObjectsFading - ) - { - alphaHue = (byte)maxAlpha; - - return maxAlpha != 0; - } - - bool result = false; - - int alpha = alphaHue; - - if (alpha > maxAlpha) - { - alpha -= 25; - - if (alpha < maxAlpha) - { - alpha = maxAlpha; - } - - result = true; - } - else if (alpha < maxAlpha) - { - alpha += 25; - - if (alpha > maxAlpha) - { - alpha = maxAlpha; - } - - result = true; - } - - alphaHue = (byte)alpha; - - return result; - } - - private static byte CalculateObjectHeight(ref int maxObjectZ, ref StaticTiles itemData) - { - if ( - itemData.Height != 0xFF /*&& itemData.Flags != 0*/ - ) - { - byte height = itemData.Height; - - if (itemData.Height == 0) - { - if (!itemData.IsBackground && !itemData.IsSurface) - { - height = 10; - } - } - - if ((itemData.Flags & TileFlag.Bridge) != 0) - { - height /= 2; - } - - maxObjectZ += height; - - return height; - } - - return 0xFF; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool IsFoliageVisibleAtSeason(ref StaticTiles itemData, Season season) - { - return !(itemData.IsFoliage && !itemData.IsMultiMovable && season >= Season.Winter); - } - - private bool HasSurfaceOverhead(Entity obj) - { - if ( - obj.Serial == World.Player.Serial /* || _maxZ == _maxGroundZ*/ - ) - { - return false; - } - - bool found = false; - - for (int y = -1; y <= 2; ++y) - { - for (int x = -1; x <= 2; ++x) - { - GameObject tile = World.Map.GetTile(obj.X + x, obj.Y + y); - - found = false; - - while (tile != null) - { - var next = tile.TNext; - - if (tile.Z > obj.Z && (tile is Static || tile is Multi)) - { - ref var itemData = ref TileDataLoader.Instance.StaticData[tile.Graphic]; - - if (itemData.IsNoShoot || itemData.IsWindow) - { - if (_maxZ - tile.Z + 5 >= tile.Z - obj.Z) - { - found = true; - - break; - } - } - } - - tile = next; - } - - if (!found) - { - return false; - } - } - } - - return found; - } - - private void PushToRenderList( - GameObject obj, - ref GameObject renderList, - ref GameObject first, - ref int renderListCount, - bool allowSelection - ) - { - if (obj.AlphaHue == 0) - { - return; - } - - // slow as fuck - if ( - allowSelection - && obj.Z <= _maxGroundZ - && obj.AllowedToDraw - && obj.CheckMouseSelection() - ) - { - if (SelectedObject.Object is GameObject prev) - { - if (obj.CalculateDepthZ() >= prev.CalculateDepthZ()) - { - SelectedObject.Object = obj; - } - } - else - { - SelectedObject.Object = obj; - } - } - - if (obj.AlphaHue != byte.MaxValue) - { - if (_renderListTransparentObjectsHead == null) - { - _renderListTransparentObjectsHead = _renderListTransparentObjects = obj; - } - else - { - _renderListTransparentObjects.RenderListNext = obj; - _renderListTransparentObjects = obj; - } - - obj.RenderListNext = null; - - ++_renderListTransparentObjectsCount; - } - else - { - if (first == null) - { - first = renderList = obj; - } - else - { - renderList.RenderListNext = obj; - renderList = obj; - } - - obj.RenderListNext = null; - - ++renderListCount; - } - } - - private unsafe bool AddTileToRenderList( - GameObject obj, - int worldX, - int worldY, - bool useObjectHandles, - int maxZ, - int cotZ, - ref Vector2 playerScreePos - ) - { - for (; obj != null; obj = obj.TNext) - { - if (UpdateDrawPosition || obj.IsPositionChanged) - { - obj.UpdateRealScreenPosition(_offset.X, _offset.Y); - } - - int screenX = obj.RealScreenPosition.X; - - if (screenX < _minPixel.X || screenX > _maxPixel.X) - { - break; - } - - int screenY = obj.RealScreenPosition.Y; - int maxObjectZ = obj.PriorityZ; - - if (obj is Land land) - { - if (maxObjectZ > maxZ) - { - return false; - } - - if (screenY > _maxPixel.Y) - { - continue; - } - - if (land.IsStretched) - { - screenY += (land.Z << 2); - screenY -= (land.MinZ << 2); - } - - if (screenY < _minPixel.Y) - { - continue; - } - - PushToRenderList( - obj, - ref _renderList, - ref _renderListStaticsHead, - ref _renderListStaticsCount, - true - ); - } - else if (obj is Static staticc) - { - ref var itemData = ref staticc.ItemData; - - if (itemData.IsInternal) - { - continue; - } - - if (!IsFoliageVisibleAtSeason(ref itemData, World.Season)) - { - continue; - } - - if ( - !ProcessAlpha( - obj, - ref itemData, - true, - ref playerScreePos, - cotZ, - out bool allowSelection - ) - ) - { - continue; - } - - //we avoid to hide impassable foliage or bushes, if present... - if (itemData.IsFoliage && ProfileManager.CurrentProfile.TreeToStumps) - { - continue; - } - - if ( - !itemData.IsMultiMovable - && staticc.IsVegetation - && ProfileManager.CurrentProfile.HideVegetation - ) - { - continue; - } - - byte height = 0; - - if (obj.AllowedToDraw) - { - height = CalculateObjectHeight(ref maxObjectZ, ref itemData); - } - - if (maxObjectZ > maxZ) - { - return itemData.Height != 0 && maxObjectZ - maxZ < height; - } - - if (screenY < _minPixel.Y || screenY > _maxPixel.Y) - { - continue; - } - - CheckIfBehindATree(obj, worldX, worldY, ref itemData); - - // hacky way to render shadows without z-fight - if ( - ProfileManager.CurrentProfile.ShadowsEnabled - && ProfileManager.CurrentProfile.ShadowsStatics - && ( - StaticFilters.IsTree(obj.Graphic, out _) - || itemData.IsFoliage - || StaticFilters.IsRock(obj.Graphic) - ) - ) - { - PushToRenderList( - obj, - ref _renderListTransparentObjects, - ref _renderListTransparentObjectsHead, - ref _renderListTransparentObjectsCount, - allowSelection - ); - } - else - { - PushToRenderList( - obj, - ref _renderList, - ref _renderListStaticsHead, - ref _renderListStaticsCount, - allowSelection - ); - } - } - else if (obj is Multi multi) - { - ref StaticTiles itemData = ref multi.ItemData; - - if (itemData.IsInternal) - { - continue; - } - - if ( - !ProcessAlpha( - obj, - ref itemData, - true, - ref playerScreePos, - cotZ, - out bool allowSelection - ) - ) - { - continue; - } - - //we avoid to hide impassable foliage or bushes, if present... - - if (!itemData.IsMultiMovable) - { - if (itemData.IsFoliage && ProfileManager.CurrentProfile.TreeToStumps) - { - continue; - } - - if (multi.IsVegetation && ProfileManager.CurrentProfile.HideVegetation) - { - continue; - } - } - - byte height = 0; - - if (obj.AllowedToDraw) - { - height = CalculateObjectHeight(ref maxObjectZ, ref itemData); - } - - if (maxObjectZ > maxZ) - { - return itemData.Height != 0 && maxObjectZ - maxZ < height; - } - - if (screenY < _minPixel.Y || screenY > _maxPixel.Y) - { - continue; - } - - CheckIfBehindATree(obj, worldX, worldY, ref itemData); - - // hacky way to render shadows without z-fight - if ( - ProfileManager.CurrentProfile.ShadowsEnabled - && ProfileManager.CurrentProfile.ShadowsStatics - && ( - StaticFilters.IsTree(obj.Graphic, out _) - || itemData.IsFoliage - || StaticFilters.IsRock(obj.Graphic) - ) - ) - { - PushToRenderList( - obj, - ref _renderListTransparentObjects, - ref _renderListTransparentObjectsHead, - ref _renderListTransparentObjectsCount, - allowSelection - ); - } - else - { - PushToRenderList( - obj, - ref _renderList, - ref _renderListStaticsHead, - ref _renderListStaticsCount, - allowSelection - ); - } - } - else if (obj is Mobile mobile) - { - UpdateObjectHandles(mobile, useObjectHandles); - - maxObjectZ += Constants.DEFAULT_CHARACTER_HEIGHT; - - if (maxObjectZ > maxZ) - { - return false; - } - - StaticTiles empty = default; - - if ( - !ProcessAlpha( - obj, - ref empty, - false, - ref playerScreePos, - cotZ, - out bool allowSelection - ) - ) - { - continue; - } - - if (screenY < _minPixel.Y || screenY > _maxPixel.Y) - { - continue; - } - - obj.AllowedToDraw = !HasSurfaceOverhead(mobile); - - PushToRenderList( - obj, - ref _renderListAnimations, - ref _renderListAnimationsHead, - ref _renderListAnimationCount, - allowSelection - ); - } - else if (obj is Item item) - { - ref StaticTiles itemData = ref ( - item.IsMulti - ? ref TileDataLoader.Instance.StaticData[item.MultiGraphic] - : ref item.ItemData - ); - - if (!item.IsCorpse && itemData.IsInternal) - { - continue; - } - - if ( - item.IsCorpse - || ( - !item.IsMulti - && (!item.IsLocked || item.IsLocked && itemData.IsContainer) - ) - ) - { - UpdateObjectHandles(item, useObjectHandles); - } - - if (!item.IsMulti && !IsFoliageVisibleAtSeason(ref itemData, World.Season)) - { - continue; - } - - if ( - !ProcessAlpha( - obj, - ref itemData, - false, - ref playerScreePos, - cotZ, - out bool allowSelection - ) - ) - { - continue; - } - - if ( - !itemData.IsMultiMovable - && itemData.IsFoliage - && ProfileManager.CurrentProfile.TreeToStumps - ) - { - continue; - } - - byte height = 0; - - if (obj.AllowedToDraw) - { - height = CalculateObjectHeight(ref maxObjectZ, ref itemData); - } - - if (maxObjectZ > maxZ) - { - return itemData.Height != 0 && maxObjectZ - maxZ < height; - } - - if (screenY < _minPixel.Y || screenY > _maxPixel.Y) - { - continue; - } - - if (!item.IsCorpse) - { - CheckIfBehindATree(obj, worldX, worldY, ref itemData); - } - - if (item.IsCorpse) - { - PushToRenderList( - obj, - ref _renderListAnimations, - ref _renderListAnimationsHead, - ref _renderListAnimationCount, - allowSelection - ); - } - else - { - PushToRenderList( - obj, - ref _renderList, - ref _renderListStaticsHead, - ref _renderListStaticsCount, - true - ); - } - } - else if (obj is GameEffect effect) - { - if ( - !ProcessAlpha( - obj, - ref TileDataLoader.Instance.StaticData[effect.Graphic], - false, - ref playerScreePos, - cotZ, - out _ - ) - ) - { - continue; - } - - if (screenY < _minPixel.Y || screenY > _maxPixel.Y) - { - continue; - } - - if (effect.IsMoving) // TODO: check for typeof(MovingEffect) ? - { } - - //PushToRenderList(obj, ref _renderList, ref _renderListStaticsHead, ref _renderListStaticsCount, false); - - PushToRenderList( - obj, - ref _renderListEffects, - ref _renderListEffectsHead, - ref _renderListEffectCount, - false - ); - } - } - - return false; - } - - private void GetViewPort() - { - int oldDrawOffsetX = _offset.X; - int oldDrawOffsetY = _offset.Y; - Point old_scaled_offset = _last_scaled_offset; - - float zoom = Camera.Zoom; - - int winGamePosX = 0; - int winGamePosY = 0; - int winGameWidth = Camera.Bounds.Width; - int winGameHeight = Camera.Bounds.Height; - int winGameCenterX = winGamePosX + (winGameWidth >> 1); - int winGameCenterY = winGamePosY + (winGameHeight >> 1) + (World.Player.Z << 2); - winGameCenterX -= (int)World.Player.Offset.X - ProfileManager.CurrentProfile.PlayerOffset.X; - winGameCenterY -= (int)(World.Player.Offset.Y - World.Player.Offset.Z - ProfileManager.CurrentProfile.PlayerOffset.Y); - - int tileOffX = World.Player.X - ProfileManager.CurrentProfile.PlayerOffset.X; - int tileOffY = World.Player.Y - ProfileManager.CurrentProfile.PlayerOffset.Y; - - int winDrawOffsetX = (tileOffX - tileOffY) * 22 - winGameCenterX; - int winDrawOffsetY = (tileOffX + tileOffY) * 22 - winGameCenterY; - - int winGameScaledOffsetX; - int winGameScaledOffsetY; - int winGameScaledWidth; - int winGameScaledHeight; - - if (zoom != 1f) - { - float left = winGamePosX; - float right = winGameWidth + left; - float top = winGamePosY; - float bottom = winGameHeight + top; - float newRight = right * zoom; - float newBottom = bottom * zoom; - - winGameScaledOffsetX = (int)(left * zoom - (newRight - right)); - winGameScaledOffsetY = (int)(top * zoom - (newBottom - bottom)); - winGameScaledWidth = (int)(newRight - winGameScaledOffsetX); - winGameScaledHeight = (int)(newBottom - winGameScaledOffsetY); - } - else - { - winGameScaledOffsetX = 0; - winGameScaledOffsetY = 0; - winGameScaledWidth = 0; - winGameScaledHeight = 0; - } - - int size = (int)(Math.Max(winGameWidth / 44f + 1, winGameHeight / 44f + 1) * zoom); - - if (Camera.Offset.X != 0 || Camera.Offset.Y != 0) - { - tileOffX += (int)(zoom * (Camera.Offset.X + Camera.Offset.Y) / 44); - tileOffY += (int)(zoom * (Camera.Offset.Y - Camera.Offset.X) / 44); - } - - int realMinRangeX = Math.Max(0, tileOffX - size); - int realMaxRangeX = tileOffX + size; - int realMinRangeY = Math.Max(0, tileOffY - size); - int realMaxRangeY = tileOffY + size; - - int drawOffset = (int)(44 / zoom); - - Point p = Point.Zero; - p.X -= drawOffset; - p.Y -= drawOffset; - p = Camera.ScreenToWorld(p); - int minPixelsX = p.X; - int minPixelsY = p.Y; - - p.X = Camera.Bounds.Width + drawOffset; - p.Y = Camera.Bounds.Height + drawOffset; - p = Camera.ScreenToWorld(p); - int maxPixelsX = p.X; - int maxPixelsY = p.Y; - - if ( - UpdateDrawPosition - || oldDrawOffsetX != winDrawOffsetX - || oldDrawOffsetY != winDrawOffsetY - || old_scaled_offset.X != winGameScaledOffsetX - || old_scaled_offset.Y != winGameScaledOffsetY - || _lastCamOffset != Camera.Offset - ) - { - UpdateDrawPosition = true; - _lastCamOffset = Camera.Offset; - - if ( - _use_render_target - && ( - _world_render_target == null - || _world_render_target.Width != (int)(winGameWidth * zoom) - || _world_render_target.Height != (int)(winGameHeight * zoom) - ) - ) - { - _world_render_target?.Dispose(); - - PresentationParameters pp = Client.Game.GraphicsDevice.PresentationParameters; - - _world_render_target = new RenderTarget2D( - Client.Game.GraphicsDevice, - winGameWidth * 1, - winGameHeight * 1, - false, - pp.BackBufferFormat, - pp.DepthStencilFormat, - pp.MultiSampleCount, - pp.RenderTargetUsage - ); - } - - if ( - _lightRenderTarget == null - || _lightRenderTarget.Width != winGameWidth - || _lightRenderTarget.Height != winGameHeight - ) - { - _lightRenderTarget?.Dispose(); - - PresentationParameters pp = Client.Game.GraphicsDevice.PresentationParameters; - - _lightRenderTarget = new RenderTarget2D( - Client.Game.GraphicsDevice, - winGameWidth, - winGameHeight, - false, - pp.BackBufferFormat, - pp.DepthStencilFormat, - pp.MultiSampleCount, - pp.RenderTargetUsage - ); - } - } - - _minTile.X = realMinRangeX; - _minTile.Y = realMinRangeY; - _maxTile.X = realMaxRangeX; - _maxTile.Y = realMaxRangeY; - - _minPixel.X = minPixelsX; - _minPixel.Y = minPixelsY; - _maxPixel.X = maxPixelsX; - _maxPixel.Y = maxPixelsY; - - _offset.X = winDrawOffsetX; - _offset.Y = winDrawOffsetY; - - _last_scaled_offset.X = winGameScaledOffsetX; - _last_scaled_offset.Y = winGameScaledOffsetY; - - UpdateMaxDrawZ(); - } - - private struct TreeUnion - { - public TreeUnion(ushort start, ushort end) - { - Start = start; - End = end; - } - - public readonly ushort Start; - public readonly ushort End; - } - } -} diff --git a/src/ClassicUO.Client/Game/Scenes/GameSceneInputHandler.cs b/src/ClassicUO.Client/Game/Scenes/GameSceneInputHandler.cs deleted file mode 100644 index 181ddb8b1..000000000 --- a/src/ClassicUO.Client/Game/Scenes/GameSceneInputHandler.cs +++ /dev/null @@ -1,1733 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Network; -using ClassicUO.Resources; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using SDL2; -using System; -using System.Linq; -using MathHelper = ClassicUO.Utility.MathHelper; - -namespace ClassicUO.Game.Scenes -{ - internal partial class GameScene - { - private bool _boatRun, - _boatIsMoving; - private readonly bool[] _flags = new bool[5]; - private uint _holdMouse2secOverItemTime; - private bool _isMouseLeftDown; - private bool _isSelectionActive; - private Direction _lastBoatDirection; - private bool _requestedWarMode; - private bool _rightMousePressed, - _continueRunning; - private Point _selectionStart, - _selectionEnd; - private int AnchorOffset => ProfileManager.CurrentProfile.DragSelectAsAnchor ? 0 : 2; - - private bool MoveCharacterByMouseInput() - { - if ((_rightMousePressed || _continueRunning) && World.InGame) // && !Pathfinder.AutoWalking) - { - if (Pathfinder.AutoWalking) - { - Pathfinder.StopAutoWalk(); - } - - int x = Camera.Bounds.X + (Camera.Bounds.Width >> 1) + ((ProfileManager.CurrentProfile.PlayerOffset.X - ProfileManager.CurrentProfile.PlayerOffset.Y) * 22); - int y = Camera.Bounds.Y + (Camera.Bounds.Height >> 1) + ((ProfileManager.CurrentProfile.PlayerOffset.X + ProfileManager.CurrentProfile.PlayerOffset.Y) * 22); - - Direction direction = (Direction) - GameCursor.GetMouseDirection(x, y, Mouse.Position.X, Mouse.Position.Y, 1); - - double mouseRange = MathHelper.Hypotenuse( - x - Mouse.Position.X, - y - Mouse.Position.Y - ); - - Direction facing = direction; - - if (facing == Direction.North) - { - facing = (Direction)8; - } - - bool run = mouseRange >= 190; - - if (World.Player.IsDrivingBoat && UIManager.GetGump() == null) - { - if (!_boatIsMoving || _boatRun != run || _lastBoatDirection != facing - 1) - { - _boatRun = run; - _lastBoatDirection = facing - 1; - _boatIsMoving = true; - - BoatMovingManager.MoveRequest(facing - 1, (byte)(run ? 2 : 1)); - } - } - else - { - World.Player.Walk(facing - 1, run); - } - - return true; - } - - return false; - } - - private bool MoveCharByController() - { - const float THRESHOLD = 0.3f; - - Microsoft.Xna.Framework.Input.GamePadState gamePadState = Microsoft.Xna.Framework.Input.GamePad.GetState(PlayerIndex.One); - - if (gamePadState.IsConnected && gamePadState.ThumbSticks.Left != Vector2.Zero && World.InGame) - { - var dir = gamePadState.ThumbSticks.Left; - bool run = dir.X > 0.5 || dir.Y > 0.5 || dir.X < -0.5 || dir.Y < -0.5; - - if (dir.X > THRESHOLD && dir.Y > THRESHOLD) // North - { - World.Player.Walk(Direction.North, run); - return true; - } - if (dir.X < -THRESHOLD && dir.Y < -THRESHOLD) // South - { - World.Player.Walk(Direction.South, run); - return true; - } - if (dir.X < -THRESHOLD && dir.Y > THRESHOLD) // Left - { - World.Player.Walk(Direction.West, run); - return true; - } - if (dir.X > THRESHOLD && dir.Y < -THRESHOLD) // Left - { - World.Player.Walk(Direction.East, run); - return true; - } - - if (dir.X < THRESHOLD && dir.Y > THRESHOLD) //Up - { - World.Player.Walk(Direction.Up, run); - return true; - } - if (dir.X < THRESHOLD && dir.Y < -THRESHOLD) //Down - { - World.Player.Walk(Direction.Down, run); - return true; - } - if (dir.X > THRESHOLD && dir.Y < THRESHOLD) // Right - { - World.Player.Walk(Direction.Right, run); - return true; - } - if (dir.X < -THRESHOLD && dir.Y < THRESHOLD) // Left - { - World.Player.Walk(Direction.Left, run); - return true; - } - } - return false; - } - - private bool CanDragSelectOnObject(GameObject obj) - { - return obj is null - || obj is Static - || obj is Land - || obj is Multi - || obj is Item tmpitem && tmpitem.IsLocked; - } - - private bool DragSelectModifierActive() - { - // src: https://github.com/andreakarasho/ClassicUO/issues/621 - // drag-select should be disabled when using nameplates - if ((Keyboard.Ctrl && Keyboard.Shift) && ProfileManager.CurrentProfile.DragSelect_NameplateModifier == 0) - { - return false; - } - - if (ProfileManager.CurrentProfile.DragSelectModifierKey == 0) - { - return true; - } - - if (ProfileManager.CurrentProfile.DragSelectModifierKey == 1 && Keyboard.Ctrl) - { - return true; - } - - if (ProfileManager.CurrentProfile.DragSelectModifierKey == 2 && Keyboard.Shift) - { - return true; - } - - return false; - } - - private void DoDragSelect() - { - bool ctrl = Keyboard.Ctrl; - bool shift = Keyboard.Shift; - - if (_selectionStart.X > Mouse.Position.X) - { - _selectionEnd.X = _selectionStart.X; - _selectionStart.X = Mouse.Position.X; - } - else - { - _selectionEnd.X = Mouse.Position.X; - } - - if (_selectionStart.Y > Mouse.Position.Y) - { - _selectionEnd.Y = _selectionStart.Y; - _selectionStart.Y = Mouse.Position.Y; - } - else - { - _selectionEnd.Y = Mouse.Position.Y; - } - - _rectangleObj.X = _selectionStart.X - Camera.Bounds.X; - _rectangleObj.Y = _selectionStart.Y - Camera.Bounds.Y; - _rectangleObj.Width = _selectionEnd.X - Camera.Bounds.X - _rectangleObj.X; - _rectangleObj.Height = _selectionEnd.Y - Camera.Bounds.Y - _rectangleObj.Y; - - int finalX = ProfileManager.CurrentProfile.DragSelectStartX; - int finalY = ProfileManager.CurrentProfile.DragSelectStartY; - - bool useCHB = ProfileManager.CurrentProfile.CustomBarsToggled; - - Rectangle rect; - - if (useCHB) - { - rect = new Rectangle( - 0, - 0, - HealthBarGumpCustom.HPB_BAR_WIDTH, - HealthBarGumpCustom.HPB_HEIGHT_MULTILINE - ); - } - else - { - rect = Client.Game.Gumps.GetGump(0x0804).UV; - } - - - foreach (Mobile mobile in World.Mobiles.Values) - { - if (( - (ProfileManager.CurrentProfile.DragSelect_PlayersModifier == 1 && ctrl) || - (ProfileManager.CurrentProfile.DragSelect_PlayersModifier == 2 && shift) - ) && !(mobile.IsHuman || mobile.IsGargoyle)) - continue; - if (( - (ProfileManager.CurrentProfile.DragSelect_MonstersModifier == 1 && ctrl) || - (ProfileManager.CurrentProfile.DragSelect_MonstersModifier == 2 && shift) - ) && (mobile.IsHuman || mobile.IsGargoyle)) - continue; - - bool skip = false; - if (( - (ProfileManager.CurrentProfile.DragSelect_NameplateModifier == 1 && ctrl) || - (ProfileManager.CurrentProfile.DragSelect_NameplateModifier == 2 && shift) - )) - { - bool _skip = true; - foreach (NameOverheadGump g in UIManager.Gumps.OfType()) - if (g.LocalSerial == mobile.Serial) - { - _skip = false; - continue; - } - skip = _skip; - } - - if (skip) continue; - - Point p = mobile.RealScreenPosition; - - p.X += (int)mobile.Offset.X + 22 + 5; - p.Y += (int)(mobile.Offset.Y - mobile.Offset.Z) + 12 * AnchorOffset; - p.X -= mobile.FrameInfo.X; - p.Y -= mobile.FrameInfo.Y; - - Point size = new Point(p.X + mobile.FrameInfo.Width, p.Y + mobile.FrameInfo.Height); - - p = Camera.WorldToScreen(p); - _rectanglePlayer.X = p.X; - _rectanglePlayer.Y = p.Y; - - size = Camera.WorldToScreen(size); - _rectanglePlayer.Width = size.X - p.X; - _rectanglePlayer.Height = size.Y - p.Y; - - if (_rectangleObj.Intersects(_rectanglePlayer)) - { - if (mobile != World.Player) - { - if (UIManager.GetGump(mobile) != null) - { - continue; - } - - BaseHealthBarGump hbgc; - - if (useCHB) - { - hbgc = new HealthBarGumpCustom(mobile); - } - else - { - hbgc = new HealthBarGump(mobile); - } - - if (finalY >= Camera.Bounds.Bottom - 20) - { - finalY = ProfileManager.CurrentProfile.DragSelectStartY; - finalX += rect.Width + 2; - } - - if (finalX >= Camera.Bounds.Right - 20) - { - finalX = ProfileManager.CurrentProfile.DragSelectStartX; - } - - hbgc.X = finalX; - hbgc.Y = finalY; - - foreach ( - BaseHealthBarGump bar in UIManager.Gumps - .OfType() - //.OrderBy(s => mobile.NotorietyFlag) - //.OrderBy(s => s.ScreenCoordinateX) ///testing placement SYRUPZ SYRUPZ SYRUPZ - .OrderBy(s => s.ScreenCoordinateX) - .ThenBy(s => s.ScreenCoordinateY) - ) - { - if (bar.Bounds.Intersects(hbgc.Bounds)) - { - finalY = bar.Bounds.Bottom + AnchorOffset; - - if (finalY >= Camera.Bounds.Bottom - 100) - { - finalY = ProfileManager.CurrentProfile.DragSelectStartY; - finalX = bar.Bounds.Right + AnchorOffset; - } - - if (finalX >= Camera.Bounds.Right - 100) - { - finalX = ProfileManager.CurrentProfile.DragSelectStartX; - } - - hbgc.X = finalX; - hbgc.Y = finalY; - if (ProfileManager.CurrentProfile.DragSelectAsAnchor) - hbgc.TryAttacheToExist(); - } - } - - if (!ProfileManager.CurrentProfile.DragSelectAsAnchor) - finalY += rect.Height + 2; - - UIManager.Add(hbgc); - - hbgc.SetInScreen(); - } - } - } - - _isSelectionActive = false; - } - - internal override bool OnMouseDown(MouseButtonType button) - { - switch (button) - { - case MouseButtonType.Left: - return OnLeftMouseDown(); - case MouseButtonType.Right: - return OnRightMouseDown(); - case MouseButtonType.Middle: - case MouseButtonType.XButton1: - case MouseButtonType.XButton2: - return OnExtraMouseDown(button); - } - - return false; - } - - internal override bool OnMouseUp(MouseButtonType button) - { - switch (button) - { - case MouseButtonType.Left: - return OnLeftMouseUp(); - case MouseButtonType.Right: - return OnRightMouseUp(); - case MouseButtonType.Middle: - case MouseButtonType.XButton1: - case MouseButtonType.XButton2: - return OnExtraMouseUp(button); - } - - return false; - } - - internal override bool OnMouseDoubleClick(MouseButtonType button) - { - switch (button) - { - case MouseButtonType.Left: - return OnLeftMouseDoubleClick(); - case MouseButtonType.Right: - return OnRightMouseDoubleClick(); - } - - return false; - } - - private bool OnLeftMouseDown() - { - if ( - UIManager.PopupMenu != null - && !UIManager.PopupMenu.Bounds.Contains(Mouse.Position.X, Mouse.Position.Y) - ) - { - UIManager.ShowGamePopup(null); - } - - if (!UIManager.IsMouseOverWorld) - { - return false; - } - - if (World.CustomHouseManager != null) - { - _isMouseLeftDown = true; - - if ( - TargetManager.IsTargeting - && TargetManager.TargetingState == CursorTarget.MultiPlacement - && ( - World.CustomHouseManager.SelectedGraphic != 0 - || World.CustomHouseManager.Erasing - || World.CustomHouseManager.SeekTile - ) - && SelectedObject.Object is GameObject obj - ) - { - World.CustomHouseManager.OnTargetWorld(obj); - _lastSelectedMultiPositionInHouseCustomization.X = obj.X; - _lastSelectedMultiPositionInHouseCustomization.Y = obj.Y; - } - } - else - { - SelectedObject.LastLeftDownObject = SelectedObject.Object; - - if (ProfileManager.CurrentProfile.EnableDragSelect && DragSelectModifierActive()) - { - if (CanDragSelectOnObject(SelectedObject.Object as GameObject)) - { - _selectionStart = Mouse.Position; - _isSelectionActive = true; - } - } - else - { - _isMouseLeftDown = true; - _holdMouse2secOverItemTime = Time.Ticks; - } - } - - return true; - } - - private bool OnLeftMouseUp() - { - if ( - UIManager.PopupMenu != null - && !UIManager.PopupMenu.Bounds.Contains(Mouse.Position.X, Mouse.Position.Y) - ) - { - UIManager.ShowGamePopup(null); - } - - if (_isMouseLeftDown) - { - _isMouseLeftDown = false; - _holdMouse2secOverItemTime = 0; - } - - // drag-select code comes first to allow selection finish on mouseup outside of viewport - if (_selectionStart.X == Mouse.Position.X && _selectionStart.Y == Mouse.Position.Y) - { - _isSelectionActive = false; - } - - if (_isSelectionActive) - { - DoDragSelect(); - - return true; - } - - if (!UIManager.IsMouseOverWorld) - { - return false; - } - - if (UIManager.SystemChat != null && !UIManager.SystemChat.IsFocused) - { - UIManager.KeyboardFocusControl = null; - UIManager.SystemChat.SetFocus(); - } - - if (!ProfileManager.CurrentProfile.DisableAutoMove && _rightMousePressed) - { - _continueRunning = true; - } - - BaseGameObject lastObj = SelectedObject.Object; - SelectedObject.LastLeftDownObject = null; - - if (UIManager.IsDragging) - { - return false; - } - - if ( - Client.Game.GameCursor.ItemHold.Enabled - && !Client.Game.GameCursor.ItemHold.IsFixedPosition - ) - { - uint drop_container = 0xFFFF_FFFF; - bool can_drop = false; - ushort dropX = 0; - ushort dropY = 0; - sbyte dropZ = 0; - - if (Keyboard.Ctrl) - { - GameActions.DropItem( - Client.Game.GameCursor.ItemHold.Serial, - World.Player.X + 1, - World.Player.Y, - World.Player.Z + 1, - 0 - ); - return true; - } - - GameObject gobj = SelectedObject.Object as GameObject; - - if (gobj is Entity obj) - { - can_drop = obj.Distance <= Constants.DRAG_ITEMS_DISTANCE; - - if (can_drop) - { - if (obj is Item it && it.ItemData.IsContainer || obj is Mobile) - { - dropX = 0xFFFF; - dropY = 0xFFFF; - dropZ = 0; - drop_container = obj.Serial; - } - else if ( - obj is Item it2 - && ( - it2.ItemData.IsSurface - || it2.ItemData.IsStackable - && it2.Graphic == Client.Game.GameCursor.ItemHold.Graphic - ) - ) - { - dropX = obj.X; - dropY = obj.Y; - dropZ = obj.Z; - - if (it2.ItemData.IsSurface) - { - dropZ += (sbyte)( - it2.ItemData.Height == 0xFF ? 0 : it2.ItemData.Height - ); - } - else - { - drop_container = obj.Serial; - } - } - } - else - { - Client.Game.Audio.PlaySound(0x0051); - } - } - else if (gobj is Land || gobj is Static || gobj is Multi) - { - can_drop = gobj.Distance <= Constants.DRAG_ITEMS_DISTANCE; - - if (can_drop) - { - dropX = gobj.X; - dropY = gobj.Y; - dropZ = gobj.Z; - - if (gobj is Land land) { } - else - { - ref StaticTiles itemData = ref TileDataLoader.Instance.StaticData[ - gobj.Graphic - ]; - - if (itemData.IsSurface) - { - dropZ += (sbyte)(itemData.Height == 0xFF ? 0 : itemData.Height); - } - } - } - else - { - Client.Game.Audio.PlaySound(0x0051); - } - } - - if (can_drop) - { - if (drop_container == 0xFFFF_FFFF && dropX == 0 && dropY == 0) - { - can_drop = false; - } - - if (can_drop) - { - GameActions.DropItem( - Client.Game.GameCursor.ItemHold.Serial, - dropX, - dropY, - dropZ, - drop_container - ); - } - } - } - else if (TargetManager.IsTargeting) - { - switch (TargetManager.TargetingState) - { - case CursorTarget.Internal: - case CursorTarget.Grab: - case CursorTarget.SetGrabBag: - case CursorTarget.Position: - case CursorTarget.Object: - case CursorTarget.MultiPlacement when World.CustomHouseManager == null: - { - BaseGameObject obj = lastObj; - - if (obj is TextObject ov) - { - obj = ov.Owner; - } - - switch (obj) - { - case Entity ent: - TargetManager.Target(ent.Serial); - - break; - - case Land land: - TargetManager.Target( - 0, - land.X, - land.Y, - land.Z, - land.TileData.IsWet - ); - - break; - - case GameObject o: - TargetManager.Target(o.Graphic, o.X, o.Y, o.Z); - - break; - } - } - - Mouse.LastLeftButtonClickTime = 0; - - break; - - case CursorTarget.SetTargetClientSide: - - { - BaseGameObject obj = lastObj; - - if (obj is TextObject ov) - { - obj = ov.Owner; - } - else if (obj is GameEffect eff && eff.Source != null) - { - obj = eff.Source; - } - - switch (obj) - { - case Entity ent: - TargetManager.Target(ent.Serial); - UIManager.Add(new InspectorGump(ent)); - - break; - - case Land land: - TargetManager.Target(0, land.X, land.Y, land.Z); - UIManager.Add(new InspectorGump(land)); - - break; - - case GameObject o: - TargetManager.Target(o.Graphic, o.X, o.Y, o.Z); - UIManager.Add(new InspectorGump(o)); - - break; - } - - Mouse.LastLeftButtonClickTime = 0; - } - - break; - - case CursorTarget.HueCommandTarget: - - if (SelectedObject.Object is Entity selectedEntity) - { - CommandManager.OnHueTarget(selectedEntity); - } - - break; - case CursorTarget.IgnorePlayerTarget: - if (SelectedObject.Object is Entity pmEntity) - { - IgnoreManager.AddIgnoredTarget(pmEntity); - } - TargetManager.CancelTarget(); - break; - case CursorTarget.MoveItemContainer: - { - BaseGameObject obj = lastObj; - - if (obj is TextObject ov) - { - obj = ov.Owner; - } - - switch (obj) - { - case Land land: - TargetManager.Reset(); - MultiItemMoveGump.OnContainerTarget(land.X, land.Y, land.Z); - break; - - case Entity o: - TargetManager.Reset(); - MultiItemMoveGump.OnContainerTarget(o.Serial); - break; - } - } - break; - } - } - else - { - GameObject obj = lastObj as GameObject; - - switch (obj) - { - case Static st: - string name = StringHelper.GetPluralAdjustedString( - st.Name, - st.ItemData.Count > 1 - ); - - if (string.IsNullOrEmpty(name)) - { - name = ClilocLoader.Instance.GetString( - 1020000 + st.Graphic, - st.ItemData.Name - ); - } - - MessageManager.HandleMessage( - null, - name, - string.Empty, - 0x03b2, - MessageType.Label, - 3, - TextType.CLIENT - ); - - obj.AddMessage(MessageType.Label, name, 3, 0x03b2, false, TextType.CLIENT); - - if (obj.TextContainer != null && obj.TextContainer.MaxSize != 1) - { - obj.TextContainer.MaxSize = 1; - } - - break; - - case Multi multi: - name = multi.Name; - - if (string.IsNullOrEmpty(name)) - { - name = ClilocLoader.Instance.GetString( - 1020000 + multi.Graphic, - multi.ItemData.Name - ); - } - - MessageManager.HandleMessage( - null, - name, - string.Empty, - 0x03b2, - MessageType.Label, - 3, - TextType.CLIENT - ); - - obj.AddMessage(MessageType.Label, name, 3, 0x03b2, false, TextType.CLIENT); - - if (obj.TextContainer != null && obj.TextContainer.MaxSize == 5) - { - obj.TextContainer.MaxSize = 1; - } - - break; - - case Entity ent: - - if (Keyboard.Alt && ent is Mobile) - { - MessageManager.HandleMessage( - World.Player, - ResGeneral.NowFollowing, - string.Empty, - 0, - MessageType.Regular, - 3, - TextType.CLIENT - ); - - ProfileManager.CurrentProfile.FollowingMode = true; - ProfileManager.CurrentProfile.FollowingTarget = ent; - } - else if (!DelayedObjectClickManager.IsEnabled) - { - DelayedObjectClickManager.Set( - ent.Serial, - Mouse.Position.X, - Mouse.Position.Y, - Time.Ticks + Mouse.MOUSE_DELAY_DOUBLE_CLICK - ); - } - - break; - } - } - - return true; - } - - private bool OnLeftMouseDoubleClick() - { - bool result = false; - - if (!UIManager.IsMouseOverWorld) - { - result = DelayedObjectClickManager.IsEnabled; - - if (result) - { - DelayedObjectClickManager.Clear(); - - return false; - } - - return false; - } - - BaseGameObject obj = SelectedObject.Object; - - switch (obj) - { - case Item item: - result = true; - - if (!GameActions.OpenCorpse(item)) - { - GameActions.DoubleClick(item); - } - - break; - - case Mobile mob: - result = true; - - if (World.Player.InWarMode && World.Player != mob) - { - GameActions.Attack(mob); - } - else - { - GameActions.DoubleClick(mob); - } - - break; - - case TextObject msg when msg.Owner is Entity entity: - result = true; - GameActions.DoubleClick(entity); - - break; - - default: - World.LastObject = 0; - - break; - } - - if (result) - { - DelayedObjectClickManager.Clear(); - } - - return result; - } - - private bool OnRightMouseDown() - { - if ( - UIManager.PopupMenu != null - && !UIManager.PopupMenu.Bounds.Contains(Mouse.Position.X, Mouse.Position.Y) - ) - { - UIManager.ShowGamePopup(null); - } - - if (!UIManager.IsMouseOverWorld) - { - return false; - } - - _rightMousePressed = true; - _continueRunning = false; - StopFollowing(); - - return true; - } - - private bool OnRightMouseUp() - { - if ( - UIManager.PopupMenu != null - && !UIManager.PopupMenu.Bounds.Contains(Mouse.Position.X, Mouse.Position.Y) - ) - { - UIManager.ShowGamePopup(null); - } - - _rightMousePressed = false; - - if (_boatIsMoving) - { - _boatIsMoving = false; - BoatMovingManager.MoveRequest(World.Player.Direction, 0); - } - - if (ProfileManager.CurrentProfile.EnablePathfind && ProfileManager.CurrentProfile.PathfindSingleClick) - { - if (ProfileManager.CurrentProfile.UseShiftToPathfind && !Keyboard.Shift) - { - return false; - } - - if (SelectedObject.Object is GameObject obj) - { - if (obj is Static || obj is Multi || obj is Item) - { - ref StaticTiles itemdata = ref TileDataLoader.Instance.StaticData[obj.Graphic]; - - if (itemdata.IsSurface && Pathfinder.WalkTo(obj.X, obj.Y, obj.Z, 0)) - { - World.Player.AddMessage - ( - MessageType.Label, - ResGeneral.Pathfinding, - 3, - 0, - false, - TextType.CLIENT - ); - - return true; - } - } - else if (obj is Land && Pathfinder.WalkTo(obj.X, obj.Y, obj.Z, 0)) - { - World.Player.AddMessage - ( - MessageType.Label, - ResGeneral.Pathfinding, - 3, - 0, - false, - TextType.CLIENT - ); - - return true; - } - } - } - - return UIManager.IsMouseOverWorld; - } - - private bool OnRightMouseDoubleClick() - { - if (!UIManager.IsMouseOverWorld) - { - return false; - } - - if (ProfileManager.CurrentProfile.EnablePathfind && !Pathfinder.AutoWalking) - { - if ((ProfileManager.CurrentProfile.UseShiftToPathfind && !Keyboard.Shift) || ProfileManager.CurrentProfile.PathfindSingleClick) - { - return false; - } - - if (SelectedObject.Object is GameObject obj) - { - if (obj is Static || obj is Multi || obj is Item) - { - ref StaticTiles itemdata = ref TileDataLoader.Instance.StaticData[ - obj.Graphic - ]; - - if (itemdata.IsSurface && Pathfinder.WalkTo(obj.X, obj.Y, obj.Z, 0)) - { - World.Player.AddMessage( - MessageType.Label, - ResGeneral.Pathfinding, - 3, - 0, - false, - TextType.CLIENT - ); - - return true; - } - } - else if (obj is Land && Pathfinder.WalkTo(obj.X, obj.Y, obj.Z, 0)) - { - World.Player.AddMessage( - MessageType.Label, - ResGeneral.Pathfinding, - 3, - 0, - false, - TextType.CLIENT - ); - - return true; - } - } - - //if (SelectedObject.Object is Land || GameObjectHelper.TryGetStaticData(SelectedObject.Object as GameObject, out var itemdata) && itemdata.IsSurface) - //{ - // if (SelectedObject.Object is GameObject obj && Pathfinder.WalkTo(obj.X, obj.Y, obj.Z, 0)) - // { - - // } - //} - } - - return false; - } - - private bool OnExtraMouseDown(MouseButtonType button) - { - if (CanExecuteMacro()) - { - Macro macro = Macros.FindMacro(button, Keyboard.Alt, Keyboard.Ctrl, Keyboard.Shift); - - if (macro != null && button != MouseButtonType.None) - { - if (macro.Items is MacroObject mac) - { - if (mac.Code == MacroType.LookAtMouse) - { - Client.Game.Scene.Camera.PeekingToMouse = true; - - if (mac.SubCode == MacroSubType.LookBackwards) - { - Client.Game.Scene.Camera.PeekBackwards = true; - } - - return true; - } - - ExecuteMacro(mac); - - return true; - } - } - } - - return false; - } - - private bool OnExtraMouseUp(MouseButtonType button) - { - if (Client.Game.Scene.Camera.PeekingToMouse) - { - Macro macro = Macros.FindMacro(button, Keyboard.Alt, Keyboard.Ctrl, Keyboard.Shift); - - if ( - macro != null - && macro.Items is MacroObject mac - && mac.Code == MacroType.LookAtMouse - ) - { - Client.Game.Scene.Camera.PeekingToMouse = Client - .Game - .Scene - .Camera - .PeekBackwards = false; - } - - return true; - } - - return false; - } - - internal override bool OnMouseWheel(bool up) - { - if (Keyboard.Ctrl && Client.Game.GameCursor.ItemHold.Enabled) - { - if (!up && !Client.Game.GameCursor.ItemHold.IsFixedPosition) - { - Client.Game.GameCursor.ItemHold.IsFixedPosition = true; - Client.Game.GameCursor.ItemHold.IgnoreFixedPosition = true; - Client.Game.GameCursor.ItemHold.FixedX = Mouse.Position.X; - Client.Game.GameCursor.ItemHold.FixedY = Mouse.Position.Y; - } - - if (Client.Game.GameCursor.ItemHold.IgnoreFixedPosition) - { - return true; - } - } - - if (CanExecuteMacro()) - { - Macro macro = Macros.FindMacro(up, Keyboard.Alt, Keyboard.Ctrl, Keyboard.Shift); - - if (macro != null) - { - if (macro.Items is MacroObject mac) - { - ExecuteMacro(mac); - - return true; - } - } - } - - if (!UIManager.IsMouseOverWorld) - { - return false; - } - - if (Keyboard.Ctrl && ProfileManager.CurrentProfile.EnableMousewheelScaleZoom) - { - if (up) - { - Camera.ZoomIn(); - } - else - { - Camera.ZoomOut(); - } - - return true; - } - - return false; - } - - internal override bool OnMouseDragging() - { - if (!UIManager.IsMouseOverWorld) - { - return false; - } - - bool ok = true; - - if (Mouse.LButtonPressed && !Client.Game.GameCursor.ItemHold.Enabled) - { - Point offset = Mouse.LDragOffset; - - if ( - !Client.Game.GameCursor.IsDraggingCursorForced - && // don't trigger "sallos ez grab" when dragging wmap or skill - !_isSelectionActive - && // and ofc when selection is enabled - ( - Math.Abs(offset.X) > Constants.MIN_PICKUP_DRAG_DISTANCE_PIXELS - || Math.Abs(offset.Y) > Constants.MIN_PICKUP_DRAG_DISTANCE_PIXELS - ) - ) - { - Entity obj; - - if ( - ProfileManager.CurrentProfile.SallosEasyGrab - && SelectedObject.Object is Entity ent - && SelectedObject.LastLeftDownObject == null - ) - { - obj = ent; - } - else - { - obj = SelectedObject.LastLeftDownObject as Entity; - } - - if (obj != null) - { - if (SerialHelper.IsMobile(obj.Serial) || obj is Item it && it.IsDamageable) - { - BaseHealthBarGump customgump = UIManager.GetGump( - obj - ); - customgump?.Dispose(); - - if (ProfileManager.CurrentProfile.CustomBarsToggled) - { - Rectangle rect = new Rectangle( - 0, - 0, - HealthBarGumpCustom.HPB_WIDTH, - HealthBarGumpCustom.HPB_HEIGHT_SINGLELINE - ); - - UIManager.Add( - customgump = new HealthBarGumpCustom(obj) - { - X = Mouse.LClickPosition.X - (rect.Width >> 1), - Y = Mouse.LClickPosition.Y - (rect.Height >> 1) - } - ); - } - else - { - var bounds = Client.Game.Gumps.GetGump(0x0804).UV; - - UIManager.Add( - customgump = new HealthBarGump(obj) - { - X = Mouse.LClickPosition.X - (bounds.Width >> 1), - Y = Mouse.LClickPosition.Y - (bounds.Height >> 1) - } - ); - } - - UIManager.AttemptDragControl(customgump, true); - ok = false; - } - else if (obj is Item item) - { - GameActions.PickUp(item, Mouse.Position.X, Mouse.Position.Y); - } - } - - SelectedObject.LastLeftDownObject = null; - } - } - - return ok; - } - - internal override void OnKeyDown(SDL.SDL_KeyboardEvent e) - { - if (e.keysym.sym == SDL.SDL_Keycode.SDLK_TAB && e.repeat != 0) - { - return; - } - - if (e.keysym.sym == SDL.SDL_Keycode.SDLK_ESCAPE && TargetManager.IsTargeting) - { - TargetManager.CancelTarget(); - } - - if (UIManager.KeyboardFocusControl != UIManager.SystemChat.TextBoxControl) - { - return; - } - - switch (e.keysym.sym) - { - case SDL.SDL_Keycode.SDLK_ESCAPE: - - if (Pathfinder.AutoWalking && Pathfinder.PathindingCanBeCancelled) - { - Pathfinder.StopAutoWalk(); - } - - break; - - case SDL.SDL_Keycode.SDLK_TAB when !ProfileManager.CurrentProfile.DisableTabBtn: - - if (ProfileManager.CurrentProfile.HoldDownKeyTab) - { - if (!_requestedWarMode) - { - _requestedWarMode = true; - - if (!World.Player.InWarMode) - { - NetClient.Socket.Send_ChangeWarMode(true); - } - } - } - - break; - - // chat system activation - - case SDL.SDL_Keycode.SDLK_1 when Keyboard.Shift: // ! - case SDL.SDL_Keycode.SDLK_BACKSLASH when Keyboard.Shift: // \ - - if ( - ProfileManager.CurrentProfile.ActivateChatAfterEnter - && ProfileManager.CurrentProfile.ActivateChatAdditionalButtons - && !UIManager.SystemChat.IsActive - ) - { - UIManager.SystemChat.IsActive = true; - } - - break; - - case SDL.SDL_Keycode.SDLK_EXCLAIM: // ! - case SDL.SDL_Keycode.SDLK_SEMICOLON: // ; - case SDL.SDL_Keycode.SDLK_COLON: // : - case SDL.SDL_Keycode.SDLK_SLASH: // / - case SDL.SDL_Keycode.SDLK_BACKSLASH: // \ - case SDL.SDL_Keycode.SDLK_PERIOD: // . - case SDL.SDL_Keycode.SDLK_KP_PERIOD: // . - case SDL.SDL_Keycode.SDLK_COMMA: // , - case SDL.SDL_Keycode.SDLK_LEFTBRACKET: // [ - case SDL.SDL_Keycode.SDLK_MINUS: // - - case SDL.SDL_Keycode.SDLK_KP_MINUS: // - - if ( - ProfileManager.CurrentProfile.ActivateChatAfterEnter - && ProfileManager.CurrentProfile.ActivateChatAdditionalButtons - && !UIManager.SystemChat.IsActive - ) - { - if (!Keyboard.Shift && !Keyboard.Alt && !Keyboard.Ctrl) - { - UIManager.SystemChat.IsActive = true; - } - else if (Keyboard.Shift && e.keysym.sym == SDL.SDL_Keycode.SDLK_SEMICOLON) - { - UIManager.SystemChat.IsActive = true; - } - } - - break; - - case SDL.SDL_Keycode.SDLK_RETURN: - case SDL.SDL_Keycode.SDLK_KP_ENTER: - - if (UIManager.KeyboardFocusControl == UIManager.SystemChat.TextBoxControl) - { - if (ProfileManager.CurrentProfile.ActivateChatAfterEnter) - { - UIManager.SystemChat.Mode = ChatMode.Default; - - if ( - !( - Keyboard.Shift - && ProfileManager.CurrentProfile.ActivateChatShiftEnterSupport - ) - ) - { - UIManager.SystemChat.ToggleChatVisibility(); - } - } - - return; - } - - break; - } - - if ( - UIManager.KeyboardFocusControl == UIManager.SystemChat.TextBoxControl - && UIManager.SystemChat.IsActive - && ProfileManager.CurrentProfile.ActivateChatAfterEnter - ) - { - return; - } - - if (CanExecuteMacro()) - { - Macro macro = Macros.FindMacro( - e.keysym.sym, - Keyboard.Alt, - Keyboard.Ctrl, - Keyboard.Shift - ); - - if (macro != null && e.keysym.sym != SDL.SDL_Keycode.SDLK_UNKNOWN) - { - if (macro.Items is MacroObject mac) - { - if (mac.Code == MacroType.LookAtMouse) - { - Client.Game.Scene.Camera.PeekingToMouse = true; - - if (mac.SubCode == MacroSubType.LookBackwards) - { - Client.Game.Scene.Camera.PeekBackwards = true; - } - } - else if (mac.Code == MacroType.Walk) - { - _flags[4] = true; - - switch (mac.SubCode) - { - case MacroSubType.NW: - _flags[0] = true; - - break; - - case MacroSubType.SW: - _flags[1] = true; - - break; - - case MacroSubType.SE: - _flags[2] = true; - - break; - - case MacroSubType.NE: - _flags[3] = true; - - break; - - case MacroSubType.N: - _flags[0] = true; - _flags[3] = true; - - break; - - case MacroSubType.S: - _flags[1] = true; - _flags[2] = true; - - break; - - case MacroSubType.E: - _flags[3] = true; - _flags[2] = true; - - break; - - case MacroSubType.W: - _flags[0] = true; - _flags[1] = true; - - break; - } - } - else - { - ExecuteMacro(mac); - } - } - } - else - { - if (string.IsNullOrEmpty(UIManager.SystemChat.TextBoxControl.Text)) - { - switch (e.keysym.sym) - { - case SDL.SDL_Keycode.SDLK_UP: - _flags[0] = true; - - break; - - case SDL.SDL_Keycode.SDLK_LEFT: - _flags[1] = true; - - break; - - case SDL.SDL_Keycode.SDLK_DOWN: - _flags[2] = true; - - break; - - case SDL.SDL_Keycode.SDLK_RIGHT: - _flags[3] = true; - - break; - } - } - } - } - - if (e.keysym.sym != SDL.SDL_Keycode.SDLK_UNKNOWN) - { - NameOverHeadManager.RegisterKeyDown(e.keysym); - } - } - - internal override void OnKeyUp(SDL.SDL_KeyboardEvent e) - { - if (!World.InGame) - { - return; - } - - if ( - ProfileManager.CurrentProfile.EnableMousewheelScaleZoom - && ProfileManager.CurrentProfile.RestoreScaleAfterUnpressCtrl - && !Keyboard.Ctrl - ) - { - Camera.Zoom = ProfileManager.CurrentProfile.DefaultScale; - } - - if (_flags[4] || Client.Game.Scene.Camera.PeekingToMouse) - { - Macro macro = Macros.FindMacro( - e.keysym.sym, - Keyboard.Alt, - Keyboard.Ctrl, - Keyboard.Shift - ); - - if (macro != null && e.keysym.sym != SDL.SDL_Keycode.SDLK_UNKNOWN) - { - if (macro.Items is MacroObject mac) - { - if (mac.Code == MacroType.LookAtMouse) - { - Client.Game.Scene.Camera.PeekingToMouse = Client - .Game - .Scene - .Camera - .PeekBackwards = false; - } - else if (mac.Code == MacroType.Walk) - { - _flags[4] = false; - - switch (mac.SubCode) - { - case MacroSubType.NW: - _flags[0] = false; - - break; - - case MacroSubType.SW: - _flags[1] = false; - - break; - - case MacroSubType.SE: - _flags[2] = false; - - break; - - case MacroSubType.NE: - _flags[3] = false; - - break; - - case MacroSubType.N: - _flags[0] = false; - _flags[3] = false; - - break; - - case MacroSubType.S: - _flags[1] = false; - _flags[2] = false; - - break; - - case MacroSubType.E: - _flags[3] = false; - _flags[2] = false; - - break; - - case MacroSubType.W: - _flags[0] = false; - _flags[1] = false; - - break; - } - - Macros.SetMacroToExecute(mac); - Macros.WaitForTargetTimer = 0; - Macros.Update(); - - for (int i = 0; i < 4; i++) - { - if (_flags[i]) - { - _flags[4] = true; - - break; - } - } - } - } - } - } - - switch (e.keysym.sym) - { - case SDL.SDL_Keycode.SDLK_UP: - _flags[0] = false; - - break; - - case SDL.SDL_Keycode.SDLK_LEFT: - _flags[1] = false; - - break; - - case SDL.SDL_Keycode.SDLK_DOWN: - _flags[2] = false; - - break; - - case SDL.SDL_Keycode.SDLK_RIGHT: - _flags[3] = false; - - break; - } - - if ( - e.keysym.sym == SDL.SDL_Keycode.SDLK_TAB - && !ProfileManager.CurrentProfile.DisableTabBtn - ) - { - if (ProfileManager.CurrentProfile.HoldDownKeyTab) - { - if (_requestedWarMode) - { - NetClient.Socket.Send_ChangeWarMode(false); - _requestedWarMode = false; - } - } - else - { - GameActions.ToggleWarMode(); - } - } - - NameOverHeadManager.RegisterKeyUp(e.keysym); - } - - internal override void OnControllerButtonDown(SDL.SDL_ControllerButtonEvent e) - { - base.OnControllerButtonDown(e); - - if (World.InGame && (UIManager.KeyboardFocusControl == UIManager.SystemChat.TextBoxControl || UIManager.KeyboardFocusControl == null)) - { - Macro macro = Macros.FindMacro((SDL.SDL_GameControllerButton)e.button); - if (macro != null && macro.Items is MacroObject mac) - { - ExecuteMacro(mac); - } - } - } - - private bool CanExecuteMacro() - { - return UIManager.KeyboardFocusControl == UIManager.SystemChat.TextBoxControl - && UIManager.SystemChat.Mode >= ChatMode.Default; - } - - private void ExecuteMacro(MacroObject macro) - { - Macros.SetMacroToExecute(macro); - Macros.WaitingBandageTarget = false; - Macros.WaitForTargetTimer = 0; - Macros.Update(); - } - } -} diff --git a/src/ClassicUO.Client/Game/Scenes/LoginScene.cs b/src/ClassicUO.Client/Game/Scenes/LoginScene.cs deleted file mode 100644 index 0ae9cd9dc..000000000 --- a/src/ClassicUO.Client/Game/Scenes/LoginScene.cs +++ /dev/null @@ -1,1143 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.IO; -using System.Net; -using System.Net.NetworkInformation; -using System.Net.Sockets; -using System.Text; -using System.Threading.Tasks; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Game.UI.Gumps.CharCreation; -using ClassicUO.Game.UI.Gumps.Login; -using ClassicUO.IO; -using ClassicUO.Assets; -using ClassicUO.Network; -using ClassicUO.Network.Encryption; -using ClassicUO.Resources; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.Scenes -{ - internal enum LoginSteps - { - Main, - Connecting, - VerifyingAccount, - ServerSelection, - LoginInToServer, - CharacterSelection, - EnteringBritania, - CharacterCreation, - CharacterCreationDone, - PopUpMessage - } - - internal sealed class LoginScene : Scene - { - private Gump _currentGump; - private LoginSteps _lastLoginStep; - private uint _pingTime; - private long _reconnectTime; - private int _reconnectTryCounter = 1; - private bool _autoLogin; - - - public bool Reconnect { get; set; } - public LoginSteps CurrentLoginStep { get; set; } = LoginSteps.Main; - public ServerListEntry[] Servers { get; private set; } - public CityInfo[] Cities { get; set; } - public string[] Characters { get; private set; } - public string PopupMessage { get; set; } - public byte ServerIndex { get; private set; } - public static string Account { get; internal set; } - public string Password { get; private set; } - public bool CanAutologin => _autoLogin || Reconnect; - - - public override void Load() - { - base.Load(); - - Client.Game.Window.AllowUserResizing = false; - - _autoLogin = Settings.GlobalSettings.AutoLogin; - - UIManager.Add(new LoginBackground()); - - if (string.IsNullOrEmpty(Settings.GlobalSettings.IP)) - { - UIManager.Add(new InputRequest("Please enter a server IP to connect to", "Save", "Cancel", (result, input) => - { - if (result == InputRequest.Result.BUTTON1 && !string.IsNullOrEmpty(input)) - { - if (Settings.GlobalSettings.Port <= 0) - { - UIManager.Add(new InputRequest("Please enter the port for this server", "Save", "Cancel", (result, input) => - { - if (result == InputRequest.Result.BUTTON1 && !string.IsNullOrEmpty(input)) - { - if (ushort.TryParse(input, out ushort p)) - { - Settings.GlobalSettings.Port = p; - } - } - UIManager.Add(_currentGump = new LoginGump(this)); - }) - { X = 130, Y = 150 }); - } - else //Port is > 0, possibly valid - { - UIManager.Add(_currentGump = new LoginGump(this)); - } - Settings.GlobalSettings.IP = input; - } - else //Cancel ip entry - { - UIManager.Add(_currentGump = new LoginGump(this)); - } - }) - { X = 130, Y = 150 }); - } - else - { - UIManager.Add(_currentGump = new LoginGump(this)); - } - - Client.Game.Audio.PlayMusic(Client.Game.Audio.LoginMusicIndex, false, true); - - if (CanAutologin && CurrentLoginStep != LoginSteps.Main || CUOEnviroment.SkipLoginScreen && _currentGump != null) - { - if (!string.IsNullOrEmpty(Settings.GlobalSettings.Username)) - { - // disable if it's the 2nd attempt - CUOEnviroment.SkipLoginScreen = false; - Connect(Settings.GlobalSettings.Username, Crypter.Decrypt(Settings.GlobalSettings.Password)); - } - } - - if (Client.Game.IsWindowMaximized()) - { - Client.Game.RestoreWindow(); - } - - Client.Game.SetWindowSize(640, 480); - } - - - public override void Unload() - { - if (IsDestroyed) - { - return; - } - - Client.Game.Audio?.StopMusic(); - Client.Game.Audio?.StopSounds(); - - UIManager.GetGump()?.Dispose(); - - _currentGump?.Dispose(); - - // UnRegistering Packet Events - NetClient.Socket.Connected -= OnNetClientConnected; - NetClient.Socket.Disconnected -= OnNetClientDisconnected; - - Client.Game.GameCursor.IsLoading = false; - base.Unload(); - } - - public override void Update() - { - base.Update(); - - if (_lastLoginStep != CurrentLoginStep) - { - Client.Game.GameCursor.IsLoading = false; - - // this trick avoid the flickering - Gump g = _currentGump; - UIManager.Add(_currentGump = GetGumpForStep()); - g?.Dispose(); - - _lastLoginStep = CurrentLoginStep; - } - - if (Reconnect && (CurrentLoginStep == LoginSteps.PopUpMessage || CurrentLoginStep == LoginSteps.Main) && !NetClient.Socket.IsConnected) - { - if (_reconnectTime < Time.Ticks) - { - if (!string.IsNullOrEmpty(Account)) - { - Connect(Account, Crypter.Decrypt(Settings.GlobalSettings.Password)); - } - else if (!string.IsNullOrEmpty(Settings.GlobalSettings.Username)) - { - Connect(Settings.GlobalSettings.Username, Crypter.Decrypt(Settings.GlobalSettings.Password)); - } - - int timeT = Settings.GlobalSettings.ReconnectTime * 1000; - - if (timeT < 1000) - { - timeT = 1000; - } - - _reconnectTime = (long)Time.Ticks + timeT; - _reconnectTryCounter++; - } - } - - if ((CurrentLoginStep == LoginSteps.CharacterCreation || CurrentLoginStep == LoginSteps.CharacterSelection) && Time.Ticks > _pingTime) - { - // Note that this will not be an ICMP ping, so it's better that this *not* be affected by -no_server_ping. - - if (NetClient.Socket.IsConnected) - { - NetClient.Socket.Statistics.SendPing(); - } - - _pingTime = Time.Ticks + 60000; - } - } - - private Gump GetGumpForStep() - { - foreach (Item item in World.Items.Values) - { - World.RemoveItem(item); - } - - foreach (Mobile mobile in World.Mobiles.Values) - { - World.RemoveMobile(mobile); - } - - World.Mobiles.Clear(); - World.Items.Clear(); - - switch (CurrentLoginStep) - { - case LoginSteps.Main: - PopupMessage = null; - - return new LoginGump(this); - - case LoginSteps.Connecting: - case LoginSteps.VerifyingAccount: - case LoginSteps.LoginInToServer: - case LoginSteps.EnteringBritania: - case LoginSteps.PopUpMessage: - case LoginSteps.CharacterCreationDone: - Client.Game.GameCursor.IsLoading = CurrentLoginStep != LoginSteps.PopUpMessage; - - return GetLoadingScreen(); - - case LoginSteps.CharacterSelection: return new CharacterSelectionGump(); - - case LoginSteps.ServerSelection: - _pingTime = Time.Ticks + 60000; // reset ping timer - - return new ServerSelectionGump(); - - case LoginSteps.CharacterCreation: - _pingTime = Time.Ticks + 60000; // reset ping timer - - return new CharCreationGump(this); - } - - return null; - } - - private LoadingGump GetLoadingScreen() - { - string labelText = "No Text"; - LoginButtons showButtons = LoginButtons.None; - - if (!string.IsNullOrEmpty(PopupMessage)) - { - labelText = PopupMessage; - showButtons = LoginButtons.OK; - PopupMessage = null; - } - else - { - switch (CurrentLoginStep) - { - case LoginSteps.Connecting: - labelText = ClilocLoader.Instance.GetString(3000002, ResGeneral.Connecting); // "Connecting..." - - showButtons = LoginButtons.Cancel; - - break; - - case LoginSteps.VerifyingAccount: - labelText = ClilocLoader.Instance.GetString(3000003, ResGeneral.VerifyingAccount); // "Verifying Account..." - - showButtons = LoginButtons.Cancel; - - break; - - case LoginSteps.LoginInToServer: - labelText = ClilocLoader.Instance.GetString(3000053, ResGeneral.LoggingIntoShard); // logging into shard - - break; - - case LoginSteps.EnteringBritania: - labelText = ClilocLoader.Instance.GetString(3000001, ResGeneral.EnteringBritannia); // Entering Britania... - - break; - - case LoginSteps.CharacterCreationDone: - labelText = ResGeneral.CreatingCharacter; - - break; - } - } - - return new LoadingGump(labelText, showButtons, OnLoadingGumpButtonClick); - } - - private void OnLoadingGumpButtonClick(int buttonId) - { - LoginButtons butt = (LoginButtons)buttonId; - - if (butt == LoginButtons.OK || butt == LoginButtons.Cancel) - { - StepBack(); - } - } - - public void Connect(string account, string password) - { - if (CurrentLoginStep == LoginSteps.Connecting) - { - return; - } - - Account = account; - Password = password; - - // Save credentials to config file - if (Settings.GlobalSettings.SaveAccount) - { - Settings.GlobalSettings.Username = Account; - Settings.GlobalSettings.Password = Crypter.Encrypt(Password); - try - { - Settings.GlobalSettings.Save(); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - Log.Trace($"Start login to: {Settings.GlobalSettings.IP},{Settings.GlobalSettings.Port}"); - - - if (!Reconnect) - { - CurrentLoginStep = LoginSteps.Connecting; - } - - //NetClient.LoginSocket.Disconnected += (o, e) => { - // PopupMessage = ResGeneral.CheckYourConnectionAndTryAgain; - // CurrentLoginStep = LoginSteps.PopUpMessage; - // Log.Error("No Internet Access"); - //}; - - NetClient.Socket.Connected -= OnNetClientConnected; - NetClient.Socket.Disconnected -= OnNetClientDisconnected; - NetClient.Socket.Connected += OnNetClientConnected; - NetClient.Socket.Disconnected += OnNetClientDisconnected; - NetClient.Socket.Connect(Settings.GlobalSettings.IP, Settings.GlobalSettings.Port); - } - - - - public int GetServerIndexByName(string name) - { - if (!string.IsNullOrWhiteSpace(name)) - { - for (int i = 0; i < Servers.Length; i++) - { - if (Servers[i].Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)) - { - return i; - } - } - } - - return -1; - } - - public int GetServerIndexFromSettings() - { - string name = Settings.GlobalSettings.LastServerName; - int index = GetServerIndexByName(name); - - if (index == -1) - { - index = Settings.GlobalSettings.LastServerNum; - } - - if (index < 0 || index >= Servers.Length) - { - index = 0; - } - - return index; - } - - public void SelectServer(byte index) - { - if (CurrentLoginStep == LoginSteps.ServerSelection) - { - for (byte i = 0; i < Servers.Length; i++) - { - if (Servers[i].Index == index) - { - ServerIndex = i; - - break; - } - } - - Settings.GlobalSettings.LastServerNum = (ushort)(1 + ServerIndex); - Settings.GlobalSettings.LastServerName = Servers[ServerIndex].Name; - Settings.GlobalSettings.Save(); - - CurrentLoginStep = LoginSteps.LoginInToServer; - - World.ServerName = Servers[ServerIndex].Name; - - NetClient.Socket.Send_SelectServer(index); - } - } - - public void SelectCharacter(uint index) - { - if (CurrentLoginStep == LoginSteps.CharacterSelection) - { - LastCharacterManager.Save(Account, World.ServerName, Characters[index]); - - CurrentLoginStep = LoginSteps.EnteringBritania; - NetClient.Socket.Send_SelectCharacter(index, Characters[index], NetClient.Socket.LocalIP); - } - } - - public void StartCharCreation() - { - if (CurrentLoginStep == LoginSteps.CharacterSelection) - { - CurrentLoginStep = LoginSteps.CharacterCreation; - } - } - - public void CreateCharacter(PlayerMobile character, int cityIndex, byte profession) - { - int i = 0; - - for (; i < Characters.Length; i++) - { - if (string.IsNullOrEmpty(Characters[i])) - { - break; - } - } - - LastCharacterManager.Save(Account, World.ServerName, character.Name); - - NetClient.Socket.Send_CreateCharacter(character, - cityIndex, - NetClient.Socket.LocalIP, - ServerIndex, - (uint)i, - profession); - - CurrentLoginStep = LoginSteps.CharacterCreationDone; - } - - public void DeleteCharacter(uint index) - { - if (CurrentLoginStep == LoginSteps.CharacterSelection) - { - NetClient.Socket.Send_DeleteCharacter((byte)index, NetClient.Socket.LocalIP); - } - } - - public void StepBack() - { - PopupMessage = null; - - if (Characters != null && CurrentLoginStep != LoginSteps.CharacterCreation) - { - CurrentLoginStep = LoginSteps.LoginInToServer; - } - - switch (CurrentLoginStep) - { - case LoginSteps.Connecting: - case LoginSteps.VerifyingAccount: - case LoginSteps.ServerSelection: - DisposeAllServerEntries(); - CurrentLoginStep = LoginSteps.Main; - NetClient.Socket.Disconnect(); - - break; - - case LoginSteps.LoginInToServer: - NetClient.Socket.Disconnect(); - Characters = null; - DisposeAllServerEntries(); - Connect(Account, Password); - - break; - - case LoginSteps.CharacterCreation: - CurrentLoginStep = LoginSteps.CharacterSelection; - - break; - - case LoginSteps.PopUpMessage: - case LoginSteps.CharacterSelection: - NetClient.Socket.Disconnect(); - Characters = null; - DisposeAllServerEntries(); - CurrentLoginStep = LoginSteps.Main; - - break; - } - } - - public CityInfo GetCity(int index) - { - if (index < Cities.Length) - { - return Cities[index]; - } - - return null; - } - - private void OnNetClientConnected(object sender, EventArgs e) - { - Log.Info("Connected!"); - CurrentLoginStep = LoginSteps.VerifyingAccount; - - uint address = NetClient.Socket.LocalIP; - - EncryptionHelper.Initialize(true, address, (ENCRYPTION_TYPE)Settings.GlobalSettings.Encryption); - - if (Client.Version >= ClientVersion.CV_6040) - { - uint clientVersion = (uint)Client.Version; - - byte major = (byte)(clientVersion >> 24); - byte minor = (byte)(clientVersion >> 16); - byte build = (byte)(clientVersion >> 8); - byte extra = (byte)clientVersion; - - - NetClient.Socket.Send_Seed(address, major, minor, build, extra); - } - else - { - NetClient.Socket.Send_Seed_Old(address); - } - - NetClient.Socket.Send_FirstLogin(Account, Password); - } - - private void OnNetClientDisconnected(object sender, SocketError e) - { - Log.Warn("Disconnected"); - - if (CurrentLoginStep == LoginSteps.CharacterCreation) - { - return; - } - - if (e != 0) - { - Characters = null; - DisposeAllServerEntries(); - - if (Settings.GlobalSettings.Reconnect) - { - Reconnect = true; - - PopupMessage = string.Format(ResGeneral.ReconnectPleaseWait01, _reconnectTryCounter, StringHelper.AddSpaceBeforeCapital(e.ToString())); - - UIManager.GetGump()?.SetText(PopupMessage); - } - else - { - PopupMessage = string.Format(ResGeneral.ConnectionLost0, StringHelper.AddSpaceBeforeCapital(e.ToString())); - } - - CurrentLoginStep = LoginSteps.PopUpMessage; - } - } - - public void ServerListReceived(ref StackDataReader p) - { - byte flags = p.ReadUInt8(); - ushort count = p.ReadUInt16BE(); - DisposeAllServerEntries(); - Servers = new ServerListEntry[count]; - - for (ushort i = 0; i < count; i++) - { - Servers[i] = ServerListEntry.Create(ref p); - } - - CurrentLoginStep = LoginSteps.ServerSelection; - - if (CanAutologin) - { - if (Servers.Length != 0) - { - int index = GetServerIndexFromSettings(); - - SelectServer((byte)Servers[index].Index); - } - } - } - - public void UpdateCharacterList(ref StackDataReader p) - { - ParseCharacterList(ref p); - - if (CurrentLoginStep != LoginSteps.PopUpMessage) - { - PopupMessage = null; - } - CurrentLoginStep = LoginSteps.CharacterSelection; - UIManager.GetGump()?.Dispose(); - - _currentGump?.Dispose(); - - UIManager.Add(_currentGump = new CharacterSelectionGump()); - if (!string.IsNullOrWhiteSpace(PopupMessage)) - { - Gump g = null; - g = new LoadingGump(PopupMessage, LoginButtons.OK, (but) => g.Dispose()) { IsModal = true }; - UIManager.Add(g); - PopupMessage = null; - } - } - - public void ReceiveCharacterList(ref StackDataReader p) - { - ParseCharacterList(ref p); - ParseCities(ref p); - - World.ClientFeatures.SetFlags((CharacterListFlags)p.ReadUInt32BE()); - CurrentLoginStep = LoginSteps.CharacterSelection; - - uint charToSelect = 0; - - bool haveAnyCharacter = false; - bool canLogin = CanAutologin; - - if (_autoLogin) - { - _autoLogin = false; - } - - string lastCharName = LastCharacterManager.GetLastCharacter(Account, World.ServerName); - - for (byte i = 0; i < Characters.Length; i++) - { - if (Characters[i].Length > 0) - { - haveAnyCharacter = true; - - if (Characters[i] == lastCharName) - { - charToSelect = i; - - break; - } - } - } - - if (canLogin && haveAnyCharacter) - { - SelectCharacter(charToSelect); - } - else if (!haveAnyCharacter) - { - StartCharCreation(); - } - } - - public void HandleErrorCode(ref StackDataReader p) - { - byte code = p.ReadUInt8(); - - PopupMessage = ServerErrorMessages.GetError(p[0], code); - CurrentLoginStep = LoginSteps.PopUpMessage; - } - - public void HandleRelayServerPacket(ref StackDataReader p) - { - long ip = p.ReadUInt32LE(); // use LittleEndian here - ushort port = p.ReadUInt16BE(); - uint seed = p.ReadUInt32BE(); - - NetClient.Socket.Disconnect(); - NetClient.Socket = new NetClient(); - EncryptionHelper.Initialize(false, seed, (ENCRYPTION_TYPE)Settings.GlobalSettings.Encryption); - - NetClient.Socket.Connect(new IPAddress(ip).ToString(), port); - - if (NetClient.Socket.IsConnected) - { - NetClient.Socket.EnableCompression(); - unsafe - { - Span b = stackalloc byte[4] { (byte)(seed >> 24), (byte)(seed >> 16), (byte)(seed >> 8), (byte)seed }; - NetClient.Socket.Send(b, true, true); - } - - NetClient.Socket.Send_SecondLogin(Account, Password, seed); - } - } - - - private void ParseCharacterList(ref StackDataReader p) - { - int count = p.ReadUInt8(); - Characters = new string[count]; - - for (ushort i = 0; i < count; i++) - { - Characters[i] = p.ReadASCII(30).TrimEnd('\0'); - - p.Skip(30); - } - } - - private void ParseCities(ref StackDataReader p) - { - byte count = p.ReadUInt8(); - Cities = new CityInfo[count]; - - bool isNew = Client.Version >= ClientVersion.CV_70130; - string[] descriptions = null; - - if (!isNew) - { - descriptions = ReadCityTextFile(count); - } - - Point[] oldtowns = - { - new Point(105, 130), new Point(245, 90), - new Point(165, 200), new Point(395, 160), - new Point(200, 305), new Point(335, 250), - new Point(160, 395), new Point(100, 250), - new Point(270, 130), new Point(0xFFFF, 0xFFFF) - }; - - for (int i = 0; i < count; i++) - { - CityInfo cityInfo; - - if (isNew) - { - byte cityIndex = p.ReadUInt8(); - string cityName = p.ReadASCII(32); - string cityBuilding = p.ReadASCII(32); - ushort cityX = (ushort)p.ReadUInt32BE(); - ushort cityY = (ushort)p.ReadUInt32BE(); - sbyte cityZ = (sbyte)p.ReadUInt32BE(); - uint cityMapIndex = p.ReadUInt32BE(); - uint cityDescription = p.ReadUInt32BE(); - p.Skip(4); - - cityInfo = new CityInfo - ( - cityIndex, - cityName, - cityBuilding, - ClilocLoader.Instance.GetString((int)cityDescription), - cityX, - cityY, - cityZ, - cityMapIndex, - isNew - ); - } - else - { - byte cityIndex = p.ReadUInt8(); - string cityName = p.ReadASCII(31); - string cityBuilding = p.ReadASCII(31); - - cityInfo = new CityInfo - ( - cityIndex, - cityName, - cityBuilding, - descriptions != null ? descriptions[i] : string.Empty, - (ushort)oldtowns[i % oldtowns.Length].X, - (ushort)oldtowns[i % oldtowns.Length].Y, - 0, - 0, - isNew - ); - } - - Cities[i] = cityInfo; - } - } - - private string[] ReadCityTextFile(int count) - { - string path = UOFileManager.GetUOFilePath("citytext.enu"); - - if (!File.Exists(path)) - { - return null; - } - - string[] descr = new string[count]; - - // TODO: stackalloc ? - byte[] data = new byte[4]; - - StringBuilder name = new StringBuilder(); - StringBuilder text = new StringBuilder(); - - using (FileStream stream = File.OpenRead(path)) - { - int cityIndex = 0; - - while (stream.Position < stream.Length) - { - int r = stream.Read(data, 0, 4); - - if (r == -1) - { - break; - } - - string dataText = Encoding.UTF8.GetString(data, 0, 4); - - if (dataText == "END\0") - { - name.Clear(); - - while (stream.Position < stream.Length) - { - char b = (char)stream.ReadByte(); - - if (b == '<') - { - stream.Position -= 1; - - break; - } - - name.Append(b); - } - - text.Clear(); - - while (stream.Position < stream.Length) - { - char b; - - while ((b = (char)stream.ReadByte()) != '\0') - { - text.Append(b); - } - - if (text.Length != 0) - { - string t = text + "\n\n"; - text.Clear(); - - text.Append(t); - } - - long pos = stream.Position; - byte end = (byte)stream.ReadByte(); - stream.Position = pos; - - if (end == 0x2E) - { - break; - } - - int r1 = stream.Read(data, 0, 4); - stream.Position = pos; - - if (r1 == -1) - { - break; - } - - string dataText1 = Encoding.UTF8.GetString(data, 0, 4); - - if (dataText1 == "END\0") - { - break; - } - } - - if (descr.Length <= cityIndex) - { - break; - } - - descr[cityIndex++] = text.ToString(); - } - else - { - stream.Position -= 3; - } - } - } - - return descr; - } - - private void DisposeAllServerEntries() - { - if (Servers != null) - { - for (int i = 0; i < Servers.Length; i++) - { - if (Servers[i] != null) - { - Servers[i].Dispose(); - Servers[i] = null; - } - } - - Servers = null; - } - } - } - - internal class ServerListEntry - { - private IPAddress _ipAddress; - private Ping _pinger = new Ping(); - private bool _sending; - private readonly bool[] _last10Results = new bool[10]; - private int _resultIndex; - - private ServerListEntry() - { - } - - public static ServerListEntry Create(ref StackDataReader p) - { - ServerListEntry entry = new ServerListEntry() - { - Index = p.ReadUInt16BE(), - Name = p.ReadASCII(32, true), - PercentFull = p.ReadUInt8(), - Timezone = p.ReadUInt8(), - Address = p.ReadUInt32BE() - }; - - // some server sends invalid ip. - try - { - entry._ipAddress = new IPAddress - ( - new byte[] - { - (byte) ((entry.Address >> 24) & 0xFF), - (byte) ((entry.Address >> 16) & 0xFF), - (byte) ((entry.Address >> 8) & 0xFF), - (byte) (entry.Address & 0xFF) - } - ); - } - catch (Exception e) - { - Log.Error(e.ToString()); - } - - entry._pinger.PingCompleted += entry.PingerOnPingCompleted; - - return entry; - } - - - public uint Address; - public ushort Index; - public string Name; - public byte PercentFull; - public byte Timezone; - public int Ping = -1; - public int PacketLoss; - public IPStatus PingStatus; - - private static byte[] _buffData = new byte[32]; - private static PingOptions _pingOptions = new PingOptions(64, true); - - public void DoPing() - { - if (_ipAddress != null && !_sending && _pinger != null) - { - if (_resultIndex >= _last10Results.Length) - { - _resultIndex = 0; - } - - try - { - _pinger.SendAsync - ( - _ipAddress, - 1000, - _buffData, - _pingOptions, - _resultIndex++ - ); - - _sending = true; - } - catch - { - _ipAddress = null; - Dispose(); - } - } - } - - private void PingerOnPingCompleted(object sender, PingCompletedEventArgs e) - { - int index = (int)e.UserState; - - if (e.Reply != null) - { - Ping = (int)e.Reply.RoundtripTime; - PingStatus = e.Reply.Status; - - _last10Results[index] = e.Reply.Status == IPStatus.Success; - } - - //if (index >= _last10Results.Length - 1) - { - PacketLoss = 0; - - for (int i = 0; i < _resultIndex; i++) - { - if (!_last10Results[i]) - { - ++PacketLoss; - } - } - - PacketLoss = (Math.Max(1, PacketLoss) / Math.Max(1, _resultIndex)) * 100; - - //_resultIndex = 0; - } - - _sending = false; - } - - public void Dispose() - { - if (_pinger != null) - { - _pinger.PingCompleted -= PingerOnPingCompleted; - - if (_sending) - { - try - { - _pinger.SendAsyncCancel(); - } - catch { } - - } - - _pinger.Dispose(); - _pinger = null; - } - } - } - - internal class CityInfo - { - public CityInfo - ( - int index, - string city, - string building, - string description, - ushort x, - ushort y, - sbyte z, - uint map, - bool isNew - ) - { - Index = index; - City = city; - Building = building; - Description = description; - X = x; - Y = y; - Z = z; - Map = map; - IsNewCity = isNew; - } - - public readonly string Building; - public readonly string City; - public readonly string Description; - public readonly int Index; - public readonly bool IsNewCity; - public readonly uint Map; - public readonly ushort X, Y; - public readonly sbyte Z; - } -} diff --git a/src/ClassicUO.Client/Game/Scenes/Scene.cs b/src/ClassicUO.Client/Game/Scenes/Scene.cs deleted file mode 100644 index 99cb71c39..000000000 --- a/src/ClassicUO.Client/Game/Scenes/Scene.cs +++ /dev/null @@ -1,105 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Game.Managers; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using SDL2; - -namespace ClassicUO.Game.Scenes -{ - internal abstract class Scene : IDisposable - { - public bool IsDestroyed { get; private set; } - public bool IsLoaded { get; private set; } - public int RenderedObjectsCount { get; protected set; } - public Camera Camera { get; } = new Camera(0.5f, 2.5f, 0.1f); - - - - public virtual void Dispose() - { - if (IsDestroyed) - { - return; - } - - Unload(); - IsDestroyed = true; - } - - public virtual void Update() - { - Camera.Update(true, Time.Delta, Mouse.Position); - } - - public virtual bool Draw(UltimaBatcher2D batcher) - { - return true; - } - - - public virtual void Load() - { - IsLoaded = true; - } - - public virtual void Unload() - { - IsLoaded = false; - } - - - internal virtual bool OnMouseUp(MouseButtonType button) => false; - internal virtual bool OnMouseDown(MouseButtonType button) => false; - internal virtual bool OnMouseDoubleClick(MouseButtonType button) => false; - internal virtual bool OnMouseWheel(bool up) => false; - internal virtual bool OnMouseDragging() => false; - - internal virtual void OnControllerButtonDown(SDL.SDL_ControllerButtonEvent e) { } - internal virtual void OnControllerButtonUp(SDL.SDL_ControllerButtonEvent e) { } - - internal virtual void OnTextInput(string text) - { - } - - internal virtual void OnKeyDown(SDL.SDL_KeyboardEvent e) - { - } - - internal virtual void OnKeyUp(SDL.SDL_KeyboardEvent e) - { - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/Scenes/SceneType.cs b/src/ClassicUO.Client/Game/Scenes/SceneType.cs deleted file mode 100644 index 369b83cd0..000000000 --- a/src/ClassicUO.Client/Game/Scenes/SceneType.cs +++ /dev/null @@ -1,41 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.Scenes -{ - internal enum SceneType - { - None, - Login, - Game - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/SelectedObject.cs b/src/ClassicUO.Client/Game/SelectedObject.cs deleted file mode 100644 index 13c609178..000000000 --- a/src/ClassicUO.Client/Game/SelectedObject.cs +++ /dev/null @@ -1,94 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Runtime.CompilerServices; -using ClassicUO.Game.GameObjects; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game -{ - internal static class SelectedObject - { - public static Point TranslatedMousePositionByViewport; - public static BaseGameObject Object; - public static BaseGameObject LastLeftDownObject; - public static Entity HealthbarObject; - public static Item SelectedContainer; - public static Item CorpseObject; - - private static readonly bool[,] _InternalArea = new bool[44, 44]; - - static SelectedObject() - { - for (int y = 21, i = 0; y >= 0; --y, i++) - { - for (int x = 0; x < 22; x++) - { - if (x < i) - { - continue; - } - - _InternalArea[x, y] = _InternalArea[43 - x, 43 - y] = _InternalArea[43 - x, y] = _InternalArea[x, 43 - y] = true; - } - } - } - - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsPointInLand(int x, int y) - { - x = TranslatedMousePositionByViewport.X - x; - y = TranslatedMousePositionByViewport.Y - y; - - return x >= 0 && x < 44 && y >= 0 && y < 44 && _InternalArea[x, y]; - } - - public static bool IsPointInStretchedLand(ref UltimaBatcher2D.YOffsets yOffsets, int x, int y) - { - //y -= 22; - x += 22; - - int testX = TranslatedMousePositionByViewport.X - x; - int testY = TranslatedMousePositionByViewport.Y; - - int y0 = -yOffsets.Top; - int y1 = 22 - yOffsets.Left; - int y2 = 44 - yOffsets.Bottom; - int y3 = 22 - yOffsets.Right; - - - return testY >= testX * (y1 - y0) / -22 + y + y0 && testY >= testX * (y3 - y0) / 22 + y + y0 && testY <= testX * (y3 - y2) / 22 + y + y2 && testY <= testX * (y1 - y2) / -22 + y + y2; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/SerialHelper.cs b/src/ClassicUO.Client/Game/SerialHelper.cs deleted file mode 100644 index b37b84dd1..000000000 --- a/src/ClassicUO.Client/Game/SerialHelper.cs +++ /dev/null @@ -1,73 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Globalization; -using System.Runtime.CompilerServices; - -namespace ClassicUO.Game -{ - internal static class SerialHelper - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsValid(uint serial) - { - return serial > 0 && serial < 0x80000000; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsMobile(uint serial) - { - return serial > 0 && serial < 0x40000000; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsItem(uint serial) - { - return serial >= 0x40000000 && serial < 0x80000000; - } - - public static uint Parse(string str) - { - if (str.StartsWith("0x")) - { - return uint.Parse(str.Remove(0, 2), NumberStyles.HexNumber); - } - - if (str.Length > 1 && str[0] == '-') - { - return (uint) int.Parse(str); - } - - return uint.Parse(str); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/AlphaBlendControl.cs b/src/ClassicUO.Client/Game/UI/Controls/AlphaBlendControl.cs deleted file mode 100644 index 148394c30..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/AlphaBlendControl.cs +++ /dev/null @@ -1,70 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - public sealed class AlphaBlendControl : Control - { - public AlphaBlendControl(float alpha = 0.5f) - { - Alpha = alpha; - AcceptMouseInput = false; - } - - public ushort Hue { get; set; } - - public Color BaseColor { get; set; } = Color.Black; - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(Hue, false, Alpha); - - batcher.Draw - ( - SolidColorTextureCache.GetTexture(BaseColor), - new Rectangle - ( - x, - y, - Width, - Height - ), - hueVector - ); - - return true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/Area.cs b/src/ClassicUO.Client/Game/UI/Controls/Area.cs deleted file mode 100644 index dbc75c0b7..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/Area.cs +++ /dev/null @@ -1,34 +0,0 @@ -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - public class Area : Control - { - private bool drawBorder; - private int hue; - - public Area(bool _drawBorder = true, int _borderHue = 0) - { - AcceptMouseInput = true; - AcceptKeyboardInput = true; - drawBorder = _drawBorder; - hue = _borderHue; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - if (drawBorder) - batcher.DrawRectangle( - SolidColorTextureCache.GetTexture(Color.Gray), - x, y, - Width-1, - Height-1, - ShaderHueTranslator.GetHueVector(hue) - ); - return true; - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/ArrowNumbersTextBox.cs b/src/ClassicUO.Client/Game/UI/Controls/ArrowNumbersTextBox.cs deleted file mode 100644 index bc218f646..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ArrowNumbersTextBox.cs +++ /dev/null @@ -1,193 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Renderer; - -namespace ClassicUO.Game.UI.Controls -{ - public class ArrowNumbersTextBox : Control - { - private const int TIME_BETWEEN_CLICKS = 250; - private readonly int _Min, _Max; - private readonly StbTextBox _textBox; - private uint _timeUntilNextClick; - private readonly Button _up, _down; - - public ArrowNumbersTextBox - ( - int x, - int y, - int width, - int raiseamount, - int minvalue, - int maxvalue, - byte font = 0, - int maxcharlength = -1, - bool isunicode = true, - FontStyle style = FontStyle.None, - ushort hue = 0 - ) - { - int height = 20; - X = x; - Y = y; - Width = width; - Height = height; - _Min = minvalue; - _Max = maxvalue; - - Add - ( - new ResizePic(0x0BB8) - { - Width = width, - Height = height + 4 - } - ); - - _up = new Button(raiseamount, 0x983, 0x984) - { - X = width - 12, - ButtonAction = ButtonAction.Activate - }; - - _up.MouseDown += (sender, e) => - { - if (_up.IsClicked) - { - UpdateValue(); - _timeUntilNextClick = TIME_BETWEEN_CLICKS * 2; - } - }; - - Add(_up); - - _down = new Button(-raiseamount, 0x985, 0x986) - { - X = width - 12, - Y = height - 7, - ButtonAction = ButtonAction.Activate - }; - - _down.MouseDown += (sender, e) => - { - if (_down.IsClicked) - { - UpdateValue(); - _timeUntilNextClick = TIME_BETWEEN_CLICKS * 2; - } - }; - - Add(_down); - - Add - ( - _textBox = new StbTextBox - ( - font, - maxcharlength, - width, - isunicode, - style, - hue - ) - { - X = 2, - Y = 2, - Height = height, - Width = width - 17, - NumbersOnly = true - } - ); - } - - internal string Text - { - get => _textBox?.Text ?? string.Empty; - set => _textBox?.SetText(value); - } - - private void UpdateValue() - { - int.TryParse(_textBox.Text, out int i); - - if (_up.IsClicked) - { - i += _up.ButtonID; - } - else - { - i += _down.ButtonID; - } - - ValidateValue(i); - } - - internal override void OnFocusLost() - { - if (IsDisposed) - { - return; - } - - int.TryParse(_textBox.Text, out int i); - ValidateValue(i); - } - - private void ValidateValue(int val) - { - Tag = val = Math.Max(_Min, Math.Min(_Max, val)); - _textBox.SetText(val.ToString()); - } - - public override void Update() - { - if (IsDisposed) - { - return; - } - - if (_up.IsClicked || _down.IsClicked) - { - if (Time.Ticks > _timeUntilNextClick) - { - _timeUntilNextClick = Time.Ticks + TIME_BETWEEN_CLICKS; - - UpdateValue(); - } - } - - base.Update(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/Button.cs b/src/ClassicUO.Client/Game/UI/Controls/Button.cs deleted file mode 100644 index 488f2c364..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/Button.cs +++ /dev/null @@ -1,330 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Game.Scenes; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.UI.Controls -{ - public enum ButtonAction - { - Default = 0, - SwitchPage = 0, - Activate = 1 - } - - public class Button : Control - { - private readonly string _caption; - private bool _entered; - private readonly RenderedText[] _fontTexture; - private ushort _normal, - _pressed, - _over; - - public Button( - int buttonID, - ushort normal, - ushort pressed, - ushort over = 0, - string caption = "", - byte font = 0, - bool isunicode = true, - ushort normalHue = ushort.MaxValue, - ushort hoverHue = ushort.MaxValue - ) - { - ButtonID = buttonID; - _normal = normal; - _pressed = pressed; - _over = over; - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(normal); - if (gumpInfo.Texture == null) - { - Dispose(); - - return; - } - - Width = gumpInfo.UV.Width; - Height = gumpInfo.UV.Height; - FontHue = normalHue == ushort.MaxValue ? (ushort)0 : normalHue; - HueHover = hoverHue == ushort.MaxValue ? normalHue : hoverHue; - - if (!string.IsNullOrEmpty(caption) && normalHue != ushort.MaxValue) - { - _fontTexture = new RenderedText[2]; - - _caption = caption; - - _fontTexture[0] = RenderedText.Create(caption, FontHue, font, isunicode); - - if (hoverHue != ushort.MaxValue) - { - _fontTexture[1] = RenderedText.Create(caption, HueHover, font, isunicode); - } - } - - CanMove = false; - AcceptMouseInput = true; - //CanCloseWithRightClick = false; - CanCloseWithEsc = false; - } - - public Button(List parts) - : this( - parts.Count >= 8 ? int.Parse(parts[7]) : 0, - UInt16Converter.Parse(parts[3]), - UInt16Converter.Parse(parts[4]) - ) - { - X = int.Parse(parts[1]); - Y = int.Parse(parts[2]); - - if (parts.Count >= 6) - { - int action = int.Parse(parts[5]); - - ButtonAction = action == 0 ? ButtonAction.SwitchPage : ButtonAction.Activate; - } - - ToPage = parts.Count >= 7 ? int.Parse(parts[6]) : 0; - WantUpdateSize = false; - ContainsByBounds = true; - IsFromServer = true; - } - - public bool IsClicked { get; set; } - - public int ButtonID { get; } - - public ButtonAction ButtonAction { get; set; } - - public int ToPage { get; set; } - - public override ClickPriority Priority => ClickPriority.High; - - public ushort ButtonGraphicNormal - { - get => _normal; - set - { - _normal = value; - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(value); - - Width = gumpInfo.UV.Width; - Height = gumpInfo.UV.Height; - } - } - - public ushort ButtonGraphicPressed - { - get => _pressed; - set - { - _pressed = value; - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(value); - - Width = gumpInfo.UV.Width; - Height = gumpInfo.UV.Height; - } - } - - public ushort ButtonGraphicOver - { - get => _over; - set - { - _over = value; - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(value); - - Width = gumpInfo.UV.Width; - Height = gumpInfo.UV.Height; - } - } - - public int Hue { get; set; } - public ushort FontHue { get; } - - public ushort HueHover { get; } - - public bool FontCenter { get; set; } - - public bool ContainsByBounds { get; set; } - - protected override void OnMouseEnter(int x, int y) - { - _entered = true; - } - - protected override void OnMouseExit(int x, int y) - { - _entered = false; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Texture2D texture = null; - Rectangle bounds = Rectangle.Empty; - - if (_entered || IsClicked) - { - if (IsClicked && _pressed > 0) - { - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(_pressed); - texture = gumpInfo.Texture; - bounds = gumpInfo.UV; - } - - if (texture == null && _over > 0) - { - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(_over); - texture = gumpInfo.Texture; - bounds = gumpInfo.UV; - } - } - - if (texture == null) - { - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(_normal); - texture = gumpInfo.Texture; - bounds = gumpInfo.UV; - } - - if (texture == null) - { - return false; - } - - var hue = ShaderHueTranslator.GetHueVector(Hue, false, Alpha, true); - - batcher.Draw(texture, new Rectangle(x, y, Width, Height), bounds, hue); - - if (!string.IsNullOrEmpty(_caption)) - { - RenderedText textTexture = _fontTexture[_entered ? 1 : 0]; - - if (FontCenter) - { - int yoffset = IsClicked ? 1 : 0; - - textTexture.Draw( - batcher, - x + ((Width - textTexture.Width) >> 1), - y + yoffset + ((Height - textTexture.Height) >> 1) - ); - } - else - { - textTexture.Draw(batcher, x, y); - } - } - - return base.Draw(batcher, x, y); - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - IsClicked = true; - } - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - IsClicked = false; - - if (!MouseIsOver) - { - return; - } - - if (_entered || Client.Game.Scene is GameScene) - { - switch (ButtonAction) - { - case ButtonAction.SwitchPage: - ChangePage(ToPage); - - break; - - case ButtonAction.Activate: - OnButtonClick(ButtonID); - - break; - } - - Mouse.LastLeftButtonClickTime = 0; - Mouse.CancelDoubleClick = true; - } - } - } - - public override bool Contains(int x, int y) - { - if (IsDisposed) - { - return false; - } - - return ContainsByBounds - ? base.Contains(x, y) - : Client.Game.Gumps.PixelCheck(_normal, x - Offset.X, y - Offset.Y, InternalScale); - } - - public sealed override void Dispose() - { - if (_fontTexture != null) - { - foreach (RenderedText t in _fontTexture) - { - t?.Destroy(); - } - } - - base.Dispose(); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/ButtonTileArt.cs b/src/ClassicUO.Client/Game/UI/Controls/ButtonTileArt.cs deleted file mode 100644 index efea00572..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ButtonTileArt.cs +++ /dev/null @@ -1,95 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - public class ButtonTileArt : Button - { - private readonly ushort _hue; - private readonly bool _isPartial; - private readonly int _tileX, - _tileY; - private ushort _graphic; - - public ButtonTileArt(List gparams) : base(gparams) - { - X = int.Parse(gparams[1]); - Y = int.Parse(gparams[2]); - _graphic = UInt16Converter.Parse(gparams[8]); - _hue = UInt16Converter.Parse(gparams[9]); - _tileX = int.Parse(gparams[10]); - _tileY = int.Parse(gparams[11]); - ContainsByBounds = true; - IsFromServer = true; - - ref readonly var artInfo = ref Client.Game.Arts.GetArt(_graphic); - - if (artInfo.Texture == null) - { - Dispose(); - - return; - } - - _isPartial = TileDataLoader.Instance.StaticData[_graphic].IsPartialHue; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - var hueVector = ShaderHueTranslator.GetHueVector(_hue, _isPartial, 1f); - - ref readonly var artInfo = ref Client.Game.Arts.GetArt(_graphic); - - if (artInfo.Texture != null) - { - batcher.Draw( - artInfo.Texture, - new Vector2(x + _tileX, y + _tileY), - artInfo.UV, - hueVector - ); - - return true; - } - - return false; - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/Checkbox.cs b/src/ClassicUO.Client/Game/UI/Controls/Checkbox.cs deleted file mode 100644 index 3cec16e7a..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/Checkbox.cs +++ /dev/null @@ -1,157 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - public class Checkbox : Control - { - private bool _isChecked; - private readonly RenderedText _text; - private ushort _inactive, - _active; - - public Checkbox( - ushort inactive, - ushort active, - string text = "", - byte font = 0, - ushort color = 0, - bool isunicode = true, - int maxWidth = 0 - ) - { - _inactive = inactive; - _active = active; - - ref readonly var gumpInfoInactive = ref Client.Game.Gumps.GetGump(inactive); - ref readonly var gumpInfoActive = ref Client.Game.Gumps.GetGump(active); - - if (gumpInfoInactive.Texture == null || gumpInfoActive.Texture == null) - { - Dispose(); - - return; - } - - Width = gumpInfoInactive.UV.Width; - - _text = RenderedText.Create(text, color, font, isunicode, maxWidth: maxWidth); - - Width += _text.Width; - - Height = Math.Max(gumpInfoInactive.UV.Width, _text.Height); - CanMove = false; - AcceptMouseInput = true; - } - - public Checkbox(List parts, string[] lines) - : this(ushort.Parse(parts[3]), ushort.Parse(parts[4])) - { - X = int.Parse(parts[1]); - Y = int.Parse(parts[2]); - IsChecked = parts[5] == "1"; - LocalSerial = SerialHelper.Parse(parts[6]); - IsFromServer = true; - } - - public bool IsChecked - { - get => _isChecked; - set - { - if (_isChecked != value) - { - _isChecked = value; - OnCheckedChanged(); - } - } - } - - public override ClickPriority Priority => ClickPriority.High; - - public string Text => _text.Text; - - public event EventHandler ValueChanged; - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsDisposed) - { - return false; - } - - var ok = base.Draw(batcher, x, y); - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump( - IsChecked ? _active : _inactive - ); - - batcher.Draw( - gumpInfo.Texture, - new Vector2(x, y), - gumpInfo.UV, - ShaderHueTranslator.GetHueVector(0) - ); - - _text.Draw(batcher, x + gumpInfo.UV.Width + 2, y); - - return ok; - } - - protected virtual void OnCheckedChanged() - { - ValueChanged.Raise(this); - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left && MouseIsOver) - { - IsChecked = !IsChecked; - } - } - - public override void Dispose() - { - base.Dispose(); - _text?.Destroy(); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/CheckerTrans.cs b/src/ClassicUO.Client/Game/UI/Controls/CheckerTrans.cs deleted file mode 100644 index a1d60e852..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/CheckerTrans.cs +++ /dev/null @@ -1,129 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.UI.Controls -{ - internal class CheckerTrans : Control - { - //TODO(deccer): should be moved into Renderer namespace - private static readonly Lazy _checkerStencil = new Lazy - ( - () => - { - DepthStencilState depthStencilState = new DepthStencilState - { - DepthBufferEnable = false, - StencilEnable = true, - StencilFunction = CompareFunction.Always, - ReferenceStencil = 1, - StencilMask = 1, - StencilFail = StencilOperation.Keep, - StencilDepthBufferFail = StencilOperation.Keep, - StencilPass = StencilOperation.Replace - }; - - - return depthStencilState; - } - ); - - - //TODO(deccer): should be moved into Renderer namespace - private static readonly Lazy _checkerBlend = new Lazy - ( - () => - { - BlendState blendState = new BlendState - { - ColorWriteChannels = ColorWriteChannels.None - }; - - return blendState; - } - ); - - //public CheckerTrans(float alpha = 0.5f) - //{ - // _alpha = alpha; - // AcceptMouseInput = false; - //} - - public CheckerTrans(List parts) - { - X = int.Parse(parts[1]); - Y = int.Parse(parts[2]); - Width = int.Parse(parts[3]); - Height = int.Parse(parts[4]); - AcceptMouseInput = false; - IsFromServer = true; - } - - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - //batcher.SetBlendState(_checkerBlend.Value); - //batcher.SetStencil(_checkerStencil.Value); - - //batcher.Draw2D(TransparentTexture, new Rectangle(position.X, position.Y, Width, Height), Vector3.Zero /*ShaderHueTranslator.GetHueVector(0, false, 0.5f, false)*/); - - //batcher.SetBlendState(null); - //batcher.SetStencil(null); - - //return true; - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0, false, 0.5f); - - //batcher.SetStencil(_checkerStencil.Value); - batcher.Draw - ( - SolidColorTextureCache.GetTexture(Color.Black), - new Rectangle - ( - x, - y, - Width, - Height - ), - hueVector - ); - - //batcher.SetStencil(null); - return true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/ClickPriority.cs b/src/ClassicUO.Client/Game/UI/Controls/ClickPriority.cs deleted file mode 100644 index 7c72b94db..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ClickPriority.cs +++ /dev/null @@ -1,41 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.UI.Controls -{ - public enum ClickPriority - { - High, - Default, - Low - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/ClickableColorBox.cs b/src/ClassicUO.Client/Game/UI/Controls/ClickableColorBox.cs deleted file mode 100644 index aab087274..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ClickableColorBox.cs +++ /dev/null @@ -1,118 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - public class ClickableColorBox : ColorBox - { - private readonly bool useModernSelector; - - public ClickableColorBox - ( - int x, - int y, - int w, - int h, - ushort hue, - bool useModernSelector = false - ) : base(w, h, hue) - { - X = x; - Y = y; - WantUpdateSize = false; - - GumpPic background = new GumpPic(0, 0, 0x00D4, 0); - Add(background); - - Width = background.Width; - Height = background.Height; - this.useModernSelector = useModernSelector; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (Children.Count != 0) - { - Children[0].Draw(batcher, x, y); - } - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(Hue); - - batcher.Draw - ( - SolidColorTextureCache.GetTexture(Color.White), - new Rectangle - ( - x + 3, - y + 3, - Width - 6, - Height - 6 - ), - hueVector - ); - - return true; - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - UIManager.GetGump()?.Dispose(); - if (useModernSelector) - { - UIManager.Add(new ModernColorPicker(s => Hue = s) { X = 100, Y = 100 }); - } - else - { - ColorPickerGump pickerGump = new ColorPickerGump - ( - 0, - 0, - 100, - 100, - s => Hue = s - ); - - UIManager.Add(pickerGump); - } - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/ColorBox.cs b/src/ClassicUO.Client/Game/UI/Controls/ColorBox.cs deleted file mode 100644 index 5eba292e7..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ColorBox.cs +++ /dev/null @@ -1,78 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.UI.Controls -{ - public class ColorBox : Control - { - public ColorBox(int width, int height, ushort hue) - { - CanMove = false; - - Width = width; - Height = height; - Hue = hue; - - WantUpdateSize = false; - } - - public ushort Hue { get; set; } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(Hue); - - hueVector.Z = Alpha; - - batcher.Draw - ( - SolidColorTextureCache.GetTexture(Color.White), - new Rectangle - ( - x, - y, - Width, - Height - ), - hueVector - ); - - return true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/ColorPickerBox.cs b/src/ClassicUO.Client/Game/UI/Controls/ColorPickerBox.cs deleted file mode 100644 index a3995252f..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ColorPickerBox.cs +++ /dev/null @@ -1,257 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Runtime.InteropServices; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.UI.Controls -{ - internal class ColorPickerBox : Gump - { - private readonly int _cellHeight; - private readonly int _cellWidth; - private readonly int _columns; - private readonly ushort[] _customPallete; - private int _graduation, _selectedIndex; - private ushort[] _hues; - private bool _needToFileeBoxes = true; - private readonly int _rows; - - - public ColorPickerBox - ( - int x, - int y, - int rows = 10, - int columns = 20, - int cellW = 8, - int cellH = 8, - ushort[] customPallete = null - ) : base(0, 0) - { - X = x; - Y = y; - Width = columns * cellW; - Height = rows * cellH; - _rows = rows; - _columns = columns; - _cellWidth = cellW; - _cellHeight = cellH; - - _customPallete = customPallete; - AcceptMouseInput = true; - - - Graduation = 1; - SelectedIndex = 0; - } - - - public event EventHandler ColorSelectedIndex; - - public bool ShowLivePreview { get; set; } - - public ushort[] Hues - { - get - { - CreateTexture(); - - return _hues; - } - } - - public int Graduation - { - get => _graduation; - set - { - if (_graduation != value) - { - _graduation = value; - - _needToFileeBoxes = true; - - CreateTexture(); - ColorSelectedIndex.Raise(); - } - } - } - - public int SelectedIndex - { - get => _selectedIndex; - set - { - if (value < 0 || value >= _hues.Length) - { - return; - } - - if (_selectedIndex != value) - { - _selectedIndex = value; - ColorSelectedIndex.Raise(); - } - } - } - - public ushort SelectedHue => SelectedIndex < 0 || SelectedIndex >= _hues.Length ? (ushort) 0 : _hues[SelectedIndex]; - - - public override void Update() - { - if (IsDisposed) - { - return; - } - - if (_needToFileeBoxes) - { - CreateTexture(); - } - - if (ShowLivePreview) - { - int xx = Mouse.Position.X - X - ParentX; - int yy = Mouse.Position.Y - Y - ParentY; - - if (Bounds.Contains(Mouse.Position.X, Mouse.Position.Y)) - { - SetSelectedIndex(xx, yy); - } - } - - base.Update(); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Texture2D texture = SolidColorTextureCache.GetTexture(Color.White); - - Rectangle rect = new Rectangle(0, 0, _cellWidth, _cellHeight); - - Vector3 hueVector; - - for (int i = 0; i < _rows; i++) - { - for (int j = 0; j < _columns; j++) - { - hueVector = ShaderHueTranslator.GetHueVector(_hues[i * _columns + j]); - - rect.X = x + j * _cellWidth; - rect.Y = y + i * _cellHeight; - - batcher.Draw - ( - texture, - rect, - hueVector - ); - } - } - - hueVector = ShaderHueTranslator.GetHueVector(0); - - if (_hues.Length > 1) - { - rect.X = (int) (x + Width / _columns * (SelectedIndex % _columns + .5f) - 1); - rect.Y = (int)(y + Height / _rows * (SelectedIndex / _columns + .5f) - 1); - rect.Width = 2; - rect.Height = 2; - - batcher.Draw - ( - SolidColorTextureCache.GetTexture(Color.White), - rect, - hueVector - ); - } - - return base.Draw(batcher, x, y); - } - - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - SetSelectedIndex(x, y); - } - } - - private void SetSelectedIndex(int x, int y) - { - int row = x / (Width / _columns); - int column = y / (Height / _rows); - SelectedIndex = row + column * _columns; - } - - private void CreateTexture() - { - if (!_needToFileeBoxes || IsDisposed) - { - return; - } - - _needToFileeBoxes = false; - - - int size = _rows * _columns; - ushort startColor = (ushort)(Graduation + 1); - - if (_hues == null || size != _hues.Length) - { - _hues = new ushort[size]; - } - - for (int y = 0; y < _rows; y++) - { - for (int x = 0; x < _columns; x++) - { - ushort hue = (ushort) ((_customPallete?[y * _columns + x] ?? startColor) + 1); - - _hues[y * _columns + x] = hue; - - startColor += 5; - } - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/Combobox.cs b/src/ClassicUO.Client/Game/UI/Controls/Combobox.cs deleted file mode 100644 index 615dbd90f..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/Combobox.cs +++ /dev/null @@ -1,294 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Linq; -using ClassicUO.Configuration; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - internal class Combobox : Control - { - private readonly byte _font; - private readonly string[] _items; - private readonly Label _label; - private readonly int _maxHeight; - private int _selectedIndex; - - public Combobox - ( - int x, - int y, - int width, - string[] items, - int selected = -1, - int maxHeight = 200, - bool showArrow = true, - string emptyString = "", - byte font = 9 - ) - { - X = x; - Y = y; - Width = width; - Height = 25; - SelectedIndex = selected; - _font = font; - _items = items; - _maxHeight = maxHeight; - - Add - ( - new ResizePic(0x0BB8) - { - Width = width, Height = Height - } - ); - - string initialText = selected > -1 ? items[selected] : emptyString; - - bool isAsianLang = string.Compare(Settings.GlobalSettings.Language, "CHT", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "KOR", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "JPN", StringComparison.InvariantCultureIgnoreCase) == 0; - - bool unicode = isAsianLang; - byte font1 = (byte)(isAsianLang ? 1 : _font); - - Add - ( - _label = new Label(initialText, unicode, 0x0453, font: font1) - { - X = 2, Y = 5 - } - ); - - if (showArrow) - { - Add(new GumpPic(width - 18, 2, 0x00FC, 0)); - } - } - - - public int SelectedIndex - { - get => _selectedIndex; - set - { - _selectedIndex = value; - - if (_items != null) - { - _label.Text = _items[value]; - - OnOptionSelected?.Invoke(this, value); - } - } - } - - - public event EventHandler OnOptionSelected; - - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (batcher.ClipBegin(x, y, Width, Height)) - { - base.Draw(batcher, x, y); - batcher.ClipEnd(); - } - - return true; - } - - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button != MouseButtonType.Left) - { - return; - } - - int comboY = ScreenCoordinateY + Offset.Y; - - if (comboY < 0) - { - comboY = 0; - } - else if (comboY + _maxHeight > Client.Game.Window.ClientBounds.Height) - { - comboY = Client.Game.Window.ClientBounds.Height - _maxHeight; - } - - UIManager.Add - ( - new ComboboxGump - ( - ScreenCoordinateX, - comboY, - Width, - _maxHeight, - _items, - _font, - this - ) - ); - - base.OnMouseUp(x, y, button); - } - - private class ComboboxGump : Gump - { - private const int ELEMENT_HEIGHT = 15; - - - private readonly Combobox _combobox; - - public ComboboxGump - ( - int x, - int y, - int width, - int maxHeight, - string[] items, - byte font, - Combobox combobox - ) : base(0, 0) - { - CanMove = false; - AcceptMouseInput = true; - X = x; - Y = y; - - IsModal = true; - LayerOrder = UILayer.Over; - ModalClickOutsideAreaClosesThisControl = true; - - _combobox = combobox; - - ResizePic background; - Add(background = new ResizePic(0x0BB8)); - background.AcceptMouseInput = false; - - HoveredLabel[] labels = new HoveredLabel[items.Length]; - - bool isAsianLang = string.Compare(Settings.GlobalSettings.Language, "CHT", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "KOR", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "JPN", StringComparison.InvariantCultureIgnoreCase) == 0; - - bool unicode = isAsianLang; - byte font1 = (byte)(isAsianLang ? 1 : font); - - for (int i = 0; i < items.Length; i++) - { - string item = items[i]; - - if (item == null) - { - item = string.Empty; - } - - HoveredLabel label = new HoveredLabel - ( - item, - unicode, - 0x0453, - 0x0453, - 0x0453, - font: font1 - ) - { - X = 2, - Y = i * ELEMENT_HEIGHT, - DrawBackgroundCurrentIndex = true, - IsVisible = item.Length != 0, - Tag = i - }; - - label.MouseUp += LabelOnMouseUp; - - labels[i] = label; - } - - int totalHeight = Math.Min(maxHeight, labels.Max(o => o.Y + o.Height)); - int maxWidth = Math.Max(width, labels.Max(o => o.X + o.Width)); - - ScrollArea area = new ScrollArea - ( - 0, - 0, - maxWidth + 15, - totalHeight, - true - ); - - foreach (HoveredLabel label in labels) - { - label.Width = maxWidth; - area.Add(label); - } - - Add(area); - - background.Width = maxWidth; - background.Height = totalHeight; - } - - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (batcher.ClipBegin(x, y, Width, Height)) - { - base.Draw(batcher, x, y); - - batcher.ClipEnd(); - } - - return true; - } - - private void LabelOnMouseUp(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtonType.Left) - { - _combobox.SelectedIndex = (int) ((Label) sender).Tag; - - Dispose(); - } - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/ContextMenuControl.cs b/src/ClassicUO.Client/Game/UI/Controls/ContextMenuControl.cs deleted file mode 100644 index 6997f77c9..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ContextMenuControl.cs +++ /dev/null @@ -1,394 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; - -namespace ClassicUO.Game.UI.Controls -{ - public class ContextMenuControl - { - private readonly List _items; - - public ContextMenuControl() - { - _items = new List(); - } - - public void Add(string text, Action action, bool canBeSelected = false, bool defaultValue = false) - { - _items.Add(new ContextMenuItemEntry(text, action, canBeSelected, defaultValue)); - } - - public void Add(ContextMenuItemEntry entry) - { - _items.Add(entry); - } - - public void Add(string text, List entries) - { - _items.Add - ( - new ContextMenuItemEntry(text) - { - Items = entries - } - ); - } - - public void Show() - { - UIManager.ShowContextMenu(null); - - if (_items.Count == 0) - { - return; - } - - UIManager.ShowContextMenu - ( - new ContextMenuShowMenu(_items) - ); - } - - public void Dispose() - { - UIManager.ShowContextMenu(null); - _items.Clear(); - } - } - - public class ContextMenuItemEntry - { - public ContextMenuItemEntry(string text, Action action = null, bool canBeSelected = false, bool defaultValue = false) - { - Text = text; - Action = action; - CanBeSelected = canBeSelected; - IsSelected = defaultValue; - } - - public readonly Action Action; - public readonly bool CanBeSelected; - public bool IsSelected; - public List Items = new List(); - public readonly string Text; - - public void Add(ContextMenuItemEntry subEntry) - { - Items.Add(subEntry); - } - } - - - public class ContextMenuShowMenu : Gump - { - private readonly AlphaBlendControl _background; - private List _subMenus; - - - public ContextMenuShowMenu(List list) : base(0, 0) - { - WantUpdateSize = true; - ModalClickOutsideAreaClosesThisControl = true; - IsModal = true; - LayerOrder = UILayer.Over; - - CanMove = false; - AcceptMouseInput = true; - - - _background = new AlphaBlendControl(0.7f); - Add(_background); - - int y = 0; - - for (int i = 0; i < list.Count; i++) - { - ContextMenuItem item = new ContextMenuItem(this, list[i]); - - if (i > 0) - { - item.Y = y; - } - - if (_background.Width < item.Width) - { - _background.Width = item.Width; - } - - _background.Height += item.Height; - - Add(item); - - y += item.Height; - } - - X = Mouse.Position.X + 5; - Y = Mouse.Position.Y - 20; - - if (X + _background.Width > Client.Game.Window.ClientBounds.Width) - { - X = Client.Game.Window.ClientBounds.Width - _background.Width; - } - - if (Y + _background.Height > Client.Game.Window.ClientBounds.Height) - { - Y = Client.Game.Window.ClientBounds.Height - _background.Height; - } - - foreach (ContextMenuItem mitem in FindControls()) - { - if (mitem.Width < _background.Width) - { - mitem.Width = _background.Width; - } - } - } - - - public override void Update() - { - base.Update(); - WantUpdateSize = true; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - batcher.DrawRectangle - ( - SolidColorTextureCache.GetTexture(Color.Gray), - x - 1, - y - 1, - _background.Width + 1, - _background.Height + 1, - hueVector - ); - - return base.Draw(batcher, x, y); - } - - public override bool Contains(int x, int y) - { - if (_background.Bounds.Contains(x, y)) - { - return true; - } - - if (_subMenus != null) - { - foreach (ContextMenuShowMenu menu in _subMenus) - { - if (menu.Contains(x - menu.X, y - menu.Y)) - { - return true; - } - } - } - - return false; - } - - private class ContextMenuItem : Control - { - private static readonly RenderedText _moreMenuLabel = RenderedText.Create(">", 0xFFFF, isunicode: true, style: FontStyle.BlackBorder); - private readonly ContextMenuItemEntry _entry; - private readonly Label _label; - private readonly GumpPic _selectedPic; - private readonly ContextMenuShowMenu _subMenu; - - - public ContextMenuItem(ContextMenuShowMenu parent, ContextMenuItemEntry entry) - { - CanCloseWithRightClick = false; - _entry = entry; - - _label = new Label - ( - entry.Text, - true, - 0xFFFF, - 0, - style: FontStyle.BlackBorder - ) - { - X = 25 - }; - - Add(_label); - - - _selectedPic = new GumpPic(3, 0, 0x838, 0) - { - IsVisible = entry.IsSelected, - IsEnabled = false - }; - - Add(_selectedPic); - - Height = 25; - - - _label.Y = (Height >> 1) - (_label.Height >> 1); - - if (_selectedPic != null) - { - //_label.X = _selectedPic.X + _selectedPic.Width + 6; - _selectedPic.Y = (Height >> 1) - (_selectedPic.Height >> 1); - } - - Width = _label.X + _label.Width + 20; - - if (Width < 100) - { - Width = 100; - } - - // it is a bit tricky, but works :D - if (_entry.Items != null && _entry.Items.Count != 0) - { - _subMenu = new ContextMenuShowMenu(_entry.Items); - parent.Add(_subMenu); - - if (parent._subMenus == null) - { - parent._subMenus = new List(); - } - - parent._subMenus.Add(_subMenu); - } - - WantUpdateSize = false; - } - - - public override void Update() - { - base.Update(); - - if (Width > _label.Width) - { - _label.Width = Width; - } - - if (_selectedPic != null) - { - _selectedPic.IsVisible = _entry.IsSelected; - } - - if (_subMenu != null) - { - _subMenu.X = Width; - _subMenu.Y = Y; - - if (MouseIsOver) - { - _subMenu.IsVisible = true; - } - else - { - Control p = UIManager.MouseOverControl?.Parent; - - while (p != null) - { - if (p == _subMenu) - { - break; - } - - p = p.Parent; - } - - _subMenu.IsVisible = p != null; - } - } - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - _entry.Action?.Invoke(); - - RootParent?.Dispose(); - - if (_entry.CanBeSelected) - { - _entry.IsSelected = !_entry.IsSelected; - _selectedPic.IsVisible = _entry.IsSelected; - } - - Mouse.CancelDoubleClick = true; - Mouse.LastLeftButtonClickTime = 0; - base.OnMouseUp(x, y, button); - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (!string.IsNullOrWhiteSpace(_label.Text) && MouseIsOver) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - batcher.Draw - ( - SolidColorTextureCache.GetTexture(Color.Gray), - new Rectangle - ( - x + 2, - y + 5, - Width - 4, - Height - 10 - ), - hueVector - ); - } - - base.Draw(batcher, x, y); - - if (_entry.Items != null && _entry.Items.Count != 0) - { - _moreMenuLabel.Draw(batcher, x + Width - _moreMenuLabel.Width, y + (Height >> 1) - (_moreMenuLabel.Height >> 1) - 1); - } - - return true; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/Control.cs b/src/ClassicUO.Client/Game/UI/Controls/Control.cs deleted file mode 100644 index d90472c88..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/Control.cs +++ /dev/null @@ -1,943 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Managers; -using ClassicUO.Input; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Input; -using SDL2; -using System; -using System.Collections.Generic; -using System.Linq; -using Keyboard = ClassicUO.Input.Keyboard; - -namespace ClassicUO.Game.UI.Controls -{ - public abstract class Control - { - internal static int _StepsDone = 1; - internal static int _StepChanger = 1; - - private bool _acceptKeyboardInput, _acceptMouseInput; - private int _activePage; - private Rectangle _bounds; - private bool _handlesKeyboardFocus; - private Point _offset; - private Control _parent; - - protected Control(Control parent = null) - { - Parent = parent; - Children = new List(); - AllowedToDraw = true; - AcceptMouseInput = true; - Page = 0; - - IsDisposed = false; - IsEnabled = true; - } - - public virtual ClickPriority Priority { get; set; } = ClickPriority.Default; - - public uint ServerSerial { get; set; } - - public uint LocalSerial { get; set; } - - public bool IsFromServer { get; set; } - - /// - /// This is not implemented in all controls, this is for use in custom control's that want to have a scale setting - /// - public double Scale { get; set; } = 1.0f; - - /// - /// This is intended for scaling mouse positions and other non-visual uses - /// - public double InternalScale { get; set; } = 1.0f; - - public int Page { get; set; } - - public Point Location - { - get => _bounds.Location; - set - { - X = value.X; - Y = value.Y; - _bounds.Location = value; - } - } - - public ref Rectangle Bounds => ref _bounds; - - public Point Offset => _offset; - - public bool IsDisposed { get; private set; } - - public bool IsVisible { get; set; } = true; - - public bool IsEnabled { get; set; } - - public bool HasKeyboardFocus => UIManager.KeyboardFocusControl == this; - - public bool MouseIsOver => UIManager.MouseOverControl == this; - - public bool CanMove { get; set; } - - public bool CanCloseWithRightClick { get; set; } = true; - - public bool CanCloseWithEsc { get; set; } - - public bool IsEditable { get; set; } - - public bool IsFocused { get; set; } - - public float Alpha { get; set; } = 1.0f; - - public List Children { get; } - - public object Tag { get; set; } - - public object Tooltip { get; private set; } - - public bool HasTooltip => /*World.ClientFlags.TooltipsEnabled &&*/ Tooltip != null; - - public virtual bool AcceptKeyboardInput - { - get => IsEnabled && !IsDisposed && IsVisible && _acceptKeyboardInput; - set => _acceptKeyboardInput = value; - } - - public virtual bool AcceptMouseInput - { - get => IsEnabled && !IsDisposed && _acceptMouseInput && IsVisible; - set => _acceptMouseInput = value; - } - - public ref int X => ref _bounds.X; - - public ref int Y => ref _bounds.Y; - - public ref int Width => ref _bounds.Width; - - public ref int Height => ref _bounds.Height; - - public int ParentX => Parent != null ? Parent.X + Parent.ParentX : 0; - - public int ParentY => Parent != null ? Parent.Y + Parent.ParentY : 0; - - public int ScreenCoordinateX => ParentX + X; - - public int ScreenCoordinateY => ParentY + Y; - - public ContextMenuControl ContextMenu { get; set; } - - public Control Parent - { - get => _parent; - internal set - { - if (value == null) - { - _parent?.Children.Remove(this); - } - else - { - _parent?.Children.Remove(this); - value.Children.Add(this); - } - - _parent = value; - } - } - - public Control RootParent - { - get - { - if (Parent == null) - { - return null; - } - - Control p = Parent; - - while (p.Parent != null) - { - p = p.Parent; - } - - return p; - } - } - - public UILayer LayerOrder { get; set; } = UILayer.Default; - public bool IsModal { get; set; } - public bool ModalClickOutsideAreaClosesThisControl { get; set; } - - - public virtual bool HandlesKeyboardFocus - { - get - { - if (!IsEnabled || IsDisposed || !IsVisible) - { - return false; - } - - if (_handlesKeyboardFocus) - { - return true; - } - - if (Children == null) - { - return false; - } - - foreach (Control c in Children) - { - if (c.HandlesKeyboardFocus) - { - return true; - } - } - - return false; - } - set => _handlesKeyboardFocus = value; - } - - public int ActivePage - { - get => _activePage; - set - { - _activePage = value; - - OnPageChanged(); - } - } - - public bool WantUpdateSize { get; set; } = true; - - public bool AllowedToDraw { get; set; } - - public int TooltipMaxLength { get; private set; } - - public void UpdateOffset(int x, int y) - { - if (_offset.X != x || _offset.Y != y) - { - _offset.X = x; - _offset.Y = y; - - foreach (Control c in Children) - { - c.UpdateOffset(x, y); - } - } - } - - - - public virtual bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsDisposed) - { - return false; - } - - for (int i = 0; i < Children.Count; i++) - { - if (Children.Count <= i) - { - break; - } - Control c = Children.ElementAt(i); - - if (c != null && (c.Page == 0 || c.Page == ActivePage)) - { - if (c.IsVisible) - { - c.Draw(batcher, c.X + x, c.Y + y); - } - } - } - - DrawDebug(batcher, x, y); - - return true; - } - - public virtual void Update() - { - if (IsDisposed) - { - return; - } - - if (Children.Count != 0) - { - //InitializeControls(); - int w = 0, h = 0; - - for (int i = 0; i < Children.Count; i++) - { - Control c = Children.ElementAt(i); - - if (c == null) - { - continue; - } - - if (c.IsDisposed) - { - OnChildRemoved(); - //Children.RemoveAt(i); - Children.Remove(c); - i--; - continue; - } - - c.Update(); - - if (WantUpdateSize) - { - if ((c.Page == 0 || c.Page == ActivePage) && c.IsVisible) - { - if (w < c.Bounds.Right) - { - w = c.Bounds.Right; - } - - if (h < c.Bounds.Bottom) - { - h = c.Bounds.Bottom; - } - } - } - } - - if (WantUpdateSize && IsVisible) - { - if (w != Width) - { - Width = w; - } - - if (h != Height) - { - Height = h; - } - - WantUpdateSize = false; - } - } - } - - /// - /// Scale the width and height of this control. Width/Height * Scale - /// - /// - /// This control - public virtual Control ScaleWidthAndHeight(double scale) - { - if (scale != 1f) - { - Width = (int)(Width * scale); - Height = (int)(Height * scale); - } - return this; - } - - /// - /// Scale the x/y position of this control. x/y * Scale - /// - /// - /// This control - public virtual Control ScaleXAndY(double scale) - { - if (scale != 1f) - { - X = (int)(X * scale); - Y = (int)(Y * scale); - } - return this; - } - - /// - /// Set the internal scale used for mouse interactions or other non visual scaling - /// - /// - /// This control - public virtual Control SetInternalScale(double scale) - { - InternalScale = scale; - return this; - } - - public void ForceSizeUpdate() - { - int h = Height, w = Width; - for (int i = 0; i < Children.Count; i++) - { - Control c = Children[i]; - if ((c.Page == 0 || c.Page == ActivePage) && c.IsVisible && !c.IsDisposed) - { - if (w < c.Bounds.Right) - { - w = c.Bounds.Right; - } - - if (h < c.Bounds.Bottom) - { - h = c.Bounds.Bottom; - } - } - } - - if (w != Width) - { - Width = w; - } - - if (h != Height) - { - Height = h; - } - - WantUpdateSize = false; - } - - public virtual void OnPageChanged() - { - //Update size as pages may vary in size. - if (ServerSerial != 0) - { - WantUpdateSize = true; - } - } - - private void DrawDebug(UltimaBatcher2D batcher, int x, int y) - { - if (IsVisible && CUOEnviroment.Debug) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - batcher.DrawRectangle - ( - SolidColorTextureCache.GetTexture(Color.Green), - x, - y, - Width, - Height, - hueVector - ); - } - } - - public void BringOnTop() - { - UIManager.MakeTopMostGump(this); - } - - public void SetTooltip(string text, int maxWidth = 0) - { - ClearTooltip(); - - if (!string.IsNullOrEmpty(text)) - { - Tooltip = text; - TooltipMaxLength = maxWidth; - } - } - - public void SetTooltip(uint entity) - { - ClearTooltip(); - Tooltip = entity; - } - - public void ClearTooltip() - { - Tooltip = null; - } - - public void SetKeyboardFocus() - { - if (AcceptKeyboardInput && !HasKeyboardFocus) - { - UIManager.KeyboardFocusControl = this; - } - } - - internal event EventHandler MouseDown, MouseUp, MouseOver, MouseEnter, MouseExit, DragBegin, DragEnd; - - internal event EventHandler MouseWheel; - - internal event EventHandler MouseDoubleClick; - - internal event EventHandler FocusEnter, FocusLost; - - internal event EventHandler KeyDown, KeyUp; - - internal event EventHandler ControllerButtonUp, ControllerButtonDown; - - - public void HitTest(int x, int y, ref Control res) - { - if (!IsVisible || !IsEnabled || IsDisposed) - { - return; - } - - int parentX = ParentX; - int parentY = ParentY; - - if (Bounds.Contains(x - parentX - _offset.X, y - parentY - _offset.Y)) - { - if (Contains(x - X - parentX, y - Y - parentY)) - { - if (AcceptMouseInput) - { - if (res == null || res.Priority >= Priority) - { - res = this; - OnHitTestSuccess(x, y, ref res); - } - } - - for (int i = 0; i < Children.Count; ++i) - { - Control c = Children[i]; - - if (c.Page == 0 || c.Page == ActivePage) - { - c.HitTest(x, y, ref res); - } - } - } - } - } - - public void HitTest(Point position, ref Control res) - { - HitTest(position.X, position.Y, ref res); - } - - public virtual void OnHitTestSuccess(int x, int y, ref Control res) - { - } - - public Control GetFirstControlAcceptKeyboardInput() - { - if (_acceptKeyboardInput) - { - return this; - } - - if (Children == null || Children.Count == 0) - { - return null; - } - - foreach (Control c in Children) - { - Control a = c.GetFirstControlAcceptKeyboardInput(); - - if (a != null) - { - return a; - } - } - - return null; - } - - public virtual void Add(Control c, int page = 0) - { - c.Page = page; - c.Parent = this; - OnChildAdded(); - } - - public void Insert(int index, Control c, int page = 0) - { - c.Page = 0; - - c._parent?.Children.Remove(c); - - c._parent = this; - - Children.Insert(index, c); - - OnChildAdded(); - } - - public virtual void Remove(Control c) - { - if (c == null) - { - return; - } - - c.Parent = null; - Children.Remove(c); - OnChildRemoved(); - } - - public virtual void Clear() - { - foreach (Control c in Children) - { - c.Dispose(); - } - } - - public T[] GetControls() where T : Control - { - return Children.OfType().Where(s => !s.IsDisposed).ToArray(); - } - - public IEnumerable FindControls() where T : Control - { - return Children.OfType().Where(s => !s.IsDisposed); - } - - - public void InvokeMouseDown(Point position, MouseButtonType button) - { - int x = position.X - X - ParentX; - int y = position.Y - Y - ParentY; - OnMouseDown(x, y, button); - MouseDown.Raise(new MouseEventArgs(x, y, button, ButtonState.Pressed), this); - } - - public void InvokeMouseUp(Point position, MouseButtonType button) - { - int x = position.X - X - ParentX; - int y = position.Y - Y - ParentY; - OnMouseUp(x, y, button); - MouseUp.Raise(new MouseEventArgs(x, y, button), this); - } - - public void InvokeMouseCloseGumpWithRClick() - { - if (CanCloseWithRightClick) - { - CloseWithRightClick(); - } - } - - public void InvokeMouseOver(Point position) - { - int x = position.X - X - ParentX; - int y = position.Y - Y - ParentY; - OnMouseOver(x, y); - MouseOver.Raise(new MouseEventArgs(x, y), this); - } - - public void InvokeMouseEnter(Point position) - { - int x = position.X - X - ParentX; - int y = position.Y - Y - ParentY; - OnMouseEnter(x, y); - MouseEnter.Raise(new MouseEventArgs(x, y), this); - } - - public void InvokeMouseExit(Point position) - { - int x = position.X - X - ParentX; - int y = position.Y - Y - ParentY; - OnMouseExit(x, y); - MouseExit.Raise(new MouseEventArgs(x, y), this); - } - - public bool InvokeMouseDoubleClick(Point position, MouseButtonType button) - { - int x = position.X - X - ParentX; - int y = position.Y - Y - ParentY; - bool result = OnMouseDoubleClick(x, y, button); - - MouseDoubleClickEventArgs arg = new MouseDoubleClickEventArgs(x, y, button); - MouseDoubleClick.Raise(arg, this); - result |= arg.Result; - - return result; - } - - public void InvokeTextInput(string c) - { - OnTextInput(c); - } - - public void InvokeKeyDown(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - OnKeyDown(key, mod); - KeyboardEventArgs arg = new KeyboardEventArgs(key, mod, KeyboardEventType.Down); - KeyDown?.Raise(arg); - } - - public void InvokeKeyUp(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - OnKeyUp(key, mod); - KeyboardEventArgs arg = new KeyboardEventArgs(key, mod, KeyboardEventType.Up); - KeyUp?.Raise(arg); - } - - public void InvokeControllerButtonUp(SDL.SDL_GameControllerButton button) { OnControllerButtonUp(button); ControllerButtonUp?.Raise(button); } - - public void InvokeControllerButtonDown(SDL.SDL_GameControllerButton button) { OnControllerButtonDown(button); ControllerButtonDown?.Raise(button); } - - public void InvokeMouseWheel(MouseEventType delta) - { - OnMouseWheel(delta); - MouseWheel.Raise(new MouseWheelEventArgs(delta), this); - } - - public void InvokeDragBegin(Point position) - { - int x = position.X - X - ParentX; - int y = position.Y - Y - ParentY; - OnDragBegin(x, y); - DragBegin.Raise(new MouseEventArgs(x, y, MouseButtonType.Left, ButtonState.Pressed), this); - } - - public void InvokeDragEnd(Point position) - { - int x = position.X - X - ParentX; - int y = position.Y - Y - ParentY; - OnDragEnd(x, y); - DragEnd.Raise(new MouseEventArgs(x, y, MouseButtonType.Left), this); - } - - public void InvokeMove(int x, int y) - { - x = x - X - ParentX; - y = y - Y - ParentY; - OnMove(x, y); - } - - protected virtual void OnMouseDown(int x, int y, MouseButtonType button) - { - Parent?.OnMouseDown(X + x, Y + y, button); - } - - protected virtual void OnMouseUp(int x, int y, MouseButtonType button) - { - Parent?.OnMouseUp(X + x, Y + y, button); - - if (button == MouseButtonType.Right && !IsDisposed && !CanCloseWithRightClick && !Keyboard.Alt && !Keyboard.Shift && !Keyboard.Ctrl) - { - ContextMenu?.Show(); - } - } - - protected virtual void OnMouseWheel(MouseEventType delta) - { - Parent?.OnMouseWheel(delta); - } - - protected virtual void OnMouseOver(int x, int y) - { - Parent?.OnMouseOver(X + x, Y + y); - } - - protected virtual void OnMouseEnter(int x, int y) - { - } - - protected virtual void OnMouseExit(int x, int y) - { - } - - protected virtual bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - return Parent?.OnMouseDoubleClick(X + x, Y + y, button) ?? false; - } - - protected virtual void OnDragBegin(int x, int y) - { - } - - protected virtual void OnDragEnd(int x, int y) - { - } - - protected virtual void OnTextInput(string c) - { - } - - protected virtual void OnKeyDown(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - Parent?.OnKeyDown(key, mod); - } - - protected virtual void OnKeyUp(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - Parent?.OnKeyUp(key, mod); - } - - protected virtual void OnControllerButtonUp(SDL.SDL_GameControllerButton button) { } - - protected virtual void OnControllerButtonDown(SDL.SDL_GameControllerButton button) { } - - public virtual bool Contains(int x, int y) - { - return !IsDisposed; - } - - protected virtual void OnMove(int x, int y) - { - } - - internal virtual void OnFocusEnter() - { - if (!IsFocused) - { - IsFocused = true; - FocusEnter.Raise(this); - //Parent?.OnFocusEnter(); - } - } - - internal virtual void OnFocusLost() - { - if (IsFocused) - { - IsFocused = false; - FocusLost.Raise(this); - //Parent?.OnFocusLeft(); - } - } - - protected virtual void OnChildAdded() - { - } - - protected virtual void OnChildRemoved() - { - } - - protected virtual void CloseWithRightClick() - { - if (!CanCloseWithRightClick) - { - return; - } - - Control parent = Parent; - - while (parent != null) - { - if (!parent.CanCloseWithRightClick) - { - return; - } - - parent = parent.Parent; - } - - if (Parent == null) - { - Dispose(); - } - else - { - Parent.CloseWithRightClick(); - } - } - - public void KeyboardTabToNextFocus(Control c) - { - int startIndex = Children.IndexOf(c); - - for (int i = startIndex + 1; i < Children.Count; i++) - { - if (Children[i].AcceptKeyboardInput) - { - Children[i].SetKeyboardFocus(); - - return; - } - } - - for (int i = 0; i < startIndex; i++) - { - if (Children[i].AcceptKeyboardInput) - { - Children[i].SetKeyboardFocus(); - - return; - } - } - } - - public virtual void OnButtonClick(int buttonID) - { - Parent?.OnButtonClick(buttonID); - } - - public virtual void OnKeyboardReturn(int textID, string text) - { - Parent?.OnKeyboardReturn(textID, text); - } - - public virtual void ChangePage(int pageIndex) - { - Parent?.ChangePage(pageIndex); - } - - public virtual void Dispose() - { - if (IsDisposed) - { - return; - } - - if (Children != null) - { - foreach (Control c in Children) - { - c.Dispose(); - } - - Children.Clear(); - } - - IsDisposed = true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/CroppedText.cs b/src/ClassicUO.Client/Game/UI/Controls/CroppedText.cs deleted file mode 100644 index 2de2e2aad..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/CroppedText.cs +++ /dev/null @@ -1,80 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Renderer; -using ClassicUO.Utility; - -namespace ClassicUO.Game.UI.Controls -{ - internal class CroppedText : Control - { - private readonly RenderedText _gameText; - - public CroppedText(string text, ushort hue, int maxWidth = 0) - { - _gameText = RenderedText.Create - ( - text, - hue, - (byte) (Client.Version >= ClientVersion.CV_305D ? 1 : 0), - true, - maxWidth > 0 ? FontStyle.BlackBorder | FontStyle.Cropped : FontStyle.BlackBorder, - maxWidth: maxWidth - ); - - AcceptMouseInput = false; - } - - public CroppedText(List parts, string[] lines) : this(int.TryParse(parts[6], out int lineIndex) && lineIndex >= 0 && lineIndex < lines.Length ? lines[lineIndex] : string.Empty, (ushort) (UInt16Converter.Parse(parts[5]) + 1), int.Parse(parts[3])) - { - X = int.Parse(parts[1]); - Y = int.Parse(parts[2]); - Width = int.Parse(parts[3]); - Height = int.Parse(parts[4]); - IsFromServer = true; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - _gameText.Draw(batcher, x, y); - - return base.Draw(batcher, x, y); - } - - public override void Dispose() - { - base.Dispose(); - _gameText?.Destroy(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/DataBox.cs b/src/ClassicUO.Client/Game/UI/Controls/DataBox.cs deleted file mode 100644 index 7af8b6bea..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/DataBox.cs +++ /dev/null @@ -1,92 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - - -namespace ClassicUO.Game.UI.Controls -{ - internal class DataBox : Control - { - public DataBox(int x, int y, int w, int h) - { - CanMove = false; - AcceptMouseInput = true; - X = x; - Y = y; - Width = w; - Height = h; - WantUpdateSize = false; - } - - public bool ContainsByBounds { get; set; } - - public void ReArrangeChildren() - { - for (int i = 0, height = 0; i < Children.Count; ++i) - { - Control c = Children[i]; - - if (c.IsVisible && !c.IsDisposed) - { - c.Y = height; - - height += c.Height; - } - } - - WantUpdateSize = true; - } - - public override bool Contains(int x, int y) - { - if (ContainsByBounds) - { - return true; - } - - Control t = null; - x += ScreenCoordinateX; - y += ScreenCoordinateY; - - foreach (Control child in Children) - { - child.HitTest(x, y, ref t); - - if (t != null) - { - return true; - } - } - - return false; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/ExpandableScroll.cs b/src/ClassicUO.Client/Game/UI/Controls/ExpandableScroll.cs deleted file mode 100644 index 88bb613c9..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ExpandableScroll.cs +++ /dev/null @@ -1,304 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Managers; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - internal class ExpandableScroll : Control - { - private const int c_ExpandableScrollHeight_Min = 274; - private const int c_ExpandableScrollHeight_Max = 800; - private const int c_GumplingExpanderY_Offset = 2; // this is the gap between the pixels of the btm Control texture and the height of the btm Control texture. - private const int c_GumplingExpander_ButtonID = 0x7FBEEF; - private readonly GumpPic _gumpBottom; - private Button _gumpExpander; - private GumpPic _gumplingTitle; - private int _gumplingTitleGumpID; - private bool _gumplingTitleGumpIDDelta; - private readonly GumpPicTiled _gumpMiddle; - private readonly GumpPicTiled _gumpRight; - private readonly GumpPic _gumpTop; - private bool _isExpanding; - private readonly bool _isResizable = true; - private Point _lastExpanderPosition; - - public ExpandableScroll(int x, int y, int height, ushort graphic, bool isResizable = true) - { - X = x; - Y = y; - SpecialHeight = height; - _isResizable = isResizable; - CanMove = true; - AcceptMouseInput = true; - - int width = 0; - - int w0 = 0, - w1 = 0, - w3 = 0; - - for (int i = 0; i < 4; i++) - { - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump((ushort)(graphic + i)); - - if (gumpInfo.Texture == null) - { - Dispose(); - - return; - } - - if (gumpInfo.UV.Width > width) - { - width = gumpInfo.UV.Width; - } - - if (i == 0) - { - w0 = gumpInfo.UV.Width; - } - else if (i == 1) - { - w1 = gumpInfo.UV.Width; - } - else if (i == 3) - { - w3 = gumpInfo.UV.Width; - } - } - - Add(_gumpTop = new GumpPic(0, 0, graphic, 0)); - - Add(_gumpRight = new GumpPicTiled(0, 0, 0, 0, (ushort)(graphic + 1))); - - Add(_gumpMiddle = new GumpPicTiled(0, 0, 0, 0, (ushort)(graphic + 2))); - - Add(_gumpBottom = new GumpPic(0, 0, (ushort)(graphic + 3), 0)); - - if (_isResizable) - { - Add( - _gumpExpander = new Button(c_GumplingExpander_ButtonID, 0x082E, 0x82F) - { - ButtonAction = ButtonAction.Activate, - X = 0, - Y = 0 - } - ); - - _gumpExpander.MouseDown += expander_OnMouseDown; - _gumpExpander.MouseUp += expander_OnMouseUp; - } - - int off = w0 - w3; - - _gumpRight.X = _gumpMiddle.X = (width - w1) / 2; - _gumpRight.Y = _gumpMiddle.Y = _gumplingMidY; - _gumpRight.Height = _gumpMiddle.Height = _gumplingMidHeight; - _gumpRight.WantUpdateSize = _gumpMiddle.WantUpdateSize = true; - _gumpBottom.X = (off / 2) + (off / 4); - - Width = _gumpMiddle.Width; - - WantUpdateSize = true; - } - - private int _gumplingMidY => _gumpTop.Height; - - private int _gumplingMidHeight => - SpecialHeight - _gumpTop.Height - _gumpBottom.Height - (_gumpExpander?.Height ?? 0); - - private int _gumplingBottomY => - SpecialHeight - _gumpBottom.Height - (_gumpExpander?.Height ?? 0); - - private int _gumplingExpanderX => (Width - (_gumpExpander?.Width ?? 0)) >> 1; - - private int _gumplingExpanderY => - SpecialHeight - (_gumpExpander?.Height ?? 0) - c_GumplingExpanderY_Offset; - - public int TitleGumpID - { - set - { - _gumplingTitleGumpID = value; - _gumplingTitleGumpIDDelta = true; - } - } - - public int SpecialHeight { get; set; } - - public ushort Hue - { - get => _gumpTop.Hue; - set => _gumpTop.Hue = _gumpBottom.Hue = _gumpMiddle.Hue = _gumpRight.Hue = value; - } - - public override void Dispose() - { - if (_gumpExpander != null) - { - _gumpExpander.MouseDown -= expander_OnMouseDown; - _gumpExpander.MouseUp -= expander_OnMouseUp; - _gumpExpander.Dispose(); - _gumpExpander = null; - } - - base.Dispose(); - } - - public override bool Contains(int x, int y) - { - x += ScreenCoordinateX; - y += ScreenCoordinateY; - - Control c = null; - - _gumpTop.HitTest(x, y, ref c); - - if (c != null) - { - return true; - } - - _gumpMiddle.HitTest(x, y, ref c); - - if (c != null) - { - return true; - } - - _gumpRight.HitTest(x, y, ref c); - - if (c != null) - { - return true; - } - - _gumpBottom.HitTest(x, y, ref c); - - if (c != null) - { - return true; - } - - _gumpExpander.HitTest(x, y, ref c); - - if (c != null) - { - return true; - } - - return false; - } - - public override void Update() - { - if (Mouse.LButtonPressed && _isExpanding) - { - SpecialHeight += Mouse.Position.Y - _lastExpanderPosition.Y; - _lastExpanderPosition = Mouse.Position; - } - - if (SpecialHeight < c_ExpandableScrollHeight_Min) - { - _lastExpanderPosition.Y += c_ExpandableScrollHeight_Min - SpecialHeight; - SpecialHeight = c_ExpandableScrollHeight_Min; - } - - if (SpecialHeight > c_ExpandableScrollHeight_Max) - { - _lastExpanderPosition.Y -= SpecialHeight - c_ExpandableScrollHeight_Max; - SpecialHeight = c_ExpandableScrollHeight_Max; - } - - if (_gumplingTitleGumpIDDelta) - { - _gumplingTitleGumpIDDelta = false; - - _gumplingTitle?.Dispose(); - Add(_gumplingTitle = new GumpPic(0, 0, (ushort)_gumplingTitleGumpID, 0)); - } - - //if (!IsVisible) - // IsVisible = true; - //TOP - _gumpTop.X = 0; - _gumpTop.Y = 0; - _gumpTop.WantUpdateSize = true; - //MIDDLE - _gumpRight.Y = _gumpMiddle.Y = _gumplingMidY; - _gumpRight.Height = _gumpMiddle.Height = _gumplingMidHeight; - _gumpRight.WantUpdateSize = _gumpMiddle.WantUpdateSize = true; - //BOTTOM - _gumpBottom.Y = _gumplingBottomY; - _gumpBottom.WantUpdateSize = true; - - if (_isResizable) - { - _gumpExpander.X = _gumplingExpanderX; - _gumpExpander.Y = _gumplingExpanderY; - _gumpExpander.WantUpdateSize = true; - } - - if (_gumplingTitle != null) - { - _gumplingTitle.X = (_gumpTop.Width - _gumplingTitle.Width) >> 1; - _gumplingTitle.Y = (_gumpTop.Height - _gumplingTitle.Height) >> 1; - _gumplingTitle.WantUpdateSize = true; - } - - WantUpdateSize = true; - Parent?.OnPageChanged(); - - base.Update(); - } - - private void expander_OnMouseDown(object sender, MouseEventArgs args) - { - if (args.Button == MouseButtonType.Left) - { - _isExpanding = true; - _lastExpanderPosition = Mouse.Position; - } - } - - private void expander_OnMouseUp(object sender, MouseEventArgs args) - { - _isExpanding = false; - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/FadingLabel.cs b/src/ClassicUO.Client/Game/UI/Controls/FadingLabel.cs deleted file mode 100644 index e47bd1389..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/FadingLabel.cs +++ /dev/null @@ -1,33 +0,0 @@ -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - internal class FadingLabel : Label - { - private readonly int tickSpeed; - private int c = 0; - - public FadingLabel(int tickSpeed, string text, bool isunicode, ushort hue, int maxwidth = 0, byte font = 255, FontStyle style = FontStyle.None, TEXT_ALIGN_TYPE align = TEXT_ALIGN_TYPE.TS_LEFT, bool ishtml = false) : base(text, isunicode, hue, maxwidth, font, style, align, ishtml) - { - this.tickSpeed = tickSpeed; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (c >= tickSpeed) - Alpha -= 0.01f; - if (Alpha <= 0f) - Dispose(); - c++; - - batcher.Draw(SolidColorTextureCache.GetTexture(Color.Green), - new Rectangle(x, y, Width, Height), - new Vector3(1, 0, Alpha) - ); - - return base.Draw(batcher, x, y); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/GumpControlInfo.cs b/src/ClassicUO.Client/Game/UI/Controls/GumpControlInfo.cs deleted file mode 100644 index 1f8e13fbc..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/GumpControlInfo.cs +++ /dev/null @@ -1,41 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.UI.Controls -{ - public enum UILayer - { - Over, - Default, - Under - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/GumpLockButton.cs b/src/ClassicUO.Client/Game/UI/Controls/GumpLockButton.cs deleted file mode 100644 index 3aa85d8f8..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/GumpLockButton.cs +++ /dev/null @@ -1,66 +0,0 @@ -using ClassicUO.Game.Managers; -using ClassicUO.Input; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using System.Xml.Linq; - -namespace ClassicUO.Game.UI.Controls -{ - internal class GumpLockButton : Control - { - private bool isLocked; - - private Rectangle lockIconBounds; - private Texture2D lockIcon; - Vector3 hueLocked = Renderer.ShaderHueTranslator.GetHueVector(32); - Vector3 hueUnlocked = Renderer.ShaderHueTranslator.GetHueVector(0); - - public GumpLockButton(ref bool isLocked) - { - this.isLocked = isLocked; - - ref readonly var ginfo = ref Client.Game.Gumps.GetGump(0x82C); - lockIcon = ginfo.Texture; - lockIconBounds = ginfo.UV; - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - base.OnMouseUp(x, y, button); - - if (button == MouseButtonType.Left && Keyboard.Alt && UIManager.MouseOverControl != null && (UIManager.MouseOverControl == this || UIManager.MouseOverControl.RootParent == this)) - { - if (lockIcon != null) - { - if (x >= 0 && x < lockIconBounds.Width && y >= 0 && y <= lockIconBounds.Height) - { - isLocked ^= true; - if (isLocked) - { - CanMove = false; - CanCloseWithRightClick = false; - } - else - { - CanMove = true; - CanCloseWithRightClick = true; - } - } - } - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - if (lockIcon != null && Keyboard.Alt && UIManager.MouseOverControl != null && (UIManager.MouseOverControl == this || UIManager.MouseOverControl.RootParent == this)) - { - batcher.Draw(lockIcon, new Vector2(x, y), lockIconBounds, isLocked ? hueLocked : hueUnlocked); - } - - return true; - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/GumpPic.cs b/src/ClassicUO.Client/Game/UI/Controls/GumpPic.cs deleted file mode 100644 index 3f9d69676..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/GumpPic.cs +++ /dev/null @@ -1,269 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Input; -using ClassicUO.Network; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - public abstract class GumpPicBase : Control - { - private ushort _graphic; - - protected GumpPicBase() - { - CanMove = true; - AcceptMouseInput = true; - } - - public ushort Graphic - { - get => _graphic; - set - { - _graphic = value; - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(_graphic); - - if (gumpInfo.Texture == null) - { - Dispose(); - - return; - } - - Width = gumpInfo.UV.Width; - Height = gumpInfo.UV.Height; - } - } - - public ushort Hue { get; set; } - - public override bool Contains(int x, int y) - { - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(_graphic); - - if (gumpInfo.Texture == null) - { - return false; - } - - if (Client.Game.Gumps.PixelCheck(Graphic, x - Offset.X, y - Offset.Y, InternalScale)) - { - return true; - } - - for (int i = 0; i < Children.Count; i++) - { - Control c = Children[i]; - - // might be wrong x, y. They should be calculated by position - if (c.Contains(x, y)) - { - return true; - } - } - - return false; - } - } - - internal class GumpPic : GumpPicBase - { - public GumpPic(int x, int y, ushort graphic, ushort hue) - { - X = x; - Y = y; - Graphic = graphic; - Hue = hue; - IsFromServer = true; - } - - public GumpPic(List parts) - : this( - int.Parse(parts[1]), - int.Parse(parts[2]), - UInt16Converter.Parse(parts[3]), - (ushort)( - parts.Count > 4 - ? TransformHue( - (ushort)( - UInt16Converter.Parse(parts[4].Substring(parts[4].IndexOf('=') + 1)) - + 1 - ) - ) - : 0 - ) - ) - { } - - public bool IsPartialHue { get; set; } - public bool ContainsByBounds { get; set; } - public bool IsVirtue { get; set; } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if (IsVirtue && button == MouseButtonType.Left) - { - NetClient.Socket.Send_VirtueGumpResponse(World.Player, Graphic); - - return true; - } - - return base.OnMouseDoubleClick(x, y, button); - } - - public override bool Contains(int x, int y) - { - return ContainsByBounds || base.Contains(x, y); - } - - private static ushort TransformHue(ushort hue) - { - if (hue <= 2) - { - hue = 0; - } - - //if (hue < 2) - // hue = 1; - return hue; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsDisposed) - { - return false; - } - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(Hue, IsPartialHue, Alpha, true); - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(Graphic); - - if (gumpInfo.Texture != null) - { - batcher.Draw( - gumpInfo.Texture, - new Rectangle(x, y, (int)(Width * Scale), (int)(Height * Scale)), - gumpInfo.UV, - hueVector - ); - } - - return base.Draw(batcher, x, y); - } - } - - internal class GumpPicInPic : GumpPicBase - { - private Rectangle _picInPicBounds; - - public Vector2 DrawOffset { get; set; } = Vector2.Zero; - - public Rectangle PicInPicBounds - { - get => _picInPicBounds; set - { - _picInPicBounds = value; - Width = _picInPicBounds.Width; - Height = _picInPicBounds.Height; - } - } - - public GumpPicInPic( - int x, - int y, - ushort graphic, - ushort sx, - ushort sy, - ushort width, - ushort height - ) - { - X = x; - Y = y; - Graphic = graphic; - Width = width; - Height = height; - _picInPicBounds = new Rectangle(sx, sy, Width, Height); - IsFromServer = true; - } - - public GumpPicInPic(List parts) - : this( - int.Parse(parts[1]), - int.Parse(parts[2]), - UInt16Converter.Parse(parts[3]), - UInt16Converter.Parse(parts[4]), - UInt16Converter.Parse(parts[5]), - UInt16Converter.Parse(parts[6]), - UInt16Converter.Parse(parts[7]) - ) - { } - - public override bool Contains(int x, int y) - { - return true; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsDisposed) - { - return false; - } - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(Hue, false, Alpha, true); - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(Graphic); - - var sourceBounds = new Rectangle(gumpInfo.UV.X + _picInPicBounds.X, gumpInfo.UV.Y + _picInPicBounds.Y, _picInPicBounds.Width, _picInPicBounds.Height); - - if (gumpInfo.Texture != null) - { - batcher.Draw( - gumpInfo.Texture, - new Rectangle((int)(x + DrawOffset.X), (int)(y + DrawOffset.Y), (int)(Width * Scale), (int)(Height * Scale)), - sourceBounds, - hueVector - ); - } - - return base.Draw(batcher, x, y); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/GumpPicExternalUrl.cs b/src/ClassicUO.Client/Game/UI/Controls/GumpPicExternalUrl.cs deleted file mode 100644 index b83d846cc..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/GumpPicExternalUrl.cs +++ /dev/null @@ -1,112 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using System; -using System.IO; -using System.Net.Http; -using System.Threading.Tasks; - -namespace ClassicUO.Game.UI.Controls -{ - public class GumpPicExternalUrl : Control - { - public GumpPicExternalUrl(int x, int y, string imgUrl, ushort hue, int width, int height, bool resize = false) - { - Width = width; - Height = height; - X = x; Y = y; - ImgUrl = imgUrl; - Hue = hue; - Resize = resize; - getImageTexture(); - AcceptMouseInput = true; - CanMove = true; - } - - public string ImgUrl { get; } - public ushort Hue { get; } - public bool Resize { get; } - public Texture2D imageTexture { get; private set; } - - private void getImageTexture() - { - Task.Factory.StartNew(() => - { - try - { - using (HttpClient httpClient = new HttpClient()) - using (Stream stream = httpClient.GetStreamAsync(ImgUrl).Result) - { - using (System.Drawing.Image image = System.Drawing.Image.FromStream(stream)) - { - Console.WriteLine($"Image size {image.Width} x {image.Height}"); - - var memStream = new MemoryStream(); - image.Save(memStream, System.Drawing.Imaging.ImageFormat.Png); - - using (memStream) - { - var t = Texture2D.FromStream(Client.Game.GraphicsDevice, memStream); - //Color[] buffer = new Color[t.Width * t.Height]; - //t.GetData(buffer); - //for (int i = 0; i < buffer.Length; i++) - // buffer[i] = Color.FromNonPremultiplied(buffer[i].R, buffer[i].G, buffer[i].B, buffer[i].A); - //t.SetData(buffer); - imageTexture = t; - } - } - - } - } - catch { } - }); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(Hue); - - if (imageTexture != null) - { - if (!Resize) - batcher.DrawTiled(imageTexture, new Rectangle(x, y, Width, Height), imageTexture.Bounds, hueVector); - else - batcher.Draw(imageTexture, new Rectangle(x, y, Width, Height), imageTexture.Bounds, hueVector); - } - - return base.Draw(batcher, x, y);; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/GumpPicTiled.cs b/src/ClassicUO.Client/Game/UI/Controls/GumpPicTiled.cs deleted file mode 100644 index 06b2e9768..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/GumpPicTiled.cs +++ /dev/null @@ -1,167 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - public class GumpPicTiled : Control - { - private ushort _graphic; - - public GumpPicTiled(ushort graphic) - { - CanMove = true; - AcceptMouseInput = true; - Graphic = graphic; - } - - public GumpPicTiled(int x, int y, int width, int heigth, ushort graphic) : this(graphic) - { - X = x; - Y = y; - - if (width > 0) - { - Width = width; - } - - if (heigth > 0) - { - Height = heigth; - } - } - - public GumpPicTiled(List parts) : this(UInt16Converter.Parse(parts[5])) - { - X = int.Parse(parts[1]); - Y = int.Parse(parts[2]); - Width = int.Parse(parts[3]); - Height = int.Parse(parts[4]); - IsFromServer = true; - } - - public ushort Graphic - { - get => _graphic; - set - { - if (_graphic != value && value != 0xFFFF) - { - _graphic = value; - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(_graphic); - - if (gumpInfo.Texture == null) - { - Dispose(); - - return; - } - - Width = gumpInfo.UV.Width; - Height = gumpInfo.UV.Height; - } - } - } - - public ushort Hue { get; set; } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(Hue, false, Alpha, true); - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(Graphic); - - if (gumpInfo.Texture != null) - { - batcher.DrawTiled( - gumpInfo.Texture, - new Rectangle(x, y, Width, Height), - gumpInfo.UV, - hueVector - ); - } - - return base.Draw(batcher, x, y); - } - - public override bool Contains(int x, int y) - { - int width = Width; - int height = Height; - - x -= Offset.X; - y -= Offset.Y; - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(Graphic); - - if (gumpInfo.Texture == null) - { - return false; - } - - if (width == 0) - { - width = gumpInfo.UV.Width; - } - - if (height == 0) - { - height = gumpInfo.UV.Height; - } - - while (x > gumpInfo.UV.Width && width > gumpInfo.UV.Width) - { - x -= gumpInfo.UV.Width; - width -= gumpInfo.UV.Width; - } - - while (y > gumpInfo.UV.Height && height > gumpInfo.UV.Height) - { - y -= gumpInfo.UV.Height; - height -= gumpInfo.UV.Height; - } - - if (x > width || y > height) - { - return false; - } - - return Client.Game.Gumps.PixelCheck(Graphic, x, y); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/GumpPicWithWidth.cs b/src/ClassicUO.Client/Game/UI/Controls/GumpPicWithWidth.cs deleted file mode 100644 index 11d646770..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/GumpPicWithWidth.cs +++ /dev/null @@ -1,72 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - internal class GumpPicWithWidth : GumpPic - { - public GumpPicWithWidth(int x, int y, ushort graphic, ushort hue, int perc) - : base(x, y, graphic, hue) - { - Percent = perc; - CanMove = true; - //AcceptMouseInput = false; - } - - public int Percent { get; set; } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(Hue); - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(Graphic); - - if (gumpInfo.Texture != null) - { - batcher.DrawTiled( - gumpInfo.Texture, - new Rectangle(x, y, Percent, Height), - gumpInfo.UV, - hueVector - ); - - return true; - } - - return false; - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/HSliderBar.cs b/src/ClassicUO.Client/Game/UI/Controls/HSliderBar.cs deleted file mode 100644 index f13b446ad..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/HSliderBar.cs +++ /dev/null @@ -1,402 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - internal enum HSliderBarStyle - { - MetalWidgetRecessedBar, - BlueWidgetNoBar - } - - internal class HSliderBar : Control - { - private bool _clicked; - private readonly bool _drawUp; - private readonly List _pairedSliders = new List(); - private int _sliderX; - private readonly HSliderBarStyle _style; - private readonly RenderedText _text; - private int _value = -1; - - public HSliderBar( - int x, - int y, - int w, - int min, - int max, - int value, - HSliderBarStyle style, - bool hasText = false, - byte font = 0, - ushort color = 0, - bool unicode = true, - bool drawUp = false - ) - { - X = x; - Y = y; - - if (hasText) - { - _text = RenderedText.Create(string.Empty, color, font, unicode); - _drawUp = drawUp; - } - - MinValue = min; - MaxValue = max; - BarWidth = w; - _style = style; - AcceptMouseInput = true; - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump( - (uint)(_style == HSliderBarStyle.MetalWidgetRecessedBar ? 216 : 0x845) - ); - - Width = BarWidth; - - if (gumpInfo.Texture != null) - { - Height = gumpInfo.UV.Height; - } - - CalculateOffset(); - - Value = value; - } - - public int MinValue { get; set; } - - public int MaxValue { get; set; } - - public int BarWidth { get; set; } - - public float Percents { get; private set; } - - public int Value - { - get => _value; - set - { - if (_value != value) - { - int oldValue = _value; - _value = /*_newValue =*/ - value; - //if (IsInitialized) - // RecalculateSliderX(); - - if (_value < MinValue) - { - _value = MinValue; - } - else if (_value > MaxValue) - { - _value = MaxValue; - } - - if (_text != null) - { - _text.Text = Value.ToString(); - } - - if (_value != oldValue) - { - ModifyPairedValues(_value - oldValue); - - CalculateOffset(); - } - - ValueChanged.Raise(); - } - } - } - - public event EventHandler ValueChanged; - - public override void Update() - { - base.Update(); - - if (_clicked) - { - int x = Mouse.Position.X - X - ParentX; - int y = Mouse.Position.Y - Y - ParentY; - - CalculateNew(x); - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - if (_style == HSliderBarStyle.MetalWidgetRecessedBar) - { - ref readonly var gumpInfo0 = ref Client.Game.Gumps.GetGump(213); - ref readonly var gumpInfo1 = ref Client.Game.Gumps.GetGump(214); - ref readonly var gumpInfo2 = ref Client.Game.Gumps.GetGump(215); - ref readonly var gumpInfo3 = ref Client.Game.Gumps.GetGump(216); - - batcher.Draw(gumpInfo0.Texture, new Vector2(x, y), gumpInfo0.UV, hueVector); - - batcher.DrawTiled( - gumpInfo1.Texture, - new Rectangle( - x + gumpInfo0.UV.Width, - y, - BarWidth - gumpInfo2.UV.Width - gumpInfo0.UV.Width, - gumpInfo1.UV.Height - ), - gumpInfo1.UV, - hueVector - ); - - batcher.Draw( - gumpInfo2.Texture, - new Vector2(x + BarWidth - gumpInfo2.UV.Width, y), - gumpInfo2.UV, - hueVector - ); - - batcher.Draw( - gumpInfo3.Texture, - new Vector2(x + _sliderX, y), - gumpInfo3.UV, - hueVector - ); - } - else - { - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(idx: 0x845); - - batcher.Draw( - gumpInfo.Texture, - new Vector2(x + _sliderX, y), - gumpInfo.UV, - hueVector - ); - } - - if (_text != null) - { - if (_drawUp) - { - _text.Draw(batcher, x, y - _text.Height); - } - else - { - _text.Draw(batcher, x + BarWidth + 2, y + (Height >> 1) - (_text.Height >> 1)); - } - } - - return base.Draw(batcher, x, y); - } - - private void InternalSetValue(int value) - { - _value = value; - CalculateOffset(); - - if (_text != null) - { - _text.Text = Value.ToString(); - } - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - if (button != MouseButtonType.Left) - { - return; - } - - _clicked = true; - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button != MouseButtonType.Left) - { - return; - } - - _clicked = false; - CalculateNew(x); - } - - protected override void OnMouseWheel(MouseEventType delta) - { - switch (delta) - { - case MouseEventType.WheelScrollUp: - Value++; - - break; - - case MouseEventType.WheelScrollDown: - Value--; - - break; - } - - CalculateOffset(); - } - - private void CalculateNew(int x) - { - int len = BarWidth; - int maxValue = MaxValue - MinValue; - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump( - (uint)(_style == HSliderBarStyle.MetalWidgetRecessedBar ? 216 : 0x845) - ); - - len -= gumpInfo.UV.Width; - float perc = x / (float)len * 100.0f; - Value = (int)(maxValue * perc / 100.0f) + MinValue; - CalculateOffset(); - } - - private void CalculateOffset() - { - if (Value < MinValue) - { - Value = MinValue; - } - else if (Value > MaxValue) - { - Value = MaxValue; - } - - int value = Value - MinValue; - int maxValue = MaxValue - MinValue; - int length = BarWidth; - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump( - (uint)(_style == HSliderBarStyle.MetalWidgetRecessedBar ? 216 : 0x845) - ); - length -= gumpInfo.UV.Width; - - if (maxValue > 0) - { - Percents = value / (float)maxValue * 100.0f; - } - else - { - Percents = 0; - } - - _sliderX = (int)(length * Percents / 100.0f); - - if (_sliderX < 0) - { - _sliderX = 0; - } - } - - public void AddParisSlider(HSliderBar s) - { - _pairedSliders.Add(s); - } - - private void ModifyPairedValues(int delta) - { - if (_pairedSliders.Count == 0) - { - return; - } - - bool updateSinceLastCycle = true; - int d = delta > 0 ? -1 : 1; - int points = Math.Abs(delta); - int sliderIndex = Value % _pairedSliders.Count; - - while (points > 0) - { - if (d > 0) - { - if (_pairedSliders[sliderIndex].Value < _pairedSliders[sliderIndex].MaxValue) - { - updateSinceLastCycle = true; - - _pairedSliders[sliderIndex].InternalSetValue( - _pairedSliders[sliderIndex].Value + d - ); - - points--; - } - } - else - { - if (_pairedSliders[sliderIndex].Value > _pairedSliders[sliderIndex].MinValue) - { - updateSinceLastCycle = true; - - _pairedSliders[sliderIndex].InternalSetValue( - _pairedSliders[sliderIndex]._value + d - ); - - points--; - } - } - - sliderIndex++; - - if (sliderIndex == _pairedSliders.Count) - { - if (!updateSinceLastCycle) - { - return; - } - - updateSinceLastCycle = false; - sliderIndex = 0; - } - } - } - - public override void Dispose() - { - _text?.Destroy(); - base.Dispose(); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/HitBox.cs b/src/ClassicUO.Client/Game/UI/Controls/HitBox.cs deleted file mode 100644 index 53ad15f38..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/HitBox.cs +++ /dev/null @@ -1,99 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.UI.Controls -{ - public class HitBox : Control - { - public HitBox - ( - int x, - int y, - int w, - int h, - string tooltip = null, - float alpha = 0.25f - ) - { - CanMove = false; - AcceptMouseInput = true; - Alpha = alpha; - _texture = SolidColorTextureCache.GetTexture(Color.White); - - X = x; - Y = y; - Width = w; - Height = h; - WantUpdateSize = false; - - SetTooltip(tooltip); - } - - - public override ClickPriority Priority { get; set; } = ClickPriority.High; - protected readonly Texture2D _texture; - - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsDisposed) - { - return false; - } - - if (MouseIsOver) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector - ( - 0, - false, - Alpha, - true - ); - - batcher.Draw - ( - _texture, - new Vector2(x, y), - new Rectangle(0, 0, Width, Height), - hueVector - ); - } - - return base.Draw(batcher, x, y); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/HorizontalScrollArea.cs b/src/ClassicUO.Client/Game/UI/Controls/HorizontalScrollArea.cs deleted file mode 100644 index 7401732ec..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/HorizontalScrollArea.cs +++ /dev/null @@ -1,88 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.UI.Controls -{ - //class HorizontalScrollArea : Control - //{ - // private Rectangle _rect; - - // public HorizontalScrollArea(int x, int y, int w, int h) - // { - // X = x; - // Y = y; - // Width = w; - // Height = h; - - // AcceptMouseInput = true; - // WantUpdateSize = false; - // CanMove = true; - - - // HSliderBar bar = new HSliderBar(0, 0, w, 0, 100, 0, HSliderBarStyle.BlueWidgetNoBar) - // { - // Parent = this - // }; - // } - - - // public override void Update() - // { - // base.Update(); - // } - - // public override bool Draw(Batcher2D batcher, Point position, Vector3? hue = null) - // { - // Children[0].Draw(batcher, new Point(position.X + Children[0].X, position.Y + Children[0].Y)); - // _rect.X = position.X; - // _rect.Y = position.Y; - // _rect.Width = Width; - // _rect.Height = Height; - - // Rectangle scissor = ScissorStack.CalculateScissors(batcher.TransformMatrix, _rect); - - // if (ScissorStack.PushScissors(scissor)) - // { - // batcher.EnableScissorTest(true); - - // int width = 0; - // int maxWidth = - - - // batcher.EnableScissorTest(false); - // ScissorStack.PopScissors(); - // } - - // return true; - // } - //} -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/HotkeyBox.cs b/src/ClassicUO.Client/Game/UI/Controls/HotkeyBox.cs deleted file mode 100644 index 9dbb5bdff..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/HotkeyBox.cs +++ /dev/null @@ -1,323 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using SDL2; - -namespace ClassicUO.Game.UI.Controls -{ - internal class HotkeyBox : Control - { - private bool _actived; - private readonly Button _buttonOK, _buttonCancel; - private readonly HoveredLabel _label; - - public HotkeyBox() - { - CanMove = false; - AcceptMouseInput = true; - AcceptKeyboardInput = true; - - - Width = 210; - Height = 25; - - ResizePic pic; - - Add - ( - pic = new ResizePic(0x0BB8) - { - Width = 150, - Height = Height, - AcceptKeyboardInput = true - } - ); - - pic.MouseUp += LabelOnMouseUp; - - Add - ( - _label = new HoveredLabel - ( - string.Empty, - true, - 1, - 0x0021, - 0x0021, - 150, - 1, - FontStyle.None, - TEXT_ALIGN_TYPE.TS_CENTER - ) - { - Y = 5 - } - ); - - - _label.MouseUp += LabelOnMouseUp; - - Add - ( - _buttonOK = new Button((int) ButtonState.Ok, 0x0481, 0x0483, 0x0482) - { - X = 152, - ButtonAction = ButtonAction.Activate - } - ); - - - Add - ( - _buttonCancel = new Button((int) ButtonState.Cancel, 0x047E, 0x0480, 0x047F) - { - X = 182, - ButtonAction = ButtonAction.Activate - } - ); - - WantUpdateSize = false; - IsActive = false; - } - - public SDL.SDL_Keycode Key { get; private set; } - public SDL.SDL_GameControllerButton[] Buttons { get; private set; } - public MouseButtonType MouseButton { get; private set; } - public bool WheelScroll { get; private set; } - public bool WheelUp { get; private set; } - public SDL.SDL_Keymod Mod { get; private set; } - - public bool IsActive - { - get => _actived; - set - { - _actived = value; - - if (value) - { - _buttonOK.IsVisible = _buttonCancel.IsVisible = true; - _buttonOK.IsEnabled = _buttonCancel.IsEnabled = true; - } - else - { - _buttonOK.IsVisible = _buttonCancel.IsVisible = false; - _buttonOK.IsEnabled = _buttonCancel.IsEnabled = false; - } - } - } - - public event EventHandler HotkeyChanged, HotkeyCancelled; - - - protected override void OnControllerButtonDown(SDL.SDL_GameControllerButton button) - { - if(IsActive) - { - SetButtons(Controller.PressedButtons()); - } - } - - protected override void OnKeyDown(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - if (IsActive) - { - SetKey(key, mod); - } - } - - public void SetButtons(SDL.SDL_GameControllerButton[] buttons) - { - ResetBinding(); - Buttons = buttons; - _label.Text = Controller.GetButtonNames(buttons); - } - - public void SetKey(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - if (key == SDL.SDL_Keycode.SDLK_UNKNOWN && mod == SDL.SDL_Keymod.KMOD_NONE) - { - ResetBinding(); - - Key = key; - Mod = mod; - } - else - { - string newvalue = KeysTranslator.TryGetKey(key, mod); - - if (!string.IsNullOrEmpty(newvalue) && key != SDL.SDL_Keycode.SDLK_UNKNOWN) - { - ResetBinding(); - - Key = key; - Mod = mod; - _label.Text = newvalue; - } - } - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Middle || button == MouseButtonType.XButton1 || button == MouseButtonType.XButton2) - { - SDL.SDL_Keymod mod = SDL.SDL_Keymod.KMOD_NONE; - - if (Keyboard.Alt) - { - mod |= SDL.SDL_Keymod.KMOD_ALT; - } - - if (Keyboard.Shift) - { - mod |= SDL.SDL_Keymod.KMOD_SHIFT; - } - - if (Keyboard.Ctrl) - { - mod |= SDL.SDL_Keymod.KMOD_CTRL; - } - - SetMouseButton(button, mod); - } - } - - public void SetMouseButton(MouseButtonType button, SDL.SDL_Keymod mod) - { - string newvalue = KeysTranslator.GetMouseButton(button, mod); - - if (!string.IsNullOrEmpty(newvalue) && button != MouseButtonType.None) - { - ResetBinding(); - - MouseButton = button; - Mod = mod; - _label.Text = newvalue; - } - } - - protected override void OnMouseWheel(MouseEventType delta) - { - SDL.SDL_Keymod mod = SDL.SDL_Keymod.KMOD_NONE; - - if (Keyboard.Alt) - { - mod |= SDL.SDL_Keymod.KMOD_ALT; - } - - if (Keyboard.Shift) - { - mod |= SDL.SDL_Keymod.KMOD_SHIFT; - } - - if (Keyboard.Ctrl) - { - mod |= SDL.SDL_Keymod.KMOD_CTRL; - } - - if (delta == MouseEventType.WheelScrollUp) - { - SetMouseWheel(true, mod); - } - else if (delta == MouseEventType.WheelScrollDown) - { - SetMouseWheel(false, mod); - } - } - - public void SetMouseWheel(bool wheelUp, SDL.SDL_Keymod mod) - { - string newvalue = KeysTranslator.GetMouseWheel(wheelUp, mod); - - if (!string.IsNullOrEmpty(newvalue)) - { - ResetBinding(); - - WheelScroll = true; - WheelUp = wheelUp; - Mod = mod; - _label.Text = newvalue; - } - } - - private void ResetBinding() - { - Key = 0; - MouseButton = MouseButtonType.None; - WheelScroll = false; - Mod = 0; - _label.Text = string.Empty; - Buttons = null; - } - - private void LabelOnMouseUp(object sender, MouseEventArgs e) - { - IsActive = true; - SetKeyboardFocus(); - } - - - public override void OnButtonClick(int buttonID) - { - switch ((ButtonState) buttonID) - { - case ButtonState.Ok: - HotkeyChanged.Raise(this); - - break; - - case ButtonState.Cancel: - _label.Text = string.Empty; - - HotkeyCancelled.Raise(this); - - Key = SDL.SDL_Keycode.SDLK_UNKNOWN; - Mod = SDL.SDL_Keymod.KMOD_NONE; - - break; - } - - IsActive = false; - } - - private enum ButtonState - { - Ok, - Cancel - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/HotkeyControl.cs b/src/ClassicUO.Client/Game/UI/Controls/HotkeyControl.cs deleted file mode 100644 index 4c3ff4375..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/HotkeyControl.cs +++ /dev/null @@ -1,116 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Resources; - -namespace ClassicUO.Game.UI.Controls -{ - internal class HotkeyControl : Control - { - private readonly List _hotkesBoxes = new List(); - private readonly HotkeyAction _key; - - public HotkeyControl(string text, HotkeyAction key) - { - _key = key; - CanMove = true; - AcceptMouseInput = true; - - Add - ( - new Label - ( - text, - true, - 0, - 150, - 1 - ) - ); - - AddNew(key); - } - - - public void AddNew(HotkeyAction action) - { - HotkeyBox box = new HotkeyBox - { - X = 150 - }; - - box.HotkeyChanged += (sender, e) => - { - GameScene gs = Client.Game.GetScene(); - - if (gs == null) - { - return; - } - - if (gs.Hotkeys.Bind(_key, box.Key, box.Mod)) - { - } - else // show a popup - { - UIManager.Add(new MessageBoxGump(400, 200, ResGumps.KeyCombinationAlreadyExists, null)); - } - }; - - box.HotkeyCancelled += (sender, e) => - { - GameScene gs = Client.Game.GetScene(); - - if (gs == null) - { - return; - } - - gs.Hotkeys.UnBind(_key); - }; - - if (_hotkesBoxes.Count != 0) - { - box.Y = _hotkesBoxes[_hotkesBoxes.Count - 1].Bounds.Bottom; - } - - - _hotkesBoxes.Add(box); - - Add(box); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/HoveredLabel.cs b/src/ClassicUO.Client/Game/UI/Controls/HoveredLabel.cs deleted file mode 100644 index bd8ffa651..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/HoveredLabel.cs +++ /dev/null @@ -1,122 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - internal class HoveredLabel : Label - { - private readonly ushort _overHue, _normalHue, _selectedHue; - - public HoveredLabel - ( - string text, - bool isunicode, - ushort hue, - ushort overHue, - ushort selectedHue, - int maxwidth = 0, - byte font = 255, - FontStyle style = FontStyle.None, - TEXT_ALIGN_TYPE align = TEXT_ALIGN_TYPE.TS_LEFT - ) : base - ( - $" {text}", - isunicode, - hue, - maxwidth, - font, - style, - align - ) - { - _overHue = overHue; - _normalHue = hue; - _selectedHue = selectedHue; - AcceptMouseInput = true; - } - - public bool DrawBackgroundCurrentIndex; - public bool IsSelected, ForceHover; - - public override void Update() - { - if (IsSelected) - { - if (Hue != _selectedHue) - { - Hue = _selectedHue; - } - } - else if (MouseIsOver || ForceHover) - { - if (Hue != _overHue) - { - Hue = _overHue; - } - } - else if (Hue != _normalHue) - { - Hue = _normalHue; - } - - - base.Update(); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (DrawBackgroundCurrentIndex && MouseIsOver && !string.IsNullOrWhiteSpace(Text)) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - batcher.Draw - ( - SolidColorTextureCache.GetTexture(Color.Gray), - new Rectangle - ( - x, - y + 2, - Width - 4, - Height - 4 - ), - hueVector - ); - } - - return base.Draw(batcher, x, y); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/HtmlControl.cs b/src/ClassicUO.Client/Game/UI/Controls/HtmlControl.cs deleted file mode 100644 index 71f505be2..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/HtmlControl.cs +++ /dev/null @@ -1,330 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using ClassicUO.Utility.Platforms; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - internal class HtmlControl : Control - { - private RenderedText _gameText; - private ScrollBarBase _scrollBar; - - public HtmlControl(List parts, string[] lines) : this() - { - X = int.Parse(parts[1]); - Y = int.Parse(parts[2]); - Width = int.Parse(parts[3]); - Height = int.Parse(parts[4]); - int textIndex = int.Parse(parts[5]); - HasBackground = parts[6] == "1"; - HasScrollbar = parts[7] != "0"; - UseFlagScrollbar = HasScrollbar && parts[7] == "2"; - _gameText.IsHTML = true; - _gameText.MaxWidth = Width - (HasScrollbar ? 16 : 0) - (HasBackground ? 8 : 0); - IsFromServer = true; - - if (textIndex >= 0 && textIndex < lines.Length) - { - InternalBuild(lines[textIndex], 0); - } - } - - public HtmlControl - ( - int x, - int y, - int w, - int h, - bool hasbackground, - bool hasscrollbar, - bool useflagscrollbar = false, - string text = "", - int hue = 0, - bool ishtml = false, - byte font = 1, - bool isunicode = true, - FontStyle style = FontStyle.None, - TEXT_ALIGN_TYPE align = TEXT_ALIGN_TYPE.TS_LEFT - ) : this() - { - X = x; - Y = y; - Width = w; - Height = h; - HasBackground = hasbackground; - HasScrollbar = hasscrollbar; - UseFlagScrollbar = useflagscrollbar; //hasscrollbar != 0 && hasscrollbar == 2; - - if (!string.IsNullOrEmpty(text)) - { - _gameText.IsHTML = ishtml; - _gameText.FontStyle = style; - _gameText.Align = align; - _gameText.Font = font; - _gameText.IsUnicode = isunicode; - _gameText.MaxWidth = w - (HasScrollbar ? 16 : 0) - (HasBackground ? 8 : 0); - } - - InternalBuild(text, hue); - } - - public HtmlControl() - { - _gameText = RenderedText.Create(string.Empty, isunicode: true, font: 1); - - CanMove = true; - } - - public bool HasScrollbar { get; } - - public bool HasBackground { get; } - - public bool UseFlagScrollbar { get; } - - public int ScrollX { get; set; } - - public int ScrollY { get; set; } - - public string Text - { - get => _gameText.Text; - set => _gameText.Text = value; - } - - private void InternalBuild(string text, int hue) - { - if (!string.IsNullOrEmpty(text)) - { - if (_gameText.IsHTML) - { - uint htmlColor = 0xFFFFFFFF; - ushort color = 0; - - if (hue > 0) - { - if (hue == 0x00FFFFFF || hue == 0xFFFF || hue == 0xFF) - { - htmlColor = 0xFFFFFFFE; - } - else - { - htmlColor = (HuesHelper.Color16To32((ushort) hue) << 8) | 0xFF; - } - } - else if (!HasBackground) - { - color = 0xFFFF; - - if (!HasScrollbar) - { - htmlColor = 0x010101FF; - } - } - else - { - _gameText.MaxWidth -= 9; - htmlColor = 0x010101FF; - } - - _gameText.HTMLColor = htmlColor; - _gameText.Hue = color; - } - else - { - _gameText.Hue = (ushort) hue; - } - - _gameText.HasBackgroundColor = !HasBackground; - _gameText.Text = text; - } - - if (HasBackground) - { - Add - ( - new ResizePic(0x2486) - { - Width = Width - (HasScrollbar ? 16 : 0), Height = Height, AcceptMouseInput = false - } - ); - } - - if (HasScrollbar) - { - if (UseFlagScrollbar) - { - _scrollBar = new ScrollFlag - { - Location = new Point(Width - 14, 0) - }; - } - else - { - _scrollBar = new ScrollBar(Width - 14, 0, Height); - } - - _scrollBar.Height = Height; - _scrollBar.MinValue = 0; - - _scrollBar.MaxValue = /* _gameText.Height*/ /* Children.Sum(s => s.Height) - Height +*/ - _gameText.Height - Height + (HasBackground ? 8 : 0); - - ScrollY = _scrollBar.Value; - - Add(_scrollBar); - } - - //if (Width != _gameText.Width) - // Width = _gameText.Width; - } - - protected override void OnMouseWheel(MouseEventType delta) - { - if (!HasScrollbar) - { - return; - } - - switch (delta) - { - case MouseEventType.WheelScrollUp: - _scrollBar.Value -= _scrollBar.ScrollStep; - - break; - - case MouseEventType.WheelScrollDown: - _scrollBar.Value += _scrollBar.ScrollStep; - - break; - } - } - - public override void Update() - { - if (HasScrollbar) - { - if (WantUpdateSize) - { - _scrollBar.Height = Height; - _scrollBar.MinValue = 0; - - _scrollBar.MaxValue = /* _gameText.Height*/ /*Children.Sum(s => s.Height) - Height */ - _gameText.Height - Height + (HasBackground ? 8 : 0); - - //_scrollBar.IsVisible = _scrollBar.MaxValue > _scrollBar.MinValue; - WantUpdateSize = false; - } - - ScrollY = _scrollBar.Value; - } - - base.Update(); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsDisposed) - { - return false; - } - - if (batcher.ClipBegin(x, y, Width, Height)) - { - base.Draw(batcher, x, y); - - int offset = HasBackground ? 4 : 0; - - _gameText.Draw - ( - batcher, - x + offset, - y + offset, - ScrollX, - ScrollY, - Width + ScrollX, - Height + ScrollY - ); - - batcher.ClipEnd(); - } - - - return true; - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - if (_gameText != null) - { - for (int i = 0; i < _gameText.Links.Count; i++) - { - WebLinkRect link = _gameText.Links[i]; - - bool inbounds = link.Bounds.Contains(x, (_scrollBar == null ? 0 : _scrollBar.Value) + y); - - if (inbounds && FontsLoader.Instance.GetWebLink(link.LinkID, out WebLink result)) - { - Log.Info("LINK CLICKED: " + result.Link); - - PlatformHelper.LaunchBrowser(result.Link); - - _gameText.CreateTexture(); - - break; - } - } - } - } - - base.OnMouseUp(x, y, button); - } - - public override void Dispose() - { - _gameText?.Destroy(); - _gameText = null; - base.Dispose(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/InfoBarBuilderControl.cs b/src/ClassicUO.Client/Game/UI/Controls/InfoBarBuilderControl.cs deleted file mode 100644 index 9e29506ee..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/InfoBarBuilderControl.cs +++ /dev/null @@ -1,102 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Managers; -using ClassicUO.Assets; -using ClassicUO.Resources; - -namespace ClassicUO.Game.UI.Controls -{ - internal class InfoBarBuilderControl : Control - { - private readonly StbTextBox infoLabel; - private readonly ClickableColorBox labelColor; - private readonly Combobox varStat; - - public InfoBarBuilderControl(InfoBarItem item) - { - infoLabel = new StbTextBox(0xFF, 10, 80) { X = 5, Y = 0, Width = 130, Height = 26 }; - infoLabel.SetText(item.label); - - string[] dataVars = InfoBarManager.GetVars(); - - varStat = new Combobox - ( - 200, - 0, - 170, - dataVars, - (int) item.var - ); - - - labelColor = new ClickableColorBox - ( - 150, - 0, - 13, - 14, - item.hue - ); - - NiceButton deleteButton = new NiceButton - ( - 390, - 0, - 60, - 25, - ButtonAction.Activate, - ResGumps.Delete - ) { ButtonParameter = 999 }; - - deleteButton.MouseUp += (sender, e) => - { - Dispose(); - ((DataBox) Parent)?.ReArrangeChildren(); - }; - - Add(new ResizePic(0x0BB8) { X = infoLabel.X - 5, Y = 0, Width = infoLabel.Width + 10, Height = infoLabel.Height }); - - Add(infoLabel); - Add(varStat); - Add(labelColor); - Add(deleteButton); - - Width = infoLabel.Width + 10; - Height = infoLabel.Height; - } - - public string LabelText => infoLabel.Text; - public InfoBarVars Var => (InfoBarVars) varStat.SelectedIndex; - public ushort Hue => labelColor.Hue; - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/ItemGump.cs b/src/ClassicUO.Client/Game/UI/Controls/ItemGump.cs deleted file mode 100644 index ff9fcfd96..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ItemGump.cs +++ /dev/null @@ -1,356 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - internal class ItemGump : Control - { - private ushort _graphic; - private readonly bool _is_gump; - - public ItemGump(uint serial, ushort graphic, ushort hue, int x, int y, bool is_gump = false) - { - _is_gump = is_gump; - - AcceptMouseInput = true; - X = (short)x; - Y = (short)y; - HighlightOnMouseOver = true; - CanPickUp = true; - LocalSerial = serial; - WantUpdateSize = false; - CanMove = false; - - Graphic = graphic; - Hue = hue; - - SetTooltip(serial); - } - - public ushort Graphic - { - get => _graphic; - set - { - _graphic = value; - - ref readonly var spriteInfo = ref _is_gump - ? ref Client.Game.Gumps.GetGump(value) - : ref Client.Game.Arts.GetArt(value); - - if (spriteInfo.Texture == null) - { - Dispose(); - - return; - } - - Width = spriteInfo.UV.Width; - Height = spriteInfo.UV.Height; - - IsPartialHue = !_is_gump && TileDataLoader.Instance.StaticData[value].IsPartialHue; - } - } - - public ushort Hue { get; set; } - public bool IsPartialHue { get; set; } - public bool HighlightOnMouseOver { get; set; } - public bool CanPickUp { get; set; } - - public override void Update() - { - if (IsDisposed) - { - return; - } - - base.Update(); - - if (World.InGame) - { - if ( - CanPickUp - && !Client.Game.GameCursor.ItemHold.Enabled - && Mouse.LButtonPressed - && UIManager.LastControlMouseDown(MouseButtonType.Left) == this - && ( - Mouse.LastLeftButtonClickTime != 0xFFFF_FFFF - && Mouse.LastLeftButtonClickTime != 0 - && Mouse.LastLeftButtonClickTime + Mouse.MOUSE_DELAY_DOUBLE_CLICK - < Time.Ticks - || CanPickup() - ) - ) - { - AttemptPickUp(); - } - else if (MouseIsOver) - { - SelectedObject.Object = World.Get(LocalSerial); - } - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsDisposed) - { - return false; - } - - base.Draw(batcher, x, y); - - bool partialHue = IsPartialHue; - ushort hue = Hue; - - if (HighlightOnMouseOver && MouseIsOver) - { - hue = 0x0035; - partialHue = false; - } - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(hue, partialHue, 1); - - ref readonly var spriteInfo = ref _is_gump - ? ref Client.Game.Gumps.GetGump(Graphic) - : ref Client.Game.Arts.GetArt(Graphic); - - if (spriteInfo.Texture != null) - { - Rectangle rect = new Rectangle(x, y, Width, Height); - - batcher.Draw(spriteInfo.Texture, rect, spriteInfo.UV, hueVector); - - Item item = World.Items.Get(LocalSerial); - - if ( - item != null - && !item.IsMulti - && !item.IsCoin - && item.Amount > 1 - && item.ItemData.IsStackable - ) - { - rect.X += 5; - rect.Y += 5; - - batcher.Draw(spriteInfo.Texture, rect, spriteInfo.UV, hueVector); - } - } - - return true; - } - - public override bool Contains(int x, int y) - { - ref readonly var spriteInfo = ref _is_gump - ? ref Client.Game.Gumps.GetGump(Graphic) - : ref Client.Game.Arts.GetArt(Graphic); - - if (spriteInfo.Texture == null) - { - return false; - } - - x -= Offset.X; - y -= Offset.Y; - - if ( - ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.ScaleItemsInsideContainers - ) - { - float scale = UIManager.ContainerScale; - - x = (int)(x / scale); - y = (int)(y / scale); - } - - if (_is_gump) - { - if (Client.Game.Gumps.PixelCheck(Graphic, x, y)) - { - return true; - } - - Item item = World.Items.Get(LocalSerial); - - if (item != null && !item.IsCoin && item.Amount > 1 && item.ItemData.IsStackable) - { - if (Client.Game.Gumps.PixelCheck(Graphic, x - 5, y - 5)) - { - return true; - } - } - } - else - { - if (Client.Game.Arts.PixelCheck(Graphic, x, y)) - { - return true; - } - - Item item = World.Items.Get(LocalSerial); - - if (item != null && !item.IsCoin && item.Amount > 1 && item.ItemData.IsStackable) - { - if (Client.Game.Arts.PixelCheck(Graphic, x - 5, y - 5)) - { - return true; - } - } - } - - return false; - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - SelectedObject.Object = World.Get(LocalSerial); - base.OnMouseUp(x, y, button); - } - - protected override void OnMouseOver(int x, int y) - { - SelectedObject.Object = World.Get(LocalSerial); - } - - private bool CanPickup() - { - Point offset = Mouse.LDragOffset; - - if ( - Math.Abs(offset.X) < Constants.MIN_PICKUP_DRAG_DISTANCE_PIXELS - && Math.Abs(offset.Y) < Constants.MIN_PICKUP_DRAG_DISTANCE_PIXELS - ) - { - return false; - } - - SplitMenuGump split = UIManager.GetGump(LocalSerial); - - if (split == null) - { - return true; - } - - split.X = Mouse.LClickPosition.X - 80; - split.Y = Mouse.LClickPosition.Y - 40; - UIManager.AttemptDragControl(split, true); - split.BringOnTop(); - - return false; - } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if (button != MouseButtonType.Left || TargetManager.IsTargeting) - { - return false; - } - - Item item = World.Items.Get(LocalSerial); - Item container; - - if ( - !Keyboard.Ctrl - && ProfileManager.CurrentProfile.DoubleClickToLootInsideContainers - && item != null - && !item.IsDestroyed - && !item.ItemData.IsContainer - && item.IsEmpty - && (container = World.Items.Get(item.RootContainer)) != null - && container != World.Player.FindItemByLayer(Layer.Backpack) - ) - { - GameActions.GrabItem(LocalSerial, item.Amount); - } - else - { - GameActions.DoubleClick(LocalSerial); - } - - return true; - } - - private void AttemptPickUp() - { - if (CanPickUp) - { - ref readonly var spriteInfo = ref _is_gump - ? ref Client.Game.Gumps.GetGump(Graphic) - : ref Client.Game.Arts.GetArt(Graphic); - - int centerX = spriteInfo.UV.Width >> 1; - int centerY = spriteInfo.UV.Height >> 1; - - if ( - ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.ScaleItemsInsideContainers - ) - { - float scale = UIManager.ContainerScale; - centerX = (int)(centerX * scale); - centerY = (int)(centerY * scale); - } - - if ( - ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.RelativeDragAndDropItems - ) - { - Point p = new Point( - centerX - (Mouse.Position.X - ScreenCoordinateX), - centerY - (Mouse.Position.Y - ScreenCoordinateY) - ); - - GameActions.PickUp(LocalSerial, centerX, centerY, offset: p, is_gump: _is_gump); - } - else - { - GameActions.PickUp(LocalSerial, centerX, centerY, is_gump: _is_gump); - } - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/Label.cs b/src/ClassicUO.Client/Game/UI/Controls/Label.cs deleted file mode 100644 index 71b4e46c0..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/Label.cs +++ /dev/null @@ -1,135 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; - -namespace ClassicUO.Game.UI.Controls -{ - public class Label : Control - { - private readonly RenderedText _gText; - - public Label - ( - string text, - bool isunicode, - ushort hue, - int maxwidth = 0, - byte font = 0xFF, - FontStyle style = FontStyle.None, - TEXT_ALIGN_TYPE align = TEXT_ALIGN_TYPE.TS_LEFT, - bool ishtml = false - ) - { - _gText = RenderedText.Create - ( - text, - hue, - font, - isunicode, - style, - align, - maxwidth, - isHTML: ishtml - ); - - AcceptMouseInput = false; - Width = _gText.Width; - Height = _gText.Height; - } - - public Label(List parts, string[] lines) : this - ( - int.TryParse(parts[4], out int lineIndex) && lineIndex >= 0 && lineIndex < lines.Length ? lines[lineIndex] : string.Empty, - true, - (ushort) (UInt16Converter.Parse(parts[3]) + 1), - 0, - style: FontStyle.BlackBorder - ) - { - X = int.Parse(parts[1]); - Y = int.Parse(parts[2]); - IsFromServer = true; - } - - public string Text - { - get => _gText.Text; - set - { - _gText.Text = value; - Width = _gText.Width; - Height = _gText.Height; - } - } - - - public ushort Hue - { - get => _gText.Hue; - set - { - if (_gText.Hue != value) - { - _gText.Hue = value; - _gText.CreateTexture(); - } - } - } - - - public byte Font => _gText.Font; - - public bool Unicode => _gText.IsUnicode; - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsDisposed) - { - return false; - } - - _gText.Draw(batcher, x, y, Alpha); - - return base.Draw(batcher, x, y); - } - - public override void Dispose() - { - base.Dispose(); - _gText.Destroy(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/Line.cs b/src/ClassicUO.Client/Game/UI/Controls/Line.cs deleted file mode 100644 index 2963724e2..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/Line.cs +++ /dev/null @@ -1,73 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.UI.Controls -{ - internal class Line : Control - { - private readonly Texture2D _texture; - - public Line(int x, int y, int w, int h, uint color) - { - X = x; - Y = y; - Width = w; - Height = h; - - _texture = SolidColorTextureCache.GetTexture(new Color { PackedValue = color }); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0, false, Alpha); - - batcher.Draw - ( - _texture, - new Rectangle - ( - x, - y, - Width, - Height - ), - hueVector - ); - - return true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/MacroControl.cs b/src/ClassicUO.Client/Game/UI/Controls/MacroControl.cs deleted file mode 100644 index 1972afd48..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/MacroControl.cs +++ /dev/null @@ -1,655 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Linq; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using SDL2; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - internal class MacroControl : Control - { - private static readonly string[] _allHotkeysNames = Enum.GetNames(typeof(MacroType)); - private static readonly string[] _allSubHotkeysNames = Enum.GetNames(typeof(MacroSubType)); - private readonly DataBox _databox; - private readonly HotkeyBox _hotkeyBox; - - private enum buttonsOption - { - AddBtn, - RemoveBtn, - CreateNewMacro, - OpenMacroOptions, - OpenButtonEditor - } - - public MacroControl(string name, bool isFastAssign = false) - { - CanMove = true; - Label _keyBinding; - Add(_keyBinding = new Label - ( - "HotKey:", - true, - 0xFFFF, - 60, - 0xFF, - FontStyle.BlackBorder | FontStyle.Cropped - )); - - _hotkeyBox = new HotkeyBox(); - _hotkeyBox.HotkeyChanged += BoxOnHotkeyChanged; - _hotkeyBox.HotkeyCancelled += BoxOnHotkeyCancelled; - _hotkeyBox.X = _keyBinding.X + _keyBinding.Width + 5; - - - Add(_hotkeyBox); - - Add - ( - new NiceButton - ( - 0, - _hotkeyBox.Height + 3, - 150, - 25, - ButtonAction.Activate, - ResGumps.CreateMacroButton, - 0, - TEXT_ALIGN_TYPE.TS_CENTER - ) { ButtonParameter = (int)buttonsOption.CreateNewMacro, IsSelectable = true, IsSelected = true } - ); - Add - ( - new NiceButton - ( - 170, - _hotkeyBox.Height + 3, - 150, - 25, - ButtonAction.Activate, - ResGumps.MacroButtonEditor, - 0, - TEXT_ALIGN_TYPE.TS_CENTER - ) - { ButtonParameter = (int)buttonsOption.OpenButtonEditor, IsSelectable = true, IsSelected = true } - ); - - Add - ( - new Line - ( - 0, - _hotkeyBox.Height + 30, - 325, - 1, - Color.Gray.PackedValue - ) - ); - - if (!isFastAssign) - { - Add - ( - new NiceButton - ( - 0, - _hotkeyBox.Height + 35, - 50, - 25, - ButtonAction.Activate, - ResGumps.Add - ) - { ButtonParameter = (int)buttonsOption.AddBtn, IsSelectable = false } - ); - - } else { - Add - ( - new NiceButton - ( - 0, - _hotkeyBox.Height + 30, - 170, - 25, - ButtonAction.Activate, - ResGumps.OpenMacroSettings - ) - { ButtonParameter = (int)buttonsOption.OpenMacroOptions, IsSelectable = false } - ); - } - - var scrollAreaH = isFastAssign ? 80 : 280; - var scrollAreaW = 280; - - ScrollArea area = new ScrollArea - ( - 10, - _hotkeyBox.Bounds.Bottom + 70, - scrollAreaW, - scrollAreaH, - true - ); - - Add(area); - - _databox = new DataBox(0, 0, 280, 280) - { - WantUpdateSize = true - }; - area.Add(_databox); - - - Macro = Client.Game.GetScene().Macros.FindMacro(name) ?? Macro.CreateEmptyMacro(name); - - SetupKeyByDefault(); - SetupMacroUI(); - } - - - public Macro Macro { get; } - - private void AddEmptyMacro() - { - MacroObject ob = (MacroObject) Macro.Items; - - if (ob.Code == MacroType.None) - { - return; - } - - while (ob.Next != null) - { - MacroObject next = (MacroObject) ob.Next; - - if (next.Code == MacroType.None) - { - return; - } - - ob = next; - } - - MacroObject obj = Macro.Create(MacroType.None); - - Macro.PushToBack(obj); - - _databox.Add(new MacroEntry(this, obj, _allHotkeysNames)); - _databox.WantUpdateSize = true; - _databox.ReArrangeChildren(); - } - - private void RemoveLastCommand() - { - if (_databox.Children.Count != 0) - { - LinkedObject last = Macro.GetLast(); - - Macro.Remove(last); - - _databox.Children[_databox.Children.Count - 1].Dispose(); - - SetupMacroUI(); - } - - if (_databox.Children.Count == 0) - { - AddEmptyMacro(); - } - } - - private void SetupMacroUI() - { - if (Macro == null) - { - return; - } - - _databox.Clear(); - _databox.Children.Clear(); - - if (Macro.Items == null) - { - Macro.Items = Macro.Create(MacroType.None); - } - - MacroObject obj = (MacroObject)Macro.Items; - while (obj != null) - { - _databox.Add(new MacroEntry(this, obj, _allHotkeysNames)); - - if (obj.Next != null && obj.Code == MacroType.None) - { - break; - } - obj = (MacroObject)obj.Next; - } - - _databox.WantUpdateSize = true; - _databox.ReArrangeChildren(); - } - - private void SetupKeyByDefault() - { - if (Macro == null || _hotkeyBox == null) - { - return; - } - - if(Macro.ControllerButtons != null && Macro.ControllerButtons.Length > 0) - { - _hotkeyBox.SetButtons(Macro.ControllerButtons); - } - - SDL.SDL_Keymod mod = SDL.SDL_Keymod.KMOD_NONE; - - if (Macro.Alt) - { - mod |= SDL.SDL_Keymod.KMOD_ALT; - } - - if (Macro.Shift) - { - mod |= SDL.SDL_Keymod.KMOD_SHIFT; - } - - if (Macro.Ctrl) - { - mod |= SDL.SDL_Keymod.KMOD_CTRL; - } - - if (Macro.Key != SDL.SDL_Keycode.SDLK_UNKNOWN) - { - _hotkeyBox.SetKey(Macro.Key, mod); - } - else if (Macro.MouseButton != MouseButtonType.None) - { - _hotkeyBox.SetMouseButton(Macro.MouseButton, mod); - } - else if (Macro.WheelScroll == true) - { - _hotkeyBox.SetMouseWheel(Macro.WheelUp, mod); - } - } - - private void BoxOnHotkeyChanged(object sender, EventArgs e) - { - bool shift = (_hotkeyBox.Mod & SDL.SDL_Keymod.KMOD_SHIFT) != SDL.SDL_Keymod.KMOD_NONE; - bool alt = (_hotkeyBox.Mod & SDL.SDL_Keymod.KMOD_ALT) != SDL.SDL_Keymod.KMOD_NONE; - bool ctrl = (_hotkeyBox.Mod & SDL.SDL_Keymod.KMOD_CTRL) != SDL.SDL_Keymod.KMOD_NONE; - - if (_hotkeyBox.Key != SDL.SDL_Keycode.SDLK_UNKNOWN) - { - Macro macro = Client.Game.GetScene().Macros.FindMacro(_hotkeyBox.Key, alt, ctrl, shift); - - if (macro != null) - { - if (Macro == macro) - { - return; - } - - SetupKeyByDefault(); - UIManager.Add(new MessageBoxGump(250, 150, string.Format(ResGumps.ThisKeyCombinationAlreadyExists, macro.Name), null)); - - return; - } - } - else if (_hotkeyBox.MouseButton != MouseButtonType.None) - { - Macro macro = Client.Game.GetScene().Macros.FindMacro(_hotkeyBox.MouseButton, alt, ctrl, shift); - - if (macro != null) - { - if (Macro == macro) - { - return; - } - - SetupKeyByDefault(); - UIManager.Add(new MessageBoxGump(250, 150, string.Format(ResGumps.ThisKeyCombinationAlreadyExists, macro.Name), null)); - - return; - } - } - else if (_hotkeyBox.WheelScroll == true) - { - Macro macro = Client.Game.GetScene().Macros.FindMacro(_hotkeyBox.WheelUp, alt, ctrl, shift); - - if (macro != null) - { - if (Macro == macro) - { - return; - } - - SetupKeyByDefault(); - UIManager.Add(new MessageBoxGump(250, 150, string.Format(ResGumps.ThisKeyCombinationAlreadyExists, macro.Name), null)); - - return; - } - } - else if(_hotkeyBox.Buttons != null && _hotkeyBox.Buttons.Length > 0) - { - - } - else - { - return; - } - - Macro m = Macro; - - if(_hotkeyBox.Buttons != null && _hotkeyBox.Buttons.Length > 0) - { - m.ControllerButtons = _hotkeyBox.Buttons; - } - - m.Key = _hotkeyBox.Key; - m.MouseButton = _hotkeyBox.MouseButton; - m.WheelScroll = _hotkeyBox.WheelScroll; - m.WheelUp = _hotkeyBox.WheelUp; - m.Shift = shift; - m.Alt = alt; - m.Ctrl = ctrl; - } - - private void BoxOnHotkeyCancelled(object sender, EventArgs e) - { - Macro m = Macro; - m.Alt = m.Ctrl = m.Shift = false; - m.Key = SDL.SDL_Keycode.SDLK_UNKNOWN; - m.MouseButton = MouseButtonType.None; - m.WheelScroll = false; - } - - public override void OnButtonClick(int buttonID) - { - switch (buttonID) - { - case (int)buttonsOption.AddBtn: - AddEmptyMacro(); - break; - case (int)buttonsOption.RemoveBtn: - RemoveLastCommand(); - break; - case (int)buttonsOption.CreateNewMacro: - UIManager.Gumps.OfType().FirstOrDefault(s => s.TheMacro == Macro)?.Dispose(); - - MacroButtonGump macroButtonGump = new MacroButtonGump(Macro, Mouse.Position.X, Mouse.Position.Y); - UIManager.Add(macroButtonGump); - break; - case (int)buttonsOption.OpenMacroOptions: - UIManager.Gumps.OfType().FirstOrDefault()?.Dispose(); - - GameActions.OpenSettings(4); - break; - case (int)buttonsOption.OpenButtonEditor: - UIManager.Gumps.OfType().FirstOrDefault()?.Dispose(); - OpenMacroButtonEditor(Macro, null); - break; - } - } - - private void OpenMacroButtonEditor(Macro macro, Vector2? position = null) - { - MacroButtonEditorGump btnEditorGump = UIManager.GetGump(); - - if (btnEditorGump == null) - { - var posX = (Client.Game.Window.ClientBounds.Width >> 1) - 300; - var posY = (Client.Game.Window.ClientBounds.Height >> 1) - 250; - Gump opt = UIManager.GetGump(); - if (opt != null) - { - posX = opt.X + opt.Width + 5; - posY = opt.Y; - } - if (position.HasValue) - { - posX = (int)position.Value.X; - posY = (int)position.Value.Y; - } - btnEditorGump = new MacroButtonEditorGump(macro, posX, posY); - UIManager.Add(btnEditorGump); - } - btnEditorGump.SetInScreen(); - btnEditorGump.BringOnTop(); - } - - - private class MacroEntry : Control - { - private readonly MacroControl _control; - private readonly MacroObject _obj; - private readonly string[] _items; - public event EventHandler OnDelete; - - public MacroEntry(MacroControl control, MacroObject obj, string[] items) - { - _control = control; - _items = items; - _obj = obj; - - Combobox mainBox = new Combobox - ( - 0, - 0, - 200, - _items, - (int) obj.Code - ) - { - Tag = obj - }; - - mainBox.OnOptionSelected += BoxOnOnOptionSelected; - - Add(mainBox); - - Width = mainBox.Width; - Height = mainBox.Height; - - Add(new NiceButton - ( - mainBox.Width + 10, - 0, - 50, - 25, - ButtonAction.Activate, - ResGumps.Remove, - 0, - TEXT_ALIGN_TYPE.TS_CENTER - ) - { ButtonParameter = (int)buttonsOption.RemoveBtn, IsSelectable = false }); - - AddSubMacro(obj); - - WantUpdateSize = true; - } - - - private void AddSubMacro(MacroObject obj) - { - if (obj == null || obj.Code == 0) - { - return; - } - - switch (obj.SubMenuType) - { - case 1: - int count = 0; - int offset = 0; - Macro.GetBoundByCode(obj.Code, ref count, ref offset); - - string[] names = new string[count]; - - for (int i = 0; i < count; i++) - { - names[i] = _allSubHotkeysNames[i + offset]; - } - - Combobox sub = new Combobox - ( - 20, - Height, - 180, - names, - (int) obj.SubCode - offset, - 300 - ); - - sub.OnOptionSelected += (senderr, ee) => - { - Macro.GetBoundByCode(obj.Code, ref count, ref offset); - MacroSubType subType = (MacroSubType) (offset + ee); - obj.SubCode = subType; - }; - - Add(sub); - - Height += sub.Height; - - - break; - - case 2: - - ResizePic background = new ResizePic(0x0BB8) - { - X = 16, - Y = Height, - Width = 240, - Height = 60 - }; - - Add(background); - - StbTextBox textbox = new StbTextBox - ( - 0xFF, - 80, - 236, - true, - FontStyle.BlackBorder - ) - { - X = background.X + 4, - Y = background.Y + 4, - Width = background.Width - 4, - Height = background.Height - 4 - }; - - textbox.SetText(obj.HasString() ? ((MacroObjectString) obj).Text : string.Empty); - - textbox.TextChanged += (sss, eee) => - { - if (obj.HasString()) - { - ((MacroObjectString) obj).Text = ((StbTextBox) sss).Text; - } - }; - - Add(textbox); - - WantUpdateSize = true; - Height += background.Height; - - break; - } - - _control._databox.ReArrangeChildren(); - } - - public override void OnButtonClick(int buttonID) - { - switch (buttonID) - { - case (int)buttonsOption.RemoveBtn: - _control.Macro.Remove(_obj); - Dispose(); - _control.SetupMacroUI(); - OnDelete?.Invoke(this, _obj); - break; - } - } - - - private void BoxOnOnOptionSelected(object sender, int e) - { - WantUpdateSize = true; - - Combobox box = (Combobox) sender; - MacroObject currentMacroObj = (MacroObject) box.Tag; - - if (e == 0) - { - _control.Macro.Remove(currentMacroObj); - - box.Tag = null; - - Dispose(); - - _control.SetupMacroUI(); - } - else - { - MacroObject newMacroObj = Macro.Create((MacroType) e); - - _control.Macro.Insert(currentMacroObj, newMacroObj); - _control.Macro.Remove(currentMacroObj); - - box.Tag = newMacroObj; - - - for (int i = 2; i < Children.Count; i++) - { - Children[i]?.Dispose(); - } - - Height = box.Height; - - AddSubMacro(newMacroObj); - } - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/MenuButton.cs b/src/ClassicUO.Client/Game/UI/Controls/MenuButton.cs deleted file mode 100644 index 895eafab2..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/MenuButton.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace ClassicUO.Game.UI.Controls -{ - internal class MenuButton : Control - { - public MenuButton(int width, uint hue, float alpha, string tooltip = "") - { - Width = width; - Height = 16; - AcceptMouseInput = true; - Area _ = new Area(true, (int)hue) { Width = Width, Height = Height, AcceptMouseInput = false }; - _.Add(new AlphaBlendControl(0.25f) { Width = Width, Height = Height }); - - Add(_); - Add(new Line(0, 2, Width, 2, hue) { Alpha = alpha, AcceptMouseInput = false }); - Add(new Line(0, 7, Width, 2, hue) { Alpha = alpha, AcceptMouseInput = false }); - Add(new Line(0, 12, Width, 2, hue) { Alpha = alpha, AcceptMouseInput = false }); - SetTooltip(tooltip); - //_.SetTooltip(tooltip); - } - - public override bool Contains(int x, int y) - { - return true; - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/MultiSelectionShrinkbox.cs b/src/ClassicUO.Client/Game/UI/Controls/MultiSelectionShrinkbox.cs deleted file mode 100644 index 3bf6cf6d4..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/MultiSelectionShrinkbox.cs +++ /dev/null @@ -1,384 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.UI.Controls -{ - //internal class MultiSelectionShrinkbox : Control - //{ - // private readonly GumpPic _arrow; - // private readonly int _buttongroup; - // private readonly ushort _buttonimg, _pressedbuttonimg; - // private NiceButton[] _buttons; - // private string[] _items; - // private readonly Label _label; - // //this particular list will be used when inside a scroll area or similar situations where you want to nest a multi selection shrinkbox inside another one, - // //so that when the parent is deactivated, all the child will be made non visible - // private readonly List _nestedBoxes = new List(); - // private bool _opened; - // private Button[] _pics; - // private readonly bool _useArrow2; - - // public MultiSelectionShrinkbox(int x, int y, int width, string indextext, string[] items, ushort hue = 0x0453, bool unicode = false, byte font = 9, int group = 0, ushort button = 0, ushort pressedbutton = 0, bool useArrow2 = false) : this(x, y, width, indextext, hue, unicode, font, group, button, pressedbutton, useArrow2) - // { - // SetItemsValue(items); - // } - - // private MultiSelectionShrinkbox(int x, int y, int width, string indextext, ushort hue, bool unicode, byte font, int group, ushort button, ushort pressedbutton, bool userArrow2 = false) - // { - // WantUpdateSize = false; - // X = x; - // Y = y; - - // if (button > 0) - // { - // _buttonimg = button; - - // if (pressedbutton > 0) - // { - // _pressedbuttonimg = pressedbutton; - // } - // else - // { - // _pressedbuttonimg = button; - // } - // } - - // _buttongroup = group; - // Width = width; - // _useArrow2 = userArrow2; - - // Add - // ( - // _label = new Label(indextext, unicode, hue, font: font, align: TEXT_ALIGN_TYPE.TS_LEFT) - // { - // X = 18 - // } - // ); - - // Height = _label.Height; - - // Add(_arrow = new GumpPic(1, 1, (ushort) (userArrow2 ? 0x0827 : 0x15E1), 0)); - - // _arrow.MouseUp += (sender, state) => - // { - // if (state.Button == MouseButtonType.Left) - // { - // Opened = !_opened; - // } - // }; - // } - - // internal bool Opened - // { - // get => _opened; - // set - // { - // if (_opened != value) - // { - // _opened = value; - - // if (_opened) - // { - // _arrow.Graphic = (ushort) (_useArrow2 ? 0x0826 : 0x15E2); - // OnBeforeContextMenu?.Invoke(this, null); - // GenerateButtons(); - - // foreach (MultiSelectionShrinkbox msb in _nestedBoxes) - // { - // msb.IsVisible = true; - // msb.OnPageChanged(); - // } - // } - // else - // { - // _arrow.Graphic = (ushort) (_useArrow2 ? 0x0827 : 0x15E1); - // ClearButtons(); - // Height = _label.Height; - // OnAfterContextMenu?.Invoke(this, null); - - // foreach (MultiSelectionShrinkbox msb in _nestedBoxes) - // { - // msb.IsVisible = false; - // msb.OnPageChanged(); - // } - // } - - // Parent?.OnPageChanged(); - // } - // } - // } - - // public int SelectedIndex { get; private set; } - - // public string SelectedName - // { - // get - // { - // if (_items != null && SelectedIndex >= 0 && SelectedIndex < _items.Length) - // { - // return _items[SelectedIndex]; - // } - - // return null; - // } - // } - - // internal uint GetItemsLength => (uint) _items.Length; - - // public string Name => _label == null ? null : _label.Text; - - // public MultiSelectionShrinkbox ParentBox { get; private set; } - - // internal bool NestBox(MultiSelectionShrinkbox box) - // { - // if (_nestedBoxes.Contains(box)) - // { - // return false; - // } - - // Control c = Parent; - - // while (c != null) - // { - // if (c is ScrollArea area) - // { - // _arrow.IsVisible = true; - // _nestedBoxes.Add(box); - // box.Width = Width - box.X; - // area.Add(box); - - // if (!_opened) - // { - // box.IsVisible = false; - // } - - // box.OnPageChanged(); - // box.ParentBox = this; - - // return true; - // } - - // c = c.Parent; - // } - - // return false; - // } - - // internal void SetItemsValue(string[] items) - // { - // _items = items; - - // if (_opened) - // { - // GenerateButtons(); - // } - - // _arrow.IsVisible = items.Length > 0 || _nestedBoxes.Count > 0; - // } - - // internal void SetItemsValue(Dictionary items) - // { - // _items = items.Select(o => o.Value) - // .ToArray(); - - // if (_opened) - // { - // GenerateButtons(); - // } - - // _arrow.IsVisible = items.Count > 0 || _nestedBoxes.Count > 0; - // } - - // private void GenerateButtons() - // { - // ClearButtons(); - // _buttons = new NiceButton[_items.Length]; - - // if (_buttonimg > 0) - // { - // _pics = new Button[_items.Length]; - // } - - // int index = 0; - // int width = 0; - // int height = 0; - // int lh = _label.Height + 2; - - // foreach (string item in _items) - // { - // int w, h; - - // if (_label.Unicode) - // { - // w = FontsLoader.Instance.GetWidthUnicode(_label.Font, item); - // } - // else - // { - // w = FontsLoader.Instance.GetWidthASCII(_label.Font, item); - // } - - // if (w > width) - // { - // if (_label.Unicode) - // { - // h = FontsLoader.Instance.GetHeightUnicode(_label.Font, item, w, TEXT_ALIGN_TYPE.TS_LEFT, 0x0); - // } - // else - // { - // h = FontsLoader.Instance.GetHeightASCII(_label.Font, item, w, TEXT_ALIGN_TYPE.TS_LEFT, 0x0); - // } - - // width = w; - // height = h + 2; - // } - // } - - // foreach (string item in _items) - // { - // NiceButton but = new NiceButton(20, index * height + lh, width, height, ButtonAction.Activate, item, _buttongroup, TEXT_ALIGN_TYPE.TS_LEFT) {Tag = index}; - - // if (_buttonimg > 0) - // { - // Add(_pics[index] = new Button(index, _buttonimg, _pressedbuttonimg) {X = 6, Y = index * height + lh + 2, ButtonAction = (ButtonAction) 0xBEEF, Tag = index}); - - // _pics[index] - // .MouseUp += Selection_MouseClick; - // } - - // but.MouseUp += Selection_MouseClick; - // _buttons[index] = but; - // Add(but); - // index++; - // } - - // int totalHeight = _buttons.Length > 0 ? _buttons.Sum(o => o.Height) + lh : lh; - - // Height = totalHeight; - - // Parent.WantUpdateSize = true; - // } - - // private void ClearButtons() - // { - // if (_buttons != null) - // { - // for (int i = _buttons.Length - 1; i >= 0; --i) - // { - // _buttons[i] - // ?.Dispose(); - - // _buttons[i] = null; - // } - // } - - // if (_pics != null) - // { - // for (int i = _pics.Length - 1; i >= 0; --i) - // { - // _pics[i] - // ?.Dispose(); - - // _pics[i] = null; - // } - // } - // } - - // private void Selection_MouseClick(object sender, MouseEventArgs e) - // { - // if (sender is Control c) - // { - // SelectedIndex = (int) c.Tag; - - // if (sender is Button) - // { - // _buttons[SelectedIndex] - // .IsSelected = true; - // } - - // if (_buttongroup > 0) - // { - // OnGroupSelection(); - // } - - // if (_items != null && SelectedIndex >= 0 && SelectedIndex < _items.Length) - // { - // OnOptionSelected?.Invoke(this, c); - // } - // } - // } - - // private void OnGroupSelection() - // { - // if (Parent != null && Parent.Parent is ScrollArea area) - // { - // foreach (Control sai in area.Children) - // { - // if (sai is ScrollAreaItem) - // { - // foreach (Control c in sai.Children) - // { - // if (c is MultiSelectionShrinkbox msb && msb._buttongroup == _buttongroup && msb != this && msb._buttons != null) - // { - // foreach (NiceButton button in msb._buttons) - // { - // if (button != null) - // { - // button.IsSelected = false; - // } - // } - // } - // } - // } - // } - // } - // } - - // public event EventHandler OnOptionSelected; - // public event EventHandler OnBeforeContextMenu; - // public event EventHandler OnAfterContextMenu; - - // protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - // { - // if (_label.Bounds.Contains(Mouse.Position.X - ScreenCoordinateX, Mouse.Position.Y - ScreenCoordinateY) && button == MouseButtonType.Left) - // { - // Opened = !_opened; - // } - - // return base.OnMouseDoubleClick(x, y, button); - // } - - // public override void OnPageChanged() - // { - // Parent?.OnPageChanged(); - // } - //} -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/NameOverheadAssignControl.cs b/src/ClassicUO.Client/Game/UI/Controls/NameOverheadAssignControl.cs deleted file mode 100644 index 3cc0efcb1..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/NameOverheadAssignControl.cs +++ /dev/null @@ -1,293 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Assets; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Resources; -using SDL2; - -namespace ClassicUO.Game.UI.Controls -{ - internal class NameOverheadAssignControl : Control - { - private readonly HotkeyBox _hotkeyBox; - private readonly Dictionary checkboxDict = new(); - private readonly ScrollArea checkBoxScroll; - - private enum ButtonType - { - CheckAll, - UncheckAll, - } - - public NameOverheadAssignControl(NameOverheadOption option) - { - Option = option; - - CanMove = true; - - AddLabel("Set hotkey:", 0, 0); - - _hotkeyBox = new HotkeyBox - { - X = 80 - }; - - _hotkeyBox.HotkeyChanged += BoxOnHotkeyChanged; - _hotkeyBox.HotkeyCancelled += BoxOnHotkeyCancelled; - - Add(_hotkeyBox); - - Add - ( - new NiceButton - ( - 0, _hotkeyBox.Height + 3, 100, 25, - ButtonAction.Activate, "Uncheck all", 0, TEXT_ALIGN_TYPE.TS_LEFT - ) { ButtonParameter = (int)ButtonType.UncheckAll, IsSelectable = false } - ); - - Add - ( - new NiceButton - ( - 120, _hotkeyBox.Height + 3, 100, 25, - ButtonAction.Activate, "Check all", 0, TEXT_ALIGN_TYPE.TS_LEFT - ) { ButtonParameter = (int)ButtonType.CheckAll, IsSelectable = false } - ); - - Add(checkBoxScroll = new ScrollArea(0, 60, 300, 350, true)); - - SetupOptionCheckboxes(); - - UpdateCheckboxesByCurrentOptionFlags(); - UpdateValueInHotkeyBox(); - } - - private void SetupOptionCheckboxes() - { - var y = 0; - AddLabel("Items", 75, y, true); - y += 28; - - AddCheckbox("Containers", NameOverheadOptions.Containers, 0, y); - AddCheckbox("Gold", NameOverheadOptions.Gold, 150, y); - y += 22; - AddCheckbox("Stackable", NameOverheadOptions.Stackable, 0, y); - AddCheckbox("Locked down", NameOverheadOptions.LockedDown, 150, y); - y += 22; - AddCheckbox("Other items", NameOverheadOptions.Other, 0, y); - y += 28; - - AddLabel("Corpses", 75, y, true); - y += 28; - - AddCheckbox("Monster corpses", NameOverheadOptions.MonsterCorpses, 0, y); - AddCheckbox("Humanoid corpses", NameOverheadOptions.HumanoidCorpses, 150, y); - //y += 22; - //AddCheckbox("Own corpses", NameOverheadOptions.OwnCorpses, 0, y); - y += 28; - - AddLabel("Mobiles by type", 75, y, true); - y += 28; - - AddCheckbox("Humanoid", NameOverheadOptions.Humanoid, 0, y); - AddCheckbox("Monster", NameOverheadOptions.Monster, 150, y); - y += 22; - AddCheckbox("Your Followers", NameOverheadOptions.OwnFollowers, 0, y); - AddCheckbox("Yourself", NameOverheadOptions.Self, 150, y); - y += 22; - AddCheckbox("Exclude yourself", NameOverheadOptions.ExcludeSelf, 0, y); - y += 28; - - AddLabel("Mobiles by notoriety", 75, y, true); - y += 28; - - AddCheckbox("Innocent (blue)", NameOverheadOptions.Innocent, 0, y); - AddCheckbox("Allied (green)", NameOverheadOptions.Ally, 150, y); - y += 22; - AddCheckbox("Attackable (gray)", NameOverheadOptions.Gray, 0, y); - AddCheckbox("Criminal (gray)", NameOverheadOptions.Criminal, 150, y); - y += 22; - AddCheckbox("Enemy (orange)", NameOverheadOptions.Enemy, 0, y); - AddCheckbox("Murderer (red)", NameOverheadOptions.Murderer, 150, y); - y += 22; - AddCheckbox("Invulnerable (yellow)", NameOverheadOptions.Invulnerable, 0, y); - } - - private void AddLabel(string name, int x, int y, bool scrollArea = false) - { - var label = new Label(name, true, 0xFFFF) - { - X = x, - Y = y, - }; - if (scrollArea) - { - checkBoxScroll.Add(label); - } - else - { - Add(label); - } - } - - private void AddCheckbox(string checkboxName, NameOverheadOptions optionFlag, int x, int y) - { - var checkbox = new Checkbox - ( - 0x00D2, 0x00D3, checkboxName, 0xFF, - 0xFFFF - ) - { - IsChecked = true, - X = x, - Y = y - }; - - checkbox.ValueChanged += (sender, args) => - { - var isChecked = ((Checkbox)sender).IsChecked; - - if (isChecked) - Option.NameOverheadOptionFlags |= (int)optionFlag; - else - Option.NameOverheadOptionFlags &= ~(int)optionFlag; - - if (NameOverHeadManager.LastActiveNameOverheadOption == Option.Name) - NameOverHeadManager.ActiveOverheadOptions = (NameOverheadOptions)Option.NameOverheadOptionFlags; - }; - - checkboxDict.Add(optionFlag, checkbox); - - checkBoxScroll.Add(checkbox); - } - - public NameOverheadOption Option { get; } - - private void UpdateValueInHotkeyBox() - { - if (Option == null || _hotkeyBox == null) - { - return; - } - - if (Option.Key != SDL.SDL_Keycode.SDLK_UNKNOWN) - { - SDL.SDL_Keymod mod = SDL.SDL_Keymod.KMOD_NONE; - - if (Option.Alt) - { - mod |= SDL.SDL_Keymod.KMOD_ALT; - } - - if (Option.Shift) - { - mod |= SDL.SDL_Keymod.KMOD_SHIFT; - } - - if (Option.Ctrl) - { - mod |= SDL.SDL_Keymod.KMOD_CTRL; - } - - _hotkeyBox.SetKey(Option.Key, mod); - } - } - - private void BoxOnHotkeyChanged(object sender, EventArgs e) - { - bool shift = (_hotkeyBox.Mod & SDL.SDL_Keymod.KMOD_SHIFT) != SDL.SDL_Keymod.KMOD_NONE; - bool alt = (_hotkeyBox.Mod & SDL.SDL_Keymod.KMOD_ALT) != SDL.SDL_Keymod.KMOD_NONE; - bool ctrl = (_hotkeyBox.Mod & SDL.SDL_Keymod.KMOD_CTRL) != SDL.SDL_Keymod.KMOD_NONE; - - if (_hotkeyBox.Key == SDL.SDL_Keycode.SDLK_UNKNOWN) - return; - - NameOverheadOption option = NameOverHeadManager.FindOptionByHotkey(_hotkeyBox.Key, alt, ctrl, shift); - - if (option == null) - { - Option.Key = _hotkeyBox.Key; - Option.Shift = shift; - Option.Alt = alt; - Option.Ctrl = ctrl; - - return; - } - - if (Option == option) - return; - - UpdateValueInHotkeyBox(); - UIManager.Add(new MessageBoxGump(250, 150, string.Format(ResGumps.ThisKeyCombinationAlreadyExists, option.Name), null)); - } - - private void BoxOnHotkeyCancelled(object sender, EventArgs e) - { - Option.Alt = Option.Ctrl = Option.Shift = false; - Option.Key = SDL.SDL_Keycode.SDLK_UNKNOWN; - } - - public override void OnButtonClick(int buttonID) - { - switch ((ButtonType)buttonID) - { - case ButtonType.CheckAll: - Option.NameOverheadOptionFlags = int.MaxValue; - UpdateCheckboxesByCurrentOptionFlags(); - - break; - - case ButtonType.UncheckAll: - Option.NameOverheadOptionFlags = 0x0; - UpdateCheckboxesByCurrentOptionFlags(); - - break; - } - } - - private void UpdateCheckboxesByCurrentOptionFlags() - { - foreach (var kvp in checkboxDict) - { - var flag = kvp.Key; - var checkbox = kvp.Value; - - checkbox.IsChecked = ((NameOverheadOptions)Option.NameOverheadOptionFlags).HasFlag(flag); - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/NiceButton.cs b/src/ClassicUO.Client/Game/UI/Controls/NiceButton.cs deleted file mode 100644 index 731b83469..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/NiceButton.cs +++ /dev/null @@ -1,184 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - public class NiceButton : HitBox - { - private readonly ButtonAction _action; - private readonly int _groupnumber; - private bool _isSelected; - - public bool DisplayBorder; - - public NiceButton - ( - int x, - int y, - int w, - int h, - ButtonAction action, - string text, - int groupnumber = 0, - TEXT_ALIGN_TYPE align = TEXT_ALIGN_TYPE.TS_CENTER, - ushort hue = 0xFFFF, - bool unicode = true, - byte font = 0xFF - ) : base(x, y, w, h) - { - _action = action; - - Add - ( - TextLabel = new Label - ( - text, - unicode, - hue, - w, - font, - FontStyle.BlackBorder | FontStyle.Cropped, - align - ) - ); - - TextLabel.Y = (h - TextLabel.Height) >> 1; - _groupnumber = groupnumber; - } - - internal Label TextLabel { get; } - - public int ButtonParameter { get; set; } - - public bool IsSelectable { get; set; } = true; - - public bool IsSelected - { - get => _isSelected && IsSelectable; - set - { - if (!IsSelectable) - { - return; - } - - _isSelected = value; - - if (value) - { - Control p = Parent; - - if (p == null) - { - return; - } - - IEnumerable list = p.FindControls(); - - foreach (NiceButton b in list) - { - if (b != this && b._groupnumber == _groupnumber) - { - b.IsSelected = false; - } - } - } - } - } - - internal static NiceButton GetSelected(Control p, int group) - { - IEnumerable list = p.FindControls(); - - foreach (NiceButton b in list) - { - if (b._groupnumber == group && b.IsSelected) - { - return b; - } - } - - return null; - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - IsSelected = true; - - if (_action == ButtonAction.SwitchPage) - { - ChangePage(ButtonParameter); - } - else - { - OnButtonClick(ButtonParameter); - } - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsSelected) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0, false, Alpha); - - batcher.Draw - ( - _texture, - new Vector2(x, y), - new Rectangle(0, 0, Width, Height), - hueVector - ); - } - - if (DisplayBorder) - { - batcher.DrawRectangle( - SolidColorTextureCache.GetTexture(Color.LightGray), - x, y, - Width, Height, - ShaderHueTranslator.GetHueVector(0, false, Alpha) - ); - } - - return base.Draw(batcher, x, y); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/PaperDollInteractable.cs b/src/ClassicUO.Client/Game/UI/Controls/PaperDollInteractable.cs deleted file mode 100644 index 0fc0ae119..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/PaperDollInteractable.cs +++ /dev/null @@ -1,558 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Gumps; -using ClassicUO.Input; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using Microsoft.Xna.Framework; -using System.Collections.Generic; - -namespace ClassicUO.Game.UI.Controls -{ - internal class PaperDollInteractable : Control - { - private static readonly Layer[] _layerOrder = - { - Layer.Cloak, - Layer.Shirt, - Layer.Pants, - Layer.Shoes, - Layer.Legs, - Layer.Arms, - Layer.Torso, - Layer.Tunic, - Layer.Ring, - Layer.Bracelet, - Layer.Face, - Layer.Gloves, - Layer.Skirt, - Layer.Robe, - Layer.Waist, - Layer.Necklace, - Layer.Hair, - Layer.Beard, - Layer.Earrings, - Layer.Helmet, - Layer.OneHanded, - Layer.TwoHanded, - Layer.Talisman - }; - - private static readonly Layer[] _layerOrder_quiver_fix = - { - Layer.Shirt, - Layer.Pants, - Layer.Shoes, - Layer.Legs, - Layer.Arms, - Layer.Torso, - Layer.Tunic, - Layer.Ring, - Layer.Bracelet, - Layer.Face, - Layer.Gloves, - Layer.Skirt, - Layer.Robe, - Layer.Cloak, - Layer.Waist, - Layer.Necklace, - Layer.Hair, - Layer.Beard, - Layer.Earrings, - Layer.Helmet, - Layer.OneHanded, - Layer.TwoHanded, - Layer.Talisman - }; - - private readonly PaperDollGump _paperDollGump; - - private bool _updateUI; - - public PaperDollInteractable(int x, int y, uint serial, PaperDollGump paperDollGump, double scale = 1f) - { - X = x; - Y = y; - _paperDollGump = paperDollGump; - AcceptMouseInput = false; - LocalSerial = serial; - _updateUI = true; - Scale = InternalScale = scale; - } - - public bool HasFakeItem { get; private set; } - - public override void Update() - { - base.Update(); - - if (_updateUI) - { - UpdateUI(); - - _updateUI = false; - } - } - - public void SetFakeItem(bool value) - { - _updateUI = HasFakeItem && !value || !HasFakeItem && value; - HasFakeItem = value; - } - - private void UpdateUI() - { - if (IsDisposed) - { - return; - } - - Mobile mobile = World.Mobiles.Get(LocalSerial); - - if (mobile == null || mobile.IsDestroyed) - { - Dispose(); - - return; - } - - Clear(); - - // Add the base gump - the semi-naked paper doll. - ushort body; - ushort hue = mobile.Hue; - - if (mobile.Graphic == 0x0191 || mobile.Graphic == 0x0193) - { - body = 0x000D; - } - else if (mobile.Graphic == 0x025D) - { - body = 0x000E; - } - else if (mobile.Graphic == 0x025E) - { - body = 0x000F; - } - else if (mobile.Graphic == 0x029A || mobile.Graphic == 0x02B6) - { - body = 0x029A; - } - else if (mobile.Graphic == 0x029B || mobile.Graphic == 0x02B7) - { - body = 0x0299; - } - else if (mobile.Graphic == 0x04E5) - { - body = 0xC835; - } - else if (mobile.Graphic == 0x03DB) - { - body = 0x000C; - hue = 0x03EA; - } - else if (mobile.IsFemale) - { - body = 0x000D; - } - else - { - body = 0x000C; - } - - // body - Add(new GumpPic(0, 0, body, hue) { IsPartialHue = true }.ScaleWidthAndHeight(Scale).SetInternalScale(Scale)); - - if (mobile.Graphic == 0x03DB) - { - Add( - new GumpPic(0, 0, 0xC72B, mobile.Hue) - { - AcceptMouseInput = true, - IsPartialHue = true - }.ScaleWidthAndHeight(Scale).SetInternalScale(Scale) - ); - } - - // equipment - Item equipItem = mobile.FindItemByLayer(Layer.Cloak); - Item arms = mobile.FindItemByLayer(Layer.Arms); - - bool switch_arms_with_torso = false; - - if (arms != null) - { - switch_arms_with_torso = arms.Graphic == 0x1410 || arms.Graphic == 0x1417; - } - else if ( - HasFakeItem - && Client.Game.GameCursor.ItemHold.Enabled - && !Client.Game.GameCursor.ItemHold.IsFixedPosition - && (byte)Layer.Arms == Client.Game.GameCursor.ItemHold.ItemData.Layer - ) - { - switch_arms_with_torso = - Client.Game.GameCursor.ItemHold.Graphic == 0x1410 - || Client.Game.GameCursor.ItemHold.Graphic == 0x1417; - } - - Layer[] layers; - - if (equipItem != null) - { - layers = equipItem.ItemData.IsContainer ? _layerOrder_quiver_fix : _layerOrder; - } - else if ( - HasFakeItem - && Client.Game.GameCursor.ItemHold.Enabled - && !Client.Game.GameCursor.ItemHold.IsFixedPosition - && (byte)Layer.Cloak == Client.Game.GameCursor.ItemHold.ItemData.Layer - ) - { - layers = Client.Game.GameCursor.ItemHold.ItemData.IsContainer - ? _layerOrder_quiver_fix - : _layerOrder; - } - else - { - layers = _layerOrder; - } - - for (int i = 0; i < layers.Length; i++) - { - Layer layer = layers[i]; - - if (switch_arms_with_torso) - { - if (layer == Layer.Arms) - { - layer = Layer.Torso; - } - else if (layer == Layer.Torso) - { - layer = Layer.Arms; - } - } - - equipItem = mobile.FindItemByLayer(layer); - - if (equipItem != null) - { - if (Mobile.IsCovered(mobile, layer)) - { - continue; - } - - ushort id = GetAnimID( - mobile.Graphic, - equipItem.ItemData.AnimID, - mobile.IsFemale - ); - Add( - new GumpPicEquipment( - equipItem.Serial, - 0, - 0, - id, - (ushort)(equipItem.Hue & 0x3FFF), - layer - ) - { - AcceptMouseInput = true, - IsPartialHue = equipItem.ItemData.IsPartialHue, - CanLift = - World.InGame - && !World.Player.IsDead - && layer != Layer.Beard - && layer != Layer.Hair - && ((_paperDollGump != null && _paperDollGump.CanLift) || (_paperDollGump != null && LocalSerial == World.Player)), - }.ScaleWidthAndHeight(Scale).SetInternalScale(InternalScale) - ); - } - else if ( - HasFakeItem - && Client.Game.GameCursor.ItemHold.Enabled - && !Client.Game.GameCursor.ItemHold.IsFixedPosition - && (byte)layer == Client.Game.GameCursor.ItemHold.ItemData.Layer - && Client.Game.GameCursor.ItemHold.ItemData.AnimID != 0 - ) - { - ushort id = GetAnimID( - mobile.Graphic, - Client.Game.GameCursor.ItemHold.ItemData.AnimID, - mobile.IsFemale - ); - - Add( - new GumpPicEquipment( - 0, - 0, - 0, - id, - (ushort)(Client.Game.GameCursor.ItemHold.Hue & 0x3FFF), - Client.Game.GameCursor.ItemHold.Layer - ) - { - AcceptMouseInput = true, - IsPartialHue = Client.Game.GameCursor.ItemHold.IsPartialHue, - Alpha = 0.5f - }.ScaleWidthAndHeight(Scale).SetInternalScale(InternalScale) - ); - } - } - - equipItem = mobile.FindItemByLayer(Layer.Backpack); - - if (equipItem != null && equipItem.ItemData.AnimID != 0 && _paperDollGump != null) - { - ushort backpackGraphic = (ushort)( - equipItem.ItemData.AnimID + Constants.MALE_GUMP_OFFSET - ); - - // If player, apply backpack skin - if (mobile.Serial == World.Player.Serial) - { - var gump = Client.Game.Gumps; - - switch (ProfileManager.CurrentProfile.BackpackStyle) - { - case 1: - if (gump.GetGump(0x777B).Texture != null) - { - backpackGraphic = 0x777B; // Suede Backpack - } - - break; - case 2: - if (gump.GetGump(0x777C).Texture != null) - { - backpackGraphic = 0x777C; // Polar Bear Backpack - } - - break; - case 3: - if (gump.GetGump(0x777D).Texture != null) - { - backpackGraphic = 0x777D; // Ghoul Skin Backpack - } - - break; - default: - if (gump.GetGump(0xC4F6).Texture != null) - { - backpackGraphic = 0xC4F6; // Default Backpack - } - - break; - } - } - - int bx = 0; - - if (World.ClientFeatures.PaperdollBooks) - { - bx = 6; - } - - Add( - new GumpPicEquipment( - equipItem.Serial, - -bx, - 0, - backpackGraphic, - (ushort)(equipItem.Hue & 0x3FFF), - Layer.Backpack - ) - { - AcceptMouseInput = true - }.ScaleWidthAndHeight(Scale).SetInternalScale(Scale) - ); - } - } - - public void RequestUpdate() - { - _updateUI = true; - } - - protected static ushort GetAnimID(ushort graphic, ushort animID, bool isfemale) - { - int offset = isfemale ? Constants.FEMALE_GUMP_OFFSET : Constants.MALE_GUMP_OFFSET; - - if ( - Client.Version >= ClientVersion.CV_7000 - && animID == 0x03CA // graphic for dead shroud - && (graphic == 0x02B7 || graphic == 0x02B6) - ) // dead gargoyle graphics - { - animID = 0x0223; - } - - Client.Game.Animations.ConvertBodyIfNeeded(ref graphic); - - if ( - AnimationsLoader.Instance.EquipConversions.TryGetValue( - graphic, - out Dictionary dict - ) - ) - { - if (dict.TryGetValue(animID, out EquipConvData data)) - { - if (data.Gump > Constants.MALE_GUMP_OFFSET) - { - animID = (ushort)( - data.Gump >= Constants.FEMALE_GUMP_OFFSET - ? data.Gump - Constants.FEMALE_GUMP_OFFSET - : data.Gump - Constants.MALE_GUMP_OFFSET - ); - } - else - { - animID = data.Gump; - } - } - } - - if ( - animID + offset > GumpsLoader.MAX_GUMP_DATA_INDEX_COUNT - || Client.Game.Gumps.GetGump((ushort)(animID + offset)).Texture == null - ) - { - // inverse - offset = isfemale ? Constants.MALE_GUMP_OFFSET : Constants.FEMALE_GUMP_OFFSET; - } - - if (Client.Game.Gumps.GetGump((ushort)(animID + offset)).Texture == null) - { - Log.Error( - $"Texture not found in paperdoll: gump_graphic: {(ushort)(animID + offset)}" - ); - } - - return (ushort)(animID + offset); - } - - protected class GumpPicEquipment : GumpPic - { - private readonly Layer _layer; - - public GumpPicEquipment( - uint serial, - int x, - int y, - ushort graphic, - ushort hue, - Layer layer - ) : base(x, y, graphic, hue) - { - LocalSerial = serial; - CanMove = false; - _layer = layer; - - if (SerialHelper.IsValid(serial) && World.InGame) - { - SetTooltip(serial); - } - } - - public bool CanLift { get; set; } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if (button != MouseButtonType.Left) - { - return false; - } - - // this check is necessary to avoid crashes during character creation - if (World.InGame) - { - GameActions.DoubleClick(LocalSerial); - } - - return true; - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - SelectedObject.Object = World.Get(LocalSerial); - base.OnMouseUp(x, y, button); - } - - public override void Update() - { - base.Update(); - - if (World.InGame) - { - if ( - CanLift - && !Client.Game.GameCursor.ItemHold.Enabled - && Mouse.LButtonPressed - && UIManager.LastControlMouseDown(MouseButtonType.Left) == this - && ( - Mouse.LastLeftButtonClickTime != 0xFFFF_FFFF - && Mouse.LastLeftButtonClickTime != 0 - && Mouse.LastLeftButtonClickTime + Mouse.MOUSE_DELAY_DOUBLE_CLICK - < Time.Ticks - || Mouse.LDragOffset != Point.Zero - ) - ) - { - GameActions.PickUp(LocalSerial, 0, 0); - - if (_layer == Layer.OneHanded || _layer == Layer.TwoHanded) - { - World.Player.UpdateAbilities(); - } - } - else if (MouseIsOver) - { - SelectedObject.Object = World.Get(LocalSerial); - } - } - } - - protected override void OnMouseOver(int x, int y) - { - SelectedObject.Object = World.Get(LocalSerial); - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/RadioButton.cs b/src/ClassicUO.Client/Game/UI/Controls/RadioButton.cs deleted file mode 100644 index ea473d30d..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/RadioButton.cs +++ /dev/null @@ -1,106 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using System.Linq; - -namespace ClassicUO.Game.UI.Controls -{ - public class RadioButton : Checkbox - { - public RadioButton(int group, List parts, string[] lines) : base(parts, lines) - { - GroupIndex = group; - IsFromServer = true; - } - - public RadioButton - ( - int group, - ushort inactive, - ushort active, - string text = "", - byte font = 0, - ushort color = 0, - bool isunicode = true, - int maxWidth = 0 - ) : base - ( - inactive, - active, - text, - font, - color, - isunicode, - maxWidth - ) - { - GroupIndex = group; - } - - public int GroupIndex { get; set; } - - protected override void OnCheckedChanged() - { - if (IsChecked) - { - if (HandleClick()) - { - base.OnCheckedChanged(); - } - } - } - - //protected override void OnMouseClick(int x, int y, MouseButton button) - //{ - // if (Parent?.FindControls().Any( s => s.GroupIndex == GroupIndex && s.IsChecked && s != this) == true) - // base.OnMouseClick(x, y, button); - //} - - private bool HandleClick() - { - IEnumerable en = Parent?.FindControls().Where(s => s.GroupIndex == GroupIndex && s != this); - - if (en == null) - { - return false; - } - - foreach (RadioButton button in en) - { - button.IsChecked = false; - } - - return true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/ResizableStaticPic.cs b/src/ClassicUO.Client/Game/UI/Controls/ResizableStaticPic.cs deleted file mode 100644 index 65e356d3e..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ResizableStaticPic.cs +++ /dev/null @@ -1,99 +0,0 @@ -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - public class ResizableStaticPic : Control - { - private uint graphic; - private ushort hue = 0; - private Vector3 hueVector { get; set; } = ShaderHueTranslator.GetHueVector(0, false, 1); - - public ushort Hue - { - get { return hue; } - set - { - hue = value; - hueVector = ShaderHueTranslator.GetHueVector(hue, false, 1); - } - } - public uint Graphic { get { return graphic; } set { graphic = value; } } - - public ResizableStaticPic(uint graphic, int width, int height) - { - this.graphic = graphic; - - Width = width; - Height = height; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - if (IsDisposed) - { - return false; - } - - ref readonly var texture = ref Client.Game.Arts.GetArt(graphic); - - Rectangle _rect = Client.Game.Arts.GetRealArtBounds(graphic); - - Point _originalSize = new Point(Width, Height); - Point _point = new Point((Width >> 1) - (_originalSize.X >> 1), (Height >> 1) - (_originalSize.Y >> 1)); - - if (_rect.Width < Width) - { - _originalSize.X = _rect.Width; - _point.X = (Width >> 1) - (_originalSize.X >> 1); - } - - if (_rect.Height < Height) - { - _originalSize.Y = _rect.Height; - _point.Y = (Height >> 1) - (_originalSize.Y >> 1); - } - - if (_rect.Width > Width) - { - _originalSize.X = Width; - _point.X = 0; - } - - if (_rect.Height > Height) - { - _originalSize.Y = Height; - _point.Y = 0; - } - - if (texture.Texture != null) - { - batcher.Draw - ( - texture.Texture, - new Rectangle - ( - x + _point.X, - y + _point.Y, - _originalSize.X, - _originalSize.Y - ), - new Rectangle - ( - texture.UV.X + _rect.X, - texture.UV.Y + _rect.Y, - _rect.Width, - _rect.Height - ), - hueVector - ); - - return true; - } - - return false; - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/ResizePic.cs b/src/ClassicUO.Client/Game/UI/Controls/ResizePic.cs deleted file mode 100644 index 477674f53..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ResizePic.cs +++ /dev/null @@ -1,436 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.UI.Controls -{ - public class ResizePic : Control - { - private int _maxIndex; - - public ResizePic(ushort graphic) - { - CanMove = true; - CanCloseWithRightClick = true; - Graphic = graphic; - - for (_maxIndex = 0; _maxIndex < 9; ++_maxIndex) - { - if (Client.Game.Gumps.GetGump((ushort)(Graphic + _maxIndex)).Texture == null) - { - break; - } - } - } - - public ResizePic(List parts) : this(UInt16Converter.Parse(parts[3])) - { - X = int.Parse(parts[1]); - Y = int.Parse(parts[2]); - Width = int.Parse(parts[4]); - Height = int.Parse(parts[5]); - IsFromServer = true; - } - - public ushort Graphic { get; } - - public override bool Contains(int x, int y) - { - x -= Offset.X; - y -= Offset.Y; - - var texture0 = GetTexture(0, out var bounds0); - var texture1 = GetTexture(1, out var bounds1); - var texture2 = GetTexture(2, out var bounds2); - var texture3 = GetTexture(3, out var bounds3); - var texture4 = GetTexture(4, out var bounds4); - var texture5 = GetTexture(5, out var bounds5); - var texture6 = GetTexture(6, out var bounds6); - var texture7 = GetTexture(7, out var bounds7); - var texture8 = GetTexture(8, out var bounds8); - - int offsetTop = Math.Max(bounds0.Height, bounds2.Height) - bounds1.Height; - int offsetBottom = Math.Max(bounds5.Height, bounds7.Height) - bounds6.Height; - int offsetLeft = Math.Abs(Math.Max(bounds0.Width, bounds5.Width) - bounds2.Width); - int offsetRight = Math.Max(bounds2.Width, bounds7.Width) - bounds4.Width; - - if (PixelsInXY(ref bounds0, Graphic, x, y)) - { - return true; - } - - int DW = Width - bounds0.Width - bounds2.Width; - - if (DW >= 1 && PixelsInXY(ref bounds1, (ushort)(Graphic + 1), x - bounds0.Width, y, DW)) - { - return true; - } - - if ( - PixelsInXY( - ref bounds2, - (ushort)(Graphic + 2), - x - (Width - bounds2.Width), - y - offsetTop - ) - ) - { - return true; - } - - int DH = Height - bounds0.Height - bounds5.Height; - - if ( - DH >= 1 - && PixelsInXY( - ref bounds3, - (ushort)(Graphic + 3), - x /*- offsetLeft*/ - , - y - bounds0.Height, - 0, - DH - ) - ) - { - return true; - } - - DH = Height - bounds2.Height - bounds7.Height; - - if ( - DH >= 1 - && PixelsInXY( - ref bounds4, - (ushort)(Graphic + 5), - x - - ( - Width - bounds4.Width /*- offsetRight*/ - ), - y - bounds2.Height, - 0, - DH - ) - ) - { - return true; - } - - if (PixelsInXY(ref bounds5, (ushort)(Graphic + 6), x, y - (Height - bounds5.Height))) - { - return true; - } - - DW = Width - bounds5.Width - bounds2.Width; - - if ( - DH >= 1 - && PixelsInXY( - ref bounds6, - (ushort)(Graphic + 7), - x - bounds5.Width, - y - (Height - bounds6.Height - offsetBottom), - DW - ) - ) - { - return true; - } - - if ( - PixelsInXY( - ref bounds7, - (ushort)(Graphic + 8), - x - (Width - bounds7.Width), - y - (Height - bounds7.Height) - ) - ) - { - return true; - } - - DW = Width - bounds0.Width - bounds2.Width; - DW += offsetLeft + offsetRight; - DH = Height - bounds2.Height - bounds7.Height; - - if ( - DW >= 1 - && DH >= 1 - && PixelsInXY( - ref bounds8, - (ushort)(Graphic + 4), - x - bounds0.Width, - y - bounds0.Height, - DW, - DH - ) - ) - { - return true; - } - - return false; - } - - private static bool PixelsInXY( - ref Rectangle bounds, - ushort graphic, - int x, - int y, - int width = 0, - int height = 0 - ) - { - if (x < 0 || y < 0 || width > 0 && x >= width || height > 0 && y >= height) - { - return false; - } - - if (bounds.Width == 0 || bounds.Height == 0) - { - return false; - } - - int textureWidth = bounds.Width; - int textureHeight = bounds.Height; - - if (width == 0) - { - width = textureWidth; - } - - if (height == 0) - { - height = textureHeight; - } - - while (x >= textureWidth && width >= textureWidth) - { - x -= textureWidth; - width -= textureWidth; - } - - if (x < 0 || x > width) - { - return false; - } - - while (y >= textureHeight && height >= textureHeight) - { - y -= textureHeight; - height -= textureHeight; - } - - if (y < 0 || y > height) - { - return false; - } - - return Client.Game.Gumps.PixelCheck(graphic, x, y); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (batcher.ClipBegin(x, y, Width, Height)) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0, false, Alpha, true); - - DrawInternal(batcher, x, y, hueVector); - base.Draw(batcher, x, y); - - batcher.ClipEnd(); - } - - return true; - } - - private void DrawInternal(UltimaBatcher2D batcher, int x, int y, Vector3 color) - { - var texture0 = GetTexture(0, out var bounds0); - var texture1 = GetTexture(1, out var bounds1); - var texture2 = GetTexture(2, out var bounds2); - var texture3 = GetTexture(3, out var bounds3); - var texture4 = GetTexture(4, out var bounds4); - var texture5 = GetTexture(5, out var bounds5); - var texture6 = GetTexture(6, out var bounds6); - var texture7 = GetTexture(7, out var bounds7); - var texture8 = GetTexture(8, out var bounds8); - - int offsetTop = Math.Max(bounds0.Height, bounds2.Height) - bounds1.Height; - int offsetBottom = Math.Max(bounds5.Height, bounds7.Height) - bounds6.Height; - int offsetLeft = Math.Abs(Math.Max(bounds0.Width, bounds5.Width) - bounds2.Width); - int offsetRight = Math.Max(bounds2.Width, bounds7.Width) - bounds4.Width; - - if (texture0 != null) - { - batcher.Draw(texture0, new Vector2(x, y), bounds0, color); - } - - if (texture1 != null) - { - batcher.DrawTiled( - texture1, - new Rectangle( - x + bounds0.Width, - y, - Width - bounds0.Width - bounds2.Width, - bounds1.Height - ), - bounds1, - color - ); - } - - if (texture2 != null) - { - batcher.Draw( - texture2, - new Vector2(x + (Width - bounds2.Width), y + offsetTop), - bounds2, - color - ); - } - - if (texture3 != null) - { - batcher.DrawTiled( - texture3, - new Rectangle( - x, - y + bounds0.Height, - bounds3.Width, - Height - bounds0.Height - bounds5.Height - ), - bounds3, - color - ); - } - - if (texture4 != null) - { - batcher.DrawTiled( - texture4, - new Rectangle( - x + (Width - bounds4.Width), - y + bounds2.Height, - bounds4.Width, - Height - bounds2.Height - bounds7.Height - ), - bounds4, - color - ); - } - - if (texture5 != null) - { - batcher.Draw( - texture5, - new Vector2(x, y + (Height - bounds5.Height)), - bounds5, - color - ); - } - - if (texture6 != null) - { - batcher.DrawTiled( - texture6, - new Rectangle( - x + bounds5.Width, - y + (Height - bounds6.Height - offsetBottom), - Width - bounds5.Width - bounds7.Width, - bounds6.Height - ), - bounds6, - color - ); - } - - if (texture7 != null) - { - batcher.Draw( - texture7, - new Vector2(x + (Width - bounds7.Width), y + (Height - bounds7.Height)), - bounds7, - color - ); - } - - if (texture8 != null) - { - batcher.DrawTiled( - texture8, - new Rectangle( - x + bounds0.Width, - y + bounds0.Height, - (Width - bounds0.Width - bounds2.Width) + (offsetLeft + offsetRight), - Height - bounds2.Height - bounds7.Height - ), - bounds8, - color - ); - } - } - - private Texture2D GetTexture(int index, out Rectangle bounds) - { - if (index >= 0 && index <= _maxIndex) - { - if (index >= 8) - { - index = 4; - } - else if (index >= 4) - { - ++index; - } - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump( - (ushort)(Graphic + index) - ); - - bounds = gumpInfo.UV; - return gumpInfo.Texture; - } - - bounds = Rectangle.Empty; - return null; - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/ScissorControl.cs b/src/ClassicUO.Client/Game/UI/Controls/ScissorControl.cs deleted file mode 100644 index 1b8ba7492..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ScissorControl.cs +++ /dev/null @@ -1,73 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Renderer; - -namespace ClassicUO.Game.UI.Controls -{ - public class ScissorControl : Control - { - public ScissorControl(bool enabled, int x, int y, int width, int height) : this(enabled) - { - X = x; - Y = y; - Width = width; - Height = height; - } - - public ScissorControl(bool enabled) - { - CanMove = false; - AcceptMouseInput = false; - AcceptKeyboardInput = false; - Alpha = 1.0f; - WantUpdateSize = false; - DoScissor = enabled; - } - - public bool DoScissor; - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (DoScissor) - { - batcher.ClipBegin(x, y, Width, Height); - } - else - { - batcher.ClipEnd(); - } - - return true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/ScrollArea.cs b/src/ClassicUO.Client/Game/UI/Controls/ScrollArea.cs deleted file mode 100644 index 45571a8eb..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ScrollArea.cs +++ /dev/null @@ -1,252 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Input; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - public enum ScrollbarBehaviour - { - ShowWhenDataExceedFromView, - ShowAlways - } - - public class ScrollArea : Control - { - private bool _isNormalScroll; - private readonly ScrollBarBase _scrollBar; - - public ScrollArea - ( - int x, - int y, - int w, - int h, - bool normalScrollbar, - int scroll_max_height = -1 - ) - { - X = x; - Y = y; - Width = w; - Height = h; - _isNormalScroll = normalScrollbar; - - if (normalScrollbar) - { - _scrollBar = new ScrollBar(Width - 14, 0, Height); - } - else - { - _scrollBar = new ScrollFlag - { - X = Width - 19, Height = h - }; - - Width += 15; - } - - ScrollMaxHeight = scroll_max_height; - - _scrollBar.MinValue = 0; - _scrollBar.MaxValue = scroll_max_height >= 0 ? scroll_max_height : Height; - _scrollBar.Parent = this; - - AcceptMouseInput = true; - WantUpdateSize = false; - CanMove = true; - ScrollbarBehaviour = ScrollbarBehaviour.ShowWhenDataExceedFromView; - } - - - public int ScrollMaxHeight { get; set; } = -1; - public ScrollbarBehaviour ScrollbarBehaviour { get; set; } - public int ScrollValue => _scrollBar.Value; - public int ScrollMinValue => _scrollBar.MinValue; - public int ScrollMaxValue => _scrollBar.MaxValue; - - - public Rectangle ScissorRectangle; - - - public override void Update() - { - base.Update(); - - CalculateScrollBarMaxValue(); - - if (ScrollbarBehaviour == ScrollbarBehaviour.ShowAlways) - { - _scrollBar.IsVisible = true; - } - else if (ScrollbarBehaviour == ScrollbarBehaviour.ShowWhenDataExceedFromView) - { - _scrollBar.IsVisible = _scrollBar.MaxValue > _scrollBar.MinValue; - } - } - - public int ScrollBarWidth() - { - if (_scrollBar == null) - return 0; - return _scrollBar.Width; - } - - public void Scroll(bool isup) - { - if (isup) - { - _scrollBar.Value -= _scrollBar.ScrollStep; - } - else - { - _scrollBar.Value += _scrollBar.ScrollStep; - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - ScrollBarBase scrollbar = (ScrollBarBase) Children[0]; - scrollbar.Draw(batcher, x + scrollbar.X, y + scrollbar.Y); - - if (batcher.ClipBegin(x + ScissorRectangle.X, y + ScissorRectangle.Y, Width - 14 + ScissorRectangle.Width, Height + ScissorRectangle.Height)) - { - for (int i = 1; i < Children.Count; i++) - { - Control child = Children[i]; - - if (!child.IsVisible) - { - continue; - } - - int finalY = y + child.Y - scrollbar.Value + ScissorRectangle.Y; - - child.Draw(batcher, x + child.X, finalY); - } - - batcher.ClipEnd(); - } - - return true; - } - - - protected override void OnMouseWheel(MouseEventType delta) - { - switch (delta) - { - case MouseEventType.WheelScrollUp: - _scrollBar.Value -= _scrollBar.ScrollStep; - - break; - - case MouseEventType.WheelScrollDown: - _scrollBar.Value += _scrollBar.ScrollStep; - - break; - } - } - - public override void Clear() - { - for (int i = 1; i < Children.Count; i++) - { - Children[i].Dispose(); - } - } - - private void CalculateScrollBarMaxValue() - { - _scrollBar.Height = ScrollMaxHeight >= 0 ? ScrollMaxHeight : Height; - bool maxValue = _scrollBar.Value == _scrollBar.MaxValue && _scrollBar.MaxValue != 0; - - int startX = 0, startY = 0, endX = 0, endY = 0; - - for (int i = 1; i < Children.Count; i++) - { - Control c = Children[i]; - - if (c.IsVisible && !c.IsDisposed) - { - if (c.X < startX) - { - startX = c.X; - } - - if (c.Y < startY) - { - startY = c.Y; - } - - if (c.Bounds.Right > endX) - { - endX = c.Bounds.Right; - } - - if (c.Bounds.Bottom > endY) - { - endY = c.Bounds.Bottom; - } - } - } - - int width = Math.Abs(startX) + Math.Abs(endX); - int height = Math.Abs(startY) + Math.Abs(endY) - _scrollBar.Height; - height = Math.Max(0, height - (-ScissorRectangle.Y + ScissorRectangle.Height)); - - if (height > 0) - { - _scrollBar.MaxValue = height; - - if (maxValue) - { - _scrollBar.Value = _scrollBar.MaxValue; - } - } - else - { - _scrollBar.Value = _scrollBar.MaxValue = 0; - } - - _scrollBar.UpdateOffset(0, Offset.Y); - - for (int i = 1; i < Children.Count; i++) - { - Children[i].UpdateOffset(0, -_scrollBar.Value + ScissorRectangle.Y); - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/ScrollBar.cs b/src/ClassicUO.Client/Game/UI/Controls/ScrollBar.cs deleted file mode 100644 index 4560c37b6..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ScrollBar.cs +++ /dev/null @@ -1,283 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - internal class ScrollBar : ScrollBarBase - { - private Rectangle _rectSlider, - _emptySpace; - - const ushort BUTTON_UP_0 = 251; - const ushort BUTTON_UP_1 = 250; - const ushort BUTTON_DOWN_0 = 253; - const ushort BUTTON_DOWN_1 = 252; - const ushort BACKGROUND_0 = 257; - const ushort BACKGROUND_1 = 256; - const ushort BACKGROUND_2 = 255; - const ushort SLIDER = 254; - - public ScrollBar(int x, int y, int height) - { - Height = height; - Location = new Point(x, y); - AcceptMouseInput = true; - - ref readonly var gumpInfoUp = ref Client.Game.Gumps.GetGump(BUTTON_UP_0); - ref readonly var gumpInfoDown = ref Client.Game.Gumps.GetGump(BUTTON_DOWN_0); - ref readonly var gumpInfoBackground = ref Client.Game.Gumps.GetGump(BACKGROUND_0); - ref readonly var gumpInfoSlider = ref Client.Game.Gumps.GetGump(SLIDER); - - Width = gumpInfoBackground.UV.Width; - - _rectDownButton = new Rectangle( - 0, - Height - gumpInfoDown.UV.Height, - gumpInfoDown.UV.Width, - gumpInfoDown.UV.Height - ); - _rectUpButton = new Rectangle(0, 0, gumpInfoUp.UV.Width, gumpInfoUp.UV.Height); - _rectSlider = new Rectangle( - (gumpInfoBackground.UV.Width - gumpInfoSlider.UV.Width) >> 1, - gumpInfoUp.UV.Height + _sliderPosition, - gumpInfoSlider.UV.Width, - gumpInfoSlider.UV.Height - ); - _emptySpace.X = 0; - _emptySpace.Y = gumpInfoUp.UV.Height; - _emptySpace.Width = gumpInfoSlider.UV.Width; - _emptySpace.Height = Height - (gumpInfoDown.UV.Height + gumpInfoUp.UV.Height); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (Height <= 0 || !IsVisible) - { - return false; - } - - var hueVector = ShaderHueTranslator.GetHueVector(0); - - ref readonly var gumpInfoUp0 = ref Client.Game.Gumps.GetGump(BUTTON_UP_0); - ref readonly var gumpInfoUp1 = ref Client.Game.Gumps.GetGump(BUTTON_UP_1); - ref readonly var gumpInfoDown0 = ref Client.Game.Gumps.GetGump(BUTTON_DOWN_0); - ref readonly var gumpInfoDown1 = ref Client.Game.Gumps.GetGump(BUTTON_DOWN_1); - ref readonly var gumpInfoBackground0 = ref Client.Game.Gumps.GetGump(BACKGROUND_0); - ref readonly var gumpInfoBackground1 = ref Client.Game.Gumps.GetGump(BACKGROUND_1); - ref readonly var gumpInfoBackground2 = ref Client.Game.Gumps.GetGump(BACKGROUND_2); - ref readonly var gumpInfoSlider = ref Client.Game.Gumps.GetGump(SLIDER); - - // draw scrollbar background - int middleHeight = - Height - - gumpInfoUp0.UV.Height - - gumpInfoDown0.UV.Height - - gumpInfoBackground0.UV.Height - - gumpInfoBackground2.UV.Height; - - if (middleHeight > 0) - { - batcher.Draw( - gumpInfoBackground0.Texture, - new Vector2(x, y + gumpInfoUp0.UV.Height), - gumpInfoBackground0.UV, - hueVector - ); - - batcher.DrawTiled( - gumpInfoBackground1.Texture, - new Rectangle( - x, - y + gumpInfoUp1.UV.Height + gumpInfoBackground0.UV.Height, - gumpInfoBackground0.UV.Width, - middleHeight - ), - gumpInfoBackground1.UV, - hueVector - ); - - batcher.Draw( - gumpInfoBackground2.Texture, - new Vector2( - x, - y + Height - gumpInfoDown0.UV.Height - gumpInfoBackground2.UV.Height - ), - gumpInfoBackground2.UV, - hueVector - ); - } - else - { - middleHeight = Height - gumpInfoUp0.UV.Height - gumpInfoDown0.UV.Height; - - batcher.DrawTiled( - gumpInfoBackground1.Texture, - new Rectangle( - x, - y + gumpInfoUp0.UV.Height, - gumpInfoBackground0.UV.Width, - middleHeight - ), - gumpInfoBackground1.UV, - hueVector - ); - } - - // draw up button - if (_btUpClicked) - { - batcher.Draw(gumpInfoUp1.Texture, new Vector2(x, y), gumpInfoUp1.UV, hueVector); - } - else - { - batcher.Draw(gumpInfoUp0.Texture, new Vector2(x, y), gumpInfoUp0.UV, hueVector); - } - - // draw down button - if (_btDownClicked) - { - batcher.Draw( - gumpInfoDown1.Texture, - new Vector2(x, y + Height - gumpInfoDown0.UV.Height), - gumpInfoDown1.UV, - hueVector - ); - } - else - { - batcher.Draw( - gumpInfoDown0.Texture, - new Vector2(x, y + Height - gumpInfoDown0.UV.Height), - gumpInfoDown0.UV, - hueVector - ); - } - - // draw slider - if (MaxValue > MinValue && middleHeight > 0) - { - batcher.Draw( - gumpInfoSlider.Texture, - new Vector2( - x + ((gumpInfoBackground0.UV.Width - gumpInfoSlider.UV.Width) >> 1), - y + gumpInfoUp0.UV.Height + _sliderPosition - ), - gumpInfoSlider.UV, - hueVector - ); - } - - return base.Draw(batcher, x, y); - } - - protected override int GetScrollableArea() - { - ref readonly var gumpInfoUp = ref Client.Game.Gumps.GetGump(BUTTON_UP_0); - ref readonly var gumpInfoDown = ref Client.Game.Gumps.GetGump(BUTTON_DOWN_0); - ref readonly var gumpInfoSlider = ref Client.Game.Gumps.GetGump(SLIDER); - - return Height - - gumpInfoUp.UV.Height - - gumpInfoDown.UV.Height - - gumpInfoSlider.UV.Height; - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - base.OnMouseDown(x, y, button); - - if (_btnSliderClicked && _emptySpace.Contains(x, y)) - { - CalculateByPosition(x, y); - } - } - - protected override void CalculateByPosition(int x, int y) - { - if (y != _clickPosition.Y) - { - y -= _emptySpace.Y + (_rectSlider.Height >> 1); - - if (y < 0) - { - y = 0; - } - - int scrollableArea = GetScrollableArea(); - - if (y > scrollableArea) - { - y = scrollableArea; - } - - _sliderPosition = y; - _clickPosition.X = x; - _clickPosition.Y = y; - - ref readonly var gumpInfoUp = ref Client.Game.Gumps.GetGump(BUTTON_UP_0); - ref readonly var gumpInfoDown = ref Client.Game.Gumps.GetGump(BUTTON_DOWN_0); - ref readonly var gumpInfoSlider = ref Client.Game.Gumps.GetGump(SLIDER); - - if ( - y == 0 - && _clickPosition.Y < gumpInfoUp.UV.Height + (gumpInfoSlider.UV.Height >> 1) - ) - { - _clickPosition.Y = gumpInfoUp.UV.Height + (gumpInfoSlider.UV.Height >> 1); - } - else if ( - y == scrollableArea - && _clickPosition.Y - > Height - gumpInfoDown.UV.Height - (gumpInfoSlider.UV.Height >> 1) - ) - { - _clickPosition.Y = - Height - gumpInfoDown.UV.Height - (gumpInfoSlider.UV.Height >> 1); - } - - _value = (int) - Math.Round(y / (float)scrollableArea * (MaxValue - MinValue) + MinValue); - } - } - - public override bool Contains(int x, int y) - { - return x >= 0 && x <= Width && y >= 0 && y <= Height; - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/ScrollBarBase.cs b/src/ClassicUO.Client/Game/UI/Controls/ScrollBarBase.cs deleted file mode 100644 index e17b68298..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ScrollBarBase.cs +++ /dev/null @@ -1,245 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Input; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - internal abstract class ScrollBarBase : Control - { - private const int TIME_BETWEEN_CLICKS = 2; - - private float _timeUntilNextClick; - - protected bool _btUpClicked, _btDownClicked, _btnSliderClicked, _btSliderClicked; - protected Point _clickPosition; - protected Rectangle _rectUpButton, _rectDownButton; - protected int _sliderPosition; - - - public int Value - { - get => _value; - set - { - if (_value == value) - { - return; - } - - _value = value; - - if (_value < MinValue) - { - _value = MinValue; - } - else if (_value > MaxValue) - { - _value = MaxValue; - } - - ValueChanged.Raise(); - } - } - - public int MinValue - { - get => _minValue; - set - { - if (_minValue == value) - { - return; - } - - _minValue = value; - - if (_value < _minValue) - { - _value = _minValue; - } - } - } - - public int MaxValue - { - get => _maxValue; - set - { - if (_maxValue == value) - { - return; - } - - if (value < 0) - { - _maxValue = 0; - } - else - { - _maxValue = value; - } - - if (_value > _maxValue) - { - _value = _maxValue; - } - } - } - - public int ScrollStep { get; set; } = 50; - protected int _value, _minValue, _maxValue; - - - public event EventHandler ValueChanged; - - - public override void Update() - { - base.Update(); - - if (_btnSliderClicked) - { - int x = Mouse.Position.X - X - ParentX; - int y = Mouse.Position.Y - Y - ParentY; - - CalculateByPosition(x, y); - } - - if (MaxValue <= MinValue) - { - Value = MaxValue = MinValue; - } - - _sliderPosition = GetSliderYPosition(); - - //_rectSlider.Y = _textureUpButton[0].Height + _sliderPosition; - - if (_btUpClicked || _btDownClicked) - { - if (_timeUntilNextClick < Time.Ticks) - { - _timeUntilNextClick = Time.Ticks + TIME_BETWEEN_CLICKS; - - if (_btUpClicked) - { - Value -= 1 + _StepChanger; - } - else if (_btDownClicked) - { - Value += 1 + _StepChanger; - } - - _StepsDone++; - - if (_StepsDone % 8 == 0) - { - _StepChanger++; - } - } - } - } - - protected override void OnMouseWheel(MouseEventType delta) - { - switch (delta) - { - case MouseEventType.WheelScrollUp: - Value -= ScrollStep; - - break; - - case MouseEventType.WheelScrollDown: - Value += ScrollStep; - - break; - } - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - if (button != MouseButtonType.Left) - { - return; - } - - _timeUntilNextClick = 0f; - _btnSliderClicked = false; - - if (_rectDownButton.Contains(x, y)) - { - _btDownClicked = true; - } - else if (_rectUpButton.Contains(x, y)) - { - _btUpClicked = true; - } - else if (Contains(x, y)) - { - _btnSliderClicked = true; - - CalculateByPosition(x, y); - } - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button != MouseButtonType.Left) - { - return; - } - - _btDownClicked = false; - _btUpClicked = false; - _btnSliderClicked = false; - _StepChanger = _StepsDone = 1; - } - - protected int GetSliderYPosition() - { - if (MaxValue == MinValue) - { - return 0; - } - - return (int) Math.Round(GetScrollableArea() * ((Value - MinValue) / (float) (MaxValue - MinValue))); - } - - - protected abstract int GetScrollableArea(); - - protected abstract void CalculateByPosition(int x, int y); - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/ScrollFlag.cs b/src/ClassicUO.Client/Game/UI/Controls/ScrollFlag.cs deleted file mode 100644 index 511ff57d9..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/ScrollFlag.cs +++ /dev/null @@ -1,190 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - internal class ScrollFlag : ScrollBarBase - { - private readonly bool _showButtons; - - const ushort BUTTON_UP = 0x0824; - const ushort BUTTON_DOWN = 0x0825; - const ushort BUTTON_FLAG = 0x0828; - - public ScrollFlag(int x, int y, int height, bool showbuttons) : this() - { - X = x; - Y = y; - Height = height; - - //TODO: - _showButtons = false; // showbuttons; - } - - public ScrollFlag() - { - AcceptMouseInput = true; - - ref readonly var gumpInfoFlag = ref Client.Game.Gumps.GetGump(BUTTON_FLAG); - - if (gumpInfoFlag.Texture == null) - { - Dispose(); - - return; - } - - ref readonly var gumpInfoUp = ref Client.Game.Gumps.GetGump(BUTTON_UP); - ref readonly var gumpInfoDown = ref Client.Game.Gumps.GetGump(BUTTON_DOWN); - - Width = gumpInfoFlag.UV.Width; - Height = gumpInfoFlag.UV.Height; - - _rectUpButton = new Rectangle(0, 0, gumpInfoUp.UV.Width, gumpInfoUp.UV.Height); - _rectDownButton = new Rectangle( - 0, - Height, - gumpInfoDown.UV.Width, - gumpInfoDown.UV.Height - ); - - WantUpdateSize = false; - } - - public override ClickPriority Priority { get; set; } = ClickPriority.High; - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - var hueVector = ShaderHueTranslator.GetHueVector(0); - - ref readonly var gumpInfoFlag = ref Client.Game.Gumps.GetGump(BUTTON_FLAG); - ref readonly var gumpInfoUp = ref Client.Game.Gumps.GetGump(BUTTON_UP); - ref readonly var gumpInfoDown = ref Client.Game.Gumps.GetGump(BUTTON_DOWN); - - if (MaxValue != MinValue && gumpInfoFlag.Texture != null) - { - batcher.Draw( - gumpInfoFlag.Texture, - new Vector2(x, y + _sliderPosition), - gumpInfoFlag.UV, - hueVector - ); - } - - if (_showButtons) - { - if (gumpInfoUp.Texture != null) - { - batcher.Draw(gumpInfoUp.Texture, new Vector2(x, y), gumpInfoUp.UV, hueVector); - } - - if (gumpInfoDown.Texture != null) - { - batcher.Draw( - gumpInfoDown.Texture, - new Vector2(x, y + Height), - gumpInfoDown.UV, - hueVector - ); - } - } - - return base.Draw(batcher, x, y); - } - - protected override int GetScrollableArea() - { - ref readonly var gumpInfoFlag = ref Client.Game.Gumps.GetGump(BUTTON_FLAG); - - return Height - gumpInfoFlag.UV.Height; - } - - protected override void CalculateByPosition(int x, int y) - { - if (y != _clickPosition.Y) - { - ref readonly var gumpInfoFlag = ref Client.Game.Gumps.GetGump(BUTTON_FLAG); - int height = gumpInfoFlag.UV.Height; - - y -= (height >> 1); - - if (y < 0) - { - y = 0; - } - - int scrollableArea = GetScrollableArea(); - - if (y > scrollableArea) - { - y = scrollableArea; - } - - _sliderPosition = y; - _clickPosition.X = x; - _clickPosition.Y = y; - - if (y == 0 && _clickPosition.Y < height >> 1) - { - _clickPosition.Y = height >> 1; - } - else if (y == scrollableArea && _clickPosition.Y > Height - (height >> 1)) - { - _clickPosition.Y = Height - (height >> 1); - } - - _value = (int) - Math.Round(y / (float)scrollableArea * (MaxValue - MinValue) + MinValue); - } - } - - public override bool Contains(int x, int y) - { - ref readonly var gumpInfoFlag = ref Client.Game.Gumps.GetGump(BUTTON_FLAG); - - if (gumpInfoFlag.Texture == null) - { - return false; - } - - y -= _sliderPosition; - - return Client.Game.Gumps.PixelCheck(BUTTON_FLAG, x, y); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/SimpleBorder.cs b/src/ClassicUO.Client/Game/UI/Controls/SimpleBorder.cs deleted file mode 100644 index 45912aa0a..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/SimpleBorder.cs +++ /dev/null @@ -1,34 +0,0 @@ -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - internal class SimpleBorder : Control - { - public ushort Hue = 0; - - private int _width = 0, _height = 0; - - //Return 0 so this control has a 0, 0 size to not interfere with hitboxes - public int Width { get { return 0; } set { _width = value; } } - public int Height { get { return 0; } set { _height = value; } } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsDisposed) - return false; - base.Draw(batcher, x, y); - - var huevec = ShaderHueTranslator.GetHueVector(Hue, false, Alpha); - - batcher.DrawRectangle( - SolidColorTextureCache.GetTexture(Color.White), - x, y, - _width, _height, - huevec - ); - - return true; - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/StaticPic.cs b/src/ClassicUO.Client/Game/UI/Controls/StaticPic.cs deleted file mode 100644 index 8527b4309..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/StaticPic.cs +++ /dev/null @@ -1,114 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Controls -{ - public class StaticPic : Control - { - private ushort _graphic; - - public StaticPic(ushort graphic, ushort hue) - { - Hue = hue; - Graphic = graphic; - CanMove = true; - WantUpdateSize = false; - } - - public StaticPic(List parts) - : this( - UInt16Converter.Parse(parts[3]), - parts.Count > 4 ? UInt16Converter.Parse(parts[4]) : (ushort)0 - ) - { - X = int.Parse(parts[1]); - Y = int.Parse(parts[2]); - IsFromServer = true; - } - - public ushort Hue { get; set; } - public bool IsPartialHue { get; set; } - - public ushort Graphic - { - get => _graphic; - set - { - _graphic = value; - - ref readonly var artInfo = ref Client.Game.Arts.GetArt(value); - - if (artInfo.Texture == null) - { - Dispose(); - - return; - } - - Width = artInfo.UV.Width; - Height = artInfo.UV.Height; - - IsPartialHue = TileDataLoader.Instance.StaticData[value].IsPartialHue; - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(Hue, IsPartialHue, 1); - - ref readonly var artInfo = ref Client.Game.Arts.GetArt(Graphic); - - if (artInfo.Texture != null) - { - batcher.Draw( - artInfo.Texture, - new Rectangle(x, y, Width, Height), - artInfo.UV, - hueVector - ); - } - - return base.Draw(batcher, x, y); - } - - public override bool Contains(int x, int y) - { - return Client.Game.Arts.PixelCheck(Graphic, x - Offset.X, y - Offset.Y); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Controls/StbTextBox.cs b/src/ClassicUO.Client/Game/UI/Controls/StbTextBox.cs deleted file mode 100644 index 132799555..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/StbTextBox.cs +++ /dev/null @@ -1,1074 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using ClassicUO.Game.Managers; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using Microsoft.Xna.Framework; -using SDL2; -using StbTextEditSharp; - -namespace ClassicUO.Game.UI.Controls -{ - public class StbTextBox : Control, ITextEditHandler - { - protected static readonly Color SELECTION_COLOR = new Color() { PackedValue = 0x80a06020 }; - private readonly FontStyle _fontStyle; - - private readonly int _maxCharCount = -1; - - - public StbTextBox - ( - byte font, - int max_char_count = -1, - int maxWidth = 0, - bool isunicode = true, - FontStyle style = FontStyle.None, - ushort hue = 0, - TEXT_ALIGN_TYPE align = 0 - ) - { - AcceptKeyboardInput = true; - AcceptMouseInput = true; - CanMove = false; - IsEditable = true; - - _maxCharCount = max_char_count; - - Stb = new TextEdit(this); - Stb.SingleLine = true; - - if (maxWidth > 0) - { - style |= FontStyle.CropTexture; - } - - _fontStyle = style; - - if ((style & (FontStyle.Fixed | FontStyle.Cropped)) != 0 && maxWidth <= 0) - { - Debug.Assert((style & (FontStyle.Fixed | FontStyle.Cropped)) != 0 && maxWidth <= 0); - } - - // stb_textedit will handle part of these tag - style &= ~( /*FontStyle.Fixed | */FontStyle.Cropped | FontStyle.CropTexture); - - _rendererText = RenderedText.Create - ( - string.Empty, - hue, - font, - isunicode, - style, - align, - maxWidth - ); - - _rendererCaret = RenderedText.Create - ( - "_", - hue, - font, - isunicode, - (style & FontStyle.BlackBorder) != 0 ? FontStyle.BlackBorder : FontStyle.None, - align - ); - - Height = _rendererCaret.Height; - LoseFocusOnEscapeKey = true; - } - - public StbTextBox(List parts, string[] lines) : this - ( - 1, - parts[0] == "textentrylimited" ? int.Parse(parts[8]) : byte.MaxValue, - int.Parse(parts[3]), - style: FontStyle.BlackBorder | FontStyle.CropTexture, - hue: (ushort) (UInt16Converter.Parse(parts[5]) + 1) - ) - { - X = int.Parse(parts[1]); - Y = int.Parse(parts[2]); - Width = _rendererText.MaxWidth; //int.Parse(parts[3]); - Height = _rendererText.MaxHeight = int.Parse(parts[4]); - Multiline = false; - _fromServer = true; - LocalSerial = SerialHelper.Parse(parts[6]); - IsFromServer = true; - - int index = int.Parse(parts[7]); - - if (index >= 0 && index < lines.Length) - { - SetText(lines[index]); - } - } - - protected TextEdit Stb { get; } - - - public override bool AcceptKeyboardInput => base.AcceptKeyboardInput && IsEditable; - - public byte Font - { - get => _rendererText.Font; - set - { - if (_rendererText.Font != value) - { - _rendererText.Font = value; - _rendererText.CreateTexture(); - _rendererCaret.Font = value; - _rendererCaret.CreateTexture(); - - UpdateCaretScreenPosition(); - } - } - } - - public bool AllowTAB { get; set; } - public bool NoSelection { get; set; } - - public bool LoseFocusOnEscapeKey { get; set; } - - public int CaretIndex - { - get => Stb.CursorIndex; - set - { - Stb.CursorIndex = value; - UpdateCaretScreenPosition(); - } - } - - public bool Multiline - { - get => !Stb.SingleLine; - set => Stb.SingleLine = !value; - } - - public bool NumbersOnly { get; set; } - - public int SelectionStart - { - get => Stb.SelectStart; - set - { - if (AllowSelection) - { - Stb.SelectStart = value; - } - } - } - - public int SelectionEnd - { - get => Stb.SelectEnd; - set - { - if (AllowSelection) - { - Stb.SelectEnd = value; - } - } - } - - public bool AllowSelection { get; set; } = true; - - public bool IsUnicode => _rendererText.IsUnicode; - - public ushort Hue - { - get => _rendererText.Hue; - set - { - if (_rendererText.Hue != value) - { - _rendererText.Hue = value; - _rendererCaret.Hue = value; - - _rendererText.CreateTexture(); - _rendererCaret.CreateTexture(); - } - } - } - - internal int TotalHeight - { - get - { - int h = 20; - MultilinesFontInfo info = GetInfo(); - - while (info != null) - { - h += info.MaxHeight; - info = info.Next; - } - - return h; - } - } - - public string Text - { - get => _rendererText.Text; - - set - { - if (_maxCharCount > 0) - { - if (NumbersOnly) - { - - } - if (value != null && value.Length > _maxCharCount) - { - value = value.Substring(0, _maxCharCount); - } - } - - //Sanitize(ref value); - - _rendererText.Text = value; - - if (!_is_writing) - { - OnTextChanged(); - } - } - } - - public int Length => Text?.Length ?? 0; - - public float GetWidth(int index) - { - return _rendererText.GetCharWidthAtIndex(index); - } - - public TextEditRow LayoutRow(int startIndex) - { - TextEditRow r = _rendererText.GetLayoutRow(startIndex); - - int sx = ScreenCoordinateX; - int sy = ScreenCoordinateY; - - r.x0 += sx; - r.x1 += sx; - r.ymin += sy; - r.ymax += sy; - - return r; - } - - protected Point _caretScreenPosition; - protected bool _is_writing; - protected bool _leftWasDown, _fromServer; - protected RenderedText _rendererText, _rendererCaret; - - public event EventHandler TextChanged; - - public MultilinesFontInfo CalculateFontInfo(string text, bool countret = true) - { - if (IsUnicode) - { - return FontsLoader.Instance.GetInfoUnicode - ( - _rendererText.Font, - text, - text.Length, - _rendererText.Align, - (ushort) _rendererText.FontStyle, - _rendererText.MaxWidth, - countret - ); - } - - return FontsLoader.Instance.GetInfoASCII - ( - _rendererText.Font, - text, - text.Length, - _rendererText.Align, - (ushort) _rendererText.FontStyle, - _rendererText.MaxWidth, - countret - ); - } - - public void SelectAll() - { - if (AllowSelection) - { - Stb.SelectStart = 0; - Stb.SelectEnd = Length; - } - } - - protected void UpdateCaretScreenPosition() - { - _caretScreenPosition = _rendererText.GetCaretPosition(Stb.CursorIndex); - } - - private ControlKeys ApplyShiftIfNecessary(ControlKeys k) - { - if (Keyboard.Shift && !NoSelection) - { - k |= ControlKeys.Shift; - } - - return k; - } - - private bool IsMaxCharReached(int count) - { - return _maxCharCount >= 0 && Length + count >= _maxCharCount; - } - - private void Sanitize(ref string text) - { - if ((_fontStyle & FontStyle.Fixed) != 0 || (_fontStyle & FontStyle.Cropped) != 0 || (_fontStyle & FontStyle.CropTexture) != 0) - { - if (_rendererText.MaxWidth == 0) - { - Log.Warn("maxwidth must be setted."); - - return; - } - - if (string.IsNullOrEmpty(text)) - { - return; - } - - - int realWidth = _rendererText.IsUnicode ? FontsLoader.Instance.GetWidthUnicode(_rendererText.Font, text) : FontsLoader.Instance.GetWidthASCII(_rendererText.Font, text); - - if (realWidth > _rendererText.MaxWidth) - { - if ((_fontStyle & FontStyle.Fixed) != 0) - { - text = Text; - Stb.CursorIndex = Math.Max(0, text.Length - 1); - - return; - } - - //MultilinesFontInfo info = _rendererText.IsUnicode - // ? FontsLoader.Instance.GetInfoUnicode( - // _rendererText.Font, - // text, - // text.Length, - // _rendererText.Align, - // (ushort) _rendererText.FontStyle, - // realWidth - // ) - // : FontsLoader.Instance.GetInfoASCII( - // _rendererText.Font, - // text, - // text.Length, - // _rendererText.Align, - // (ushort) _rendererText.FontStyle, - // realWidth - // ); - - - if ((_fontStyle & FontStyle.CropTexture) != 0) - { - //string sb = text; - //int total_height = 0; - //int start = 0; - - //while (info != null) - //{ - // total_height += info.MaxHeight; - - // if (total_height >= Height) - // { - // if (Text != null && Text.Length <= text.Length) - // text = Text; - - // _stb.CursorIndex = Math.Max(0, text.Length - 1); - // return; - // } - - // uint count = info.Data.Count; - - // //if (_stb.CursorIndex >= start && _stb.CursorIndex <= start + info.CharCount) - // { - // int pixel_width = 0; - - // for (int i = 0; i < count; i++) - // { - // pixel_width += _rendererText.GetCharWidth(info.Data[i].Item); - - // if (pixel_width >= _rendererText.MaxWidth) - // { - // sb = sb.Insert(start + i, "\n"); - // _stb.CursorIndex = start + i + 1; - // pixel_width = 0; - // } - // } - // } - - // start += (int) count; - // info = info.Next; - //} - - //text = sb.ToString(); - } - - if ((_fontStyle & FontStyle.Cropped) != 0) - { - } - } - } - } - - - protected virtual void OnTextChanged() - { - TextChanged?.Raise(this); - - UpdateCaretScreenPosition(); - } - - protected MultilinesFontInfo GetInfo() - { - return _rendererText.GetInfo(); - } - - internal override void OnFocusEnter() - { - base.OnFocusEnter(); - CaretIndex = Text?.Length ?? 0; - } - - internal override void OnFocusLost() - { - if (Stb != null) - { - Stb.SelectStart = Stb.SelectEnd = 0; - } - - base.OnFocusLost(); - } - - protected override void OnKeyDown(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - ControlKeys? stb_key = null; - bool update_caret = false; - - switch (key) - { - case SDL.SDL_Keycode.SDLK_TAB: - if (AllowTAB) - { - // UO does not support '\t' char in its fonts - OnTextInput(" "); - } - else - { - Parent?.KeyboardTabToNextFocus(this); - } - - break; - - case SDL.SDL_Keycode.SDLK_a when Keyboard.Ctrl && !NoSelection: - SelectAll(); - - break; - - case SDL.SDL_Keycode.SDLK_ESCAPE: - if (LoseFocusOnEscapeKey && SelectionStart == SelectionEnd) - { - UIManager.KeyboardFocusControl = null; - } - SelectionStart = 0; - SelectionEnd = 0; - break; - - case SDL.SDL_Keycode.SDLK_INSERT when IsEditable: - stb_key = ControlKeys.InsertMode; - - break; - - case SDL.SDL_Keycode.SDLK_c when Keyboard.Ctrl && !NoSelection: - int selectStart = Math.Min(Stb.SelectStart, Stb.SelectEnd); - int selectEnd = Math.Max(Stb.SelectStart, Stb.SelectEnd); - - if (selectStart < selectEnd && selectStart >= 0 && selectEnd - selectStart <= Text.Length) - { - SDL.SDL_SetClipboardText(Text.Substring(selectStart, selectEnd - selectStart)); - } - - break; - - case SDL.SDL_Keycode.SDLK_x when Keyboard.Ctrl && !NoSelection: - selectStart = Math.Min(Stb.SelectStart, Stb.SelectEnd); - selectEnd = Math.Max(Stb.SelectStart, Stb.SelectEnd); - - if (selectStart < selectEnd && selectStart >= 0 && selectEnd - selectStart <= Text.Length) - { - SDL.SDL_SetClipboardText(Text.Substring(selectStart, selectEnd - selectStart)); - - if (IsEditable) - { - Stb.Cut(); - } - } - - break; - - case SDL.SDL_Keycode.SDLK_v when Keyboard.Ctrl && IsEditable: - OnTextInput(StringHelper.GetClipboardText(Multiline)); - - break; - - case SDL.SDL_Keycode.SDLK_z when Keyboard.Ctrl && IsEditable: - stb_key = ControlKeys.Undo; - - break; - - case SDL.SDL_Keycode.SDLK_y when Keyboard.Ctrl && IsEditable: - stb_key = ControlKeys.Redo; - - break; - - case SDL.SDL_Keycode.SDLK_LEFT: - if (Keyboard.Ctrl && Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.WordLeft; - } - } - else if (Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.Left; - } - } - else if (Keyboard.Ctrl) - { - stb_key = ControlKeys.WordLeft; - } - else - { - stb_key = ControlKeys.Left; - } - - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_RIGHT: - if (Keyboard.Ctrl && Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.WordRight; - } - } - else if (Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.Right; - } - } - else if (Keyboard.Ctrl) - { - stb_key = ControlKeys.WordRight; - } - else - { - stb_key = ControlKeys.Right; - } - - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_UP: - stb_key = ApplyShiftIfNecessary(ControlKeys.Up); - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_DOWN: - stb_key = ApplyShiftIfNecessary(ControlKeys.Down); - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_BACKSPACE when IsEditable: - stb_key = ApplyShiftIfNecessary(ControlKeys.BackSpace); - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_DELETE when IsEditable: - stb_key = ApplyShiftIfNecessary(ControlKeys.Delete); - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_HOME: - if (Keyboard.Ctrl && Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.TextStart; - } - } - else if (Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.LineStart; - } - } - else if (Keyboard.Ctrl) - { - stb_key = ControlKeys.TextStart; - } - else - { - stb_key = ControlKeys.LineStart; - } - - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_END: - if (Keyboard.Ctrl && Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.TextEnd; - } - } - else if (Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.LineEnd; - } - } - else if (Keyboard.Ctrl) - { - stb_key = ControlKeys.TextEnd; - } - else - { - stb_key = ControlKeys.LineEnd; - } - - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_KP_ENTER: - case SDL.SDL_Keycode.SDLK_RETURN: - if (IsEditable) - { - if (Multiline) - { - if (!_fromServer && !IsMaxCharReached(0)) - { - OnTextInput("\n"); - } - } - else - { - Parent?.OnKeyboardReturn(0, Text); - - if (UIManager.SystemChat != null && UIManager.SystemChat.TextBoxControl != null && IsFocused) - { - if (!IsFromServer || !UIManager.SystemChat.TextBoxControl.IsVisible) - { - OnFocusLost(); - OnFocusEnter(); - } - else if (UIManager.KeyboardFocusControl == null || UIManager.KeyboardFocusControl != UIManager.SystemChat.TextBoxControl) - { - UIManager.SystemChat.TextBoxControl.SetKeyboardFocus(); - } - } - } - } - - break; - } - - if (stb_key != null) - { - Stb.Key(stb_key.Value); - } - - if (update_caret) - { - UpdateCaretScreenPosition(); - } - - base.OnKeyDown(key, mod); - } - - public void SetText(string text) - { - if (string.IsNullOrEmpty(text)) - { - ClearText(); - } - else - { - if (_maxCharCount > 0) - { - if (NumbersOnly) - { - // TODO ? - } - else if (text.Length > _maxCharCount) - { - text = text.Substring(0, _maxCharCount); - } - } - - Stb.ClearState(!Multiline); - Text = text; - - Stb.CursorIndex = Length; - - if (!_is_writing) - { - OnTextChanged(); - } - } - } - - public void ClearText() - { - if (Length != 0) - { - SelectionStart = 0; - SelectionEnd = 0; - Stb.Delete(0, Length); - - if (!_is_writing) - { - OnTextChanged(); - } - } - } - - public void AppendText(string text) - { - Stb.Paste(text); - } - - - protected override void OnTextInput(string c) - { - if (c == null || !IsEditable) - { - return; - } - - _is_writing = true; - - if (SelectionStart != SelectionEnd) - { - Stb.DeleteSelection(); - } - - int count; - - if (_maxCharCount > 0) - { - int remains = _maxCharCount - Length; - - if (remains <= 0) - { - _is_writing = false; - - return; - } - - count = Math.Min(remains, c.Length); - - if (remains < c.Length && count > 0) - { - c = c.Substring(0, count); - } - } - else - { - count = c.Length; - } - - if (count > 0) - { - if (NumbersOnly) - { - for (int i = 0; i < count; i++) - { - if (!char.IsNumber(c[i])) - { - _is_writing = false; - - return; - } - } - - if (_maxCharCount > 0 && int.TryParse(Stb.text + c, out int val)) - { - if (val > _maxCharCount) - { - _is_writing = false; - SetText(_maxCharCount.ToString()); - - return; - } - } - } - - - if (count > 1) - { - Stb.Paste(c); - OnTextChanged(); - } - else if (_rendererText.GetCharWidth(c[0]) > 0 || c[0] == '\n') - { - Stb.InputChar(c[0]); - OnTextChanged(); - } - } - - _is_writing = false; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (batcher.ClipBegin(x, y, Width, Height)) - { - base.Draw(batcher, x, y); - DrawSelection(batcher, x, y); - _rendererText.Draw(batcher, x, y); - DrawCaret(batcher, x, y); - - batcher.ClipEnd(); - } - - return true; - } - - private protected void DrawSelection(UltimaBatcher2D batcher, int x, int y) - { - if (!AllowSelection) - { - return; - } - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0, false, 0.5f); - - int selectStart = Math.Min(Stb.SelectStart, Stb.SelectEnd); - int selectEnd = Math.Max(Stb.SelectStart, Stb.SelectEnd); - - if (selectStart < selectEnd) - { - MultilinesFontInfo info = _rendererText.GetInfo(); - - int drawY = 1; - int start = 0; - int diffX = _rendererText.Align != TEXT_ALIGN_TYPE.TS_LEFT ? _rendererText.GetCaretPosition(0).X - 1 : 0; - - while (info != null && selectStart < selectEnd) - { - // ok we are inside the selection - if (selectStart >= start && selectStart < start + info.CharCount) - { - int startSelectionIndex = selectStart - start; - - // calculate offset x - int drawX = 0; - - for (int i = 0; i < startSelectionIndex; i++) - { - drawX += _rendererText.GetCharWidth(info.Data[i].Item); - } - - // selection is gone. Bye bye - if (selectEnd >= start && selectEnd < start + info.CharCount) - { - int count = selectEnd - selectStart; - - int endX = 0; - - // calculate width - for (int k = 0; k < count; k++) - { - endX += _rendererText.GetCharWidth(info.Data[startSelectionIndex + k].Item); - } - - batcher.Draw - ( - SolidColorTextureCache.GetTexture(SELECTION_COLOR), - new Rectangle - ( - x + drawX + diffX, - y + drawY, - endX, - info.MaxHeight + 1 - ), - hueVector - ); - - break; - } - - - // do the whole line - batcher.Draw - ( - SolidColorTextureCache.GetTexture(SELECTION_COLOR), - new Rectangle - ( - x + drawX + diffX, - y + drawY, - info.Width - drawX, - info.MaxHeight + 1 - ), - hueVector - ); - - // first selection is gone. M - selectStart = start + info.CharCount; - } - - start += info.CharCount; - drawY += info.MaxHeight; - info = info.Next; - } - } - } - - protected virtual void DrawCaret(UltimaBatcher2D batcher, int x, int y) - { - if (HasKeyboardFocus) - { - _rendererCaret.Draw(batcher, x + _caretScreenPosition.X, y + _caretScreenPosition.Y); - } - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left && IsEditable) - { - if (!NoSelection) - { - _leftWasDown = true; - } - - Stb.Click(Mouse.Position.X, Mouse.Position.Y); - UpdateCaretScreenPosition(); - } - - base.OnMouseDown(x, y, button); - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - _leftWasDown = false; - } - - base.OnMouseUp(x, y, button); - } - - protected override void OnMouseOver(int x, int y) - { - base.OnMouseOver(x, y); - - if (!_leftWasDown) - { - return; - } - - Stb.Drag(Mouse.Position.X, Mouse.Position.Y); - } - - public override void Dispose() - { - _rendererText?.Destroy(); - _rendererCaret?.Destroy(); - - base.Dispose(); - } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if (!NoSelection && CaretIndex < Text.Length && CaretIndex >= 0 && !char.IsWhiteSpace(Text[CaretIndex])) - { - int idx = CaretIndex; - - if (idx - 1 >= 0 && char.IsWhiteSpace(Text[idx - 1])) - { - ++idx; - } - - SelectionStart = Stb.MoveToPreviousWord(idx); - SelectionEnd = Stb.MoveToNextWord(idx); - - if (SelectionEnd < Text.Length) - { - --SelectionEnd; - } - - return true; - } - - return base.OnMouseDoubleClick(x, y, button); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Controls/TextBox.cs b/src/ClassicUO.Client/Game/UI/Controls/TextBox.cs deleted file mode 100644 index 8c3c74786..000000000 --- a/src/ClassicUO.Client/Game/UI/Controls/TextBox.cs +++ /dev/null @@ -1,343 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Renderer; -using FontStashSharp.RichText; -using Microsoft.Xna.Framework; -using System; -using System.Text.RegularExpressions; - -namespace ClassicUO.Game.UI.Controls -{ - public class TextBox : Control - { - private RichTextLayout _rtl; - private string _font; - private float _size; - private Color _color; - private TextHorizontalAlignment _align; - private bool _dirty = false; - - private int getStrokeSize - { - get - { - if (ProfileManager.CurrentProfile != null) - return ProfileManager.CurrentProfile.TextBorderSize; - return 2; - } - } - - public TextBox - ( - string text, - string font, - float size, - int? width, - int hue = 2996, - TextHorizontalAlignment align = TextHorizontalAlignment.Left, - bool strokeEffect = true, - bool supportsCommands = true, - bool ignoreColorCommands = false, - bool calculateGlyphs = false - ) - { - if (strokeEffect) - text = $"/es[{getStrokeSize}]" + text; - - _rtl = new RichTextLayout - { - Font = TrueTypeLoader.Instance.GetFont(font, size), - Text = text, - IgnoreColorCommand = ignoreColorCommands, - SupportsCommands = supportsCommands, - CalculateGlyphs = calculateGlyphs - }; - - if (width != null) - _rtl.Width = width; - - _font = font; - _size = size; - _color.PackedValue = HuesLoader.Instance.GetHueColorRgba8888(31, (ushort)hue); - - if (hue == 0xFFFF || hue == ushort.MaxValue) - _color = Color.White; - - _align = align; - - AcceptMouseInput = true; - Width = _rtl.Width == null ? _rtl.Size.X : (int)_rtl.Width; - base.Height = _rtl.Size.Y; - } - public TextBox - ( - string text, - string font, - float size, - int? width, - Color color, - TextHorizontalAlignment align = TextHorizontalAlignment.Left, - bool strokeEffect = true, - bool supportsCommands = true, - bool ignoreColorCommands = false, - bool calculateGlyphs = false - ) - { - if (strokeEffect) - text = $"/es[{getStrokeSize}]" + text; - - _rtl = new RichTextLayout - { - Font = TrueTypeLoader.Instance.GetFont(font, size), - Text = text, - IgnoreColorCommand = ignoreColorCommands, - SupportsCommands = supportsCommands, - CalculateGlyphs = calculateGlyphs, - }; - if (width != null) - _rtl.Width = width; - - _font = font; - _size = size; - _color = color; - - _align = align; - - AcceptMouseInput = true; - Width = _rtl.Width == null ? _rtl.Size.X : (int)_rtl.Width; - base.Height = _rtl.Size.Y; - } - - public bool PixelCheck(int x, int y) - { - if (!AcceptMouseInput || string.IsNullOrWhiteSpace(Text)) - { - return false; - } - - if (x < 0 || x >= Width) - { - return false; - } - - if (y < 0 || y >= Height) - { - return false; - } - - return true; - } - - public new int Height - { - get - { - if (_rtl == null) - return 0; - - return _rtl.Size.Y; - } - } - - public Point MeasuredSize - { - get - { - if (_rtl == null) - return Point.Zero; - return _rtl.Size; - } - } - - public string Text - { - get => _rtl.Text; - set - { - if (_rtl.Text != value) - { - _rtl.Text = value; - _dirty = true; - } - } - } - - public int Hue - { - get => (int)_color.PackedValue; - set - { - _color.PackedValue = HuesLoader.Instance.GetHueColorRgba8888(31, (ushort)value); - _dirty = true; - } - } - - public Color Fontcolor - { - get => _color; - set - { - _color = value; - _dirty = true; - } - } - - public RichTextLayout RTL => _rtl; - - public string Font - { - get => _font; - set - { - _font = value; - _dirty = true; - } - - } - - public float Size - { - get => _size; - set - { - _size = value; - _dirty = true; - } - } - - /// - /// Update the text of the TextBox - /// - /// New string - /// Set to null to ignore width, taking as much width as needed. - public void UpdateText(string text, int? width = null) - { - - if (width != null && width > 0) - { - _rtl = new RichTextLayout - { - Font = TrueTypeLoader.Instance.GetFont(_font, _size), - Text = text, - Width = width - }; - } - else - { - _rtl = new RichTextLayout - { - Font = TrueTypeLoader.Instance.GetFont(_font, _size), - Text = text, - }; - Width = _rtl.Size.X; - } - } - - public static string ConvertHtmlToFontStashSharpCommand(string text) - { - string finalString; - - if (String.IsNullOrEmpty(text)) - return ""; - - finalString = Regex.Replace(text, ".*?)\"?'?>", " /c[${color}]", RegexOptions.Multiline | RegexOptions.IgnoreCase); - finalString = Regex.Replace(finalString, ".*?)\"?'?>", " /c[${color}]", RegexOptions.Multiline | RegexOptions.IgnoreCase); - finalString = finalString.Replace("", "/cd").Replace("", "/cd").Replace("
", "\n").Replace("
", "\n").Replace("\n", "\n/cd"); - finalString = finalString.Replace("", "").Replace("", ""); - finalString = finalString.Replace("", "").Replace("", ""); - finalString = finalString.Replace("", "").Replace("

", ""); - finalString = finalString.Replace("", "").Replace("", ""); - finalString = finalString.Replace("", "").Replace("", ""); - return finalString; - } - - public override void Update() - { - if (Width != _rtl.Width || _dirty || WantUpdateSize) - { - var text = _rtl.Text; - - if (WantUpdateSize) - { - _rtl = new RichTextLayout - { - Font = TrueTypeLoader.Instance.GetFont(_font, _size), - Text = text, - }; - } - else - { - _rtl = new RichTextLayout - { - Font = TrueTypeLoader.Instance.GetFont(_font, _size), - Text = text, - Width = Width, - }; - } - - WantUpdateSize = false; - _dirty = false; - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - return Draw(batcher, x, y, _color); - } - - public bool Draw(UltimaBatcher2D batcher, int x, int y, Color color) - { - if (IsDisposed) - { - return false; - } - - if (_align == TextHorizontalAlignment.Center) - { - x += Width / 2; - } - else if (_align == TextHorizontalAlignment.Right) - { - x += Width; - } - - _rtl.Draw(batcher, new Vector2(x, y), color * Alpha, horizontalAlignment: _align); - - return true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/AnchorableGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/AnchorableGump.cs deleted file mode 100644 index 5e9e71687..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/AnchorableGump.cs +++ /dev/null @@ -1,258 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Game.Managers; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.UI.Gumps -{ - public enum ANCHOR_TYPE - { - NONE, - SPELL, - HEALTHBAR, - DISABLED - } - - public abstract class AnchorableGump : Gump - { - private AnchorableGump _anchorCandidate; - - //private GumpPic _lockGumpPic; - private int _prevX, - _prevY; - - const ushort LOCK_GRAPHIC = 0x082C; - - protected AnchorableGump(uint local, uint server) : base(local, server) { } - - public ANCHOR_TYPE AnchorType { get; set; } - public virtual int GroupMatrixWidth { get; protected set; } - public virtual int GroupMatrixHeight { get; protected set; } - public int WidthMultiplier { get; protected set; } = 1; - public int HeightMultiplier { get; protected set; } = 1; - - public bool ShowLock => Keyboard.Alt && UIManager.AnchorManager[this] != null; - - protected override void OnMove(int x, int y) - { - if (Keyboard.Alt && !ProfileManager.CurrentProfile.HoldAltToMoveGumps) - { - UIManager.AnchorManager.DetachControl(this); - } - else - { - UIManager.AnchorManager[this]?.UpdateLocation(this, X - _prevX, Y - _prevY); - } - - _prevX = X; - _prevY = Y; - - base.OnMove(x, y); - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - UIManager.AnchorManager[this]?.MakeTopMost(); - - _prevX = X; - _prevY = Y; - - base.OnMouseDown(x, y, button); - } - - protected override void OnMouseOver(int x, int y) - { - if (!IsDisposed && UIManager.IsDragging && UIManager.DraggingControl == this && AnchorType != ANCHOR_TYPE.DISABLED) - { - _anchorCandidate = UIManager.AnchorManager.GetAnchorableControlUnder(this); - } - - base.OnMouseOver(x, y); - } - - protected override void OnDragEnd(int x, int y) - { - Attache(); - - base.OnDragEnd(x, y); - } - - public void TryAttacheToExist() - { - _anchorCandidate = UIManager.AnchorManager.GetAnchorableControlUnder(this); - - Attache(); - } - - private void Attache() - { - if (_anchorCandidate != null) - { - Location = UIManager.AnchorManager.GetCandidateDropLocation(this, _anchorCandidate); - UIManager.AnchorManager.DropControl(this, _anchorCandidate); - _anchorCandidate = null; - } - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left && ShowLock) - { - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(LOCK_GRAPHIC); - if (gumpInfo.Texture != null) - { - if ( - x >= Width - gumpInfo.UV.Width - && x < Width - && y >= 0 - && y <= gumpInfo.UV.Height - ) - { - UIManager.AnchorManager.DetachControl(this); - } - } - } - - base.OnMouseUp(x, y, button); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - Vector3 hueVector; - - if (ShowLock) - { - hueVector = ShaderHueTranslator.GetHueVector(0); - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(LOCK_GRAPHIC); - - if (gumpInfo.Texture != null) - { - if ( - UIManager.MouseOverControl != null - && ( - UIManager.MouseOverControl == this - || UIManager.MouseOverControl.RootParent == this - ) - ) - { - hueVector.X = 34; - hueVector.Y = 1; - } - - batcher.Draw( - gumpInfo.Texture, - new Vector2(x + (Width - gumpInfo.UV.Width), y), - gumpInfo.UV, - hueVector - ); - } - } - - hueVector = ShaderHueTranslator.GetHueVector(0); - - if (_anchorCandidate != null) - { - Point drawLoc = UIManager.AnchorManager.GetCandidateDropLocation( - this, - _anchorCandidate - ); - - if (drawLoc != Location) - { - Texture2D previewColor = SolidColorTextureCache.GetTexture(Color.Silver); - hueVector = ShaderHueTranslator.GetHueVector(0, false, 0.5f); - - batcher.Draw( - previewColor, - new Rectangle(drawLoc.X, drawLoc.Y, Width, Height), - hueVector - ); - - hueVector.Z = 1f; - - // double rectangle for thicker "stroke" - batcher.DrawRectangle( - previewColor, - drawLoc.X, - drawLoc.Y, - Width, - Height, - hueVector - ); - - batcher.DrawRectangle( - previewColor, - drawLoc.X + 1, - drawLoc.Y + 1, - Width - 2, - Height - 2, - hueVector - ); - } - } - - return true; - } - - protected override void CloseWithRightClick() - { - if ( - UIManager.AnchorManager[this] == null - || Keyboard.Alt - || !ProfileManager.CurrentProfile.HoldDownKeyAltToCloseAnchored - ) - { - if (ProfileManager.CurrentProfile.CloseAllAnchoredGumpsInGroupWithRightClick) - { - UIManager.AnchorManager.DisposeAllControls(this); - } - - base.CloseWithRightClick(); - } - } - - public override void Dispose() - { - UIManager.AnchorManager.DetachControl(this); - - base.Dispose(); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/AutoLootOptions.cs b/src/ClassicUO.Client/Game/UI/Gumps/AutoLootOptions.cs deleted file mode 100644 index 6a1995c3b..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/AutoLootOptions.cs +++ /dev/null @@ -1,134 +0,0 @@ -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using Microsoft.Xna.Framework; -using System.Globalization; -using static ClassicUO.Game.Managers.AutoLootManager; -using static ClassicUO.Game.UI.Gumps.OptionsGump; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class AutoLootOptions : Gump - { - public AutoLootOptions() : base(0, 0) - { - if (!AutoLootManager.Instance.IsLoaded) - { - Dispose(); - return; - } - - Width = 400; - Height = 600; - X = 100; - Y = 100; - - CanMove = true; - CanCloseWithRightClick = true; - - BuildGump(); - } - - private void BuildGump() - { - Add(new AlphaBlendControl(0.85f) { Width = Width, Height = Height }); - - SettingsSection topSecion = new SettingsSection("Simple Auto Loot", Width); - - topSecion.Add(new TextBox("Enable auto loot", TrueTypeLoader.EMBEDDED_FONT, 18, null, Color.White, strokeEffect: false) { AcceptMouseInput = true }); - - Checkbox enable; - topSecion.AddRight(enable = new Checkbox(0x00D2, 0x00D3, "", 0xff, 0xffff) { IsChecked = ProfileManager.CurrentProfile.EnableAutoLoot }); - enable.ValueChanged += (e, v) => { ProfileManager.CurrentProfile.EnableAutoLoot = enable.IsChecked; }; - - NiceButton addEntry; - topSecion.AddRight(addEntry = new NiceButton(0, 0, 100, 25, ButtonAction.Activate, "Add entry") { IsSelectable = false }); - addEntry.MouseUp += (e, v) => - { - AutoLootManager.Instance.AddLootItem(); - AddToUI(); - }; - - Add(topSecion); - - ScrollArea entries = new ScrollArea(0, topSecion.Y + topSecion.Height, Width, Height - topSecion.Y + topSecion.Height + 15, true); - SettingsSection entriesSection = new SettingsSection("Loot entries", Width) { Y = topSecion.Y + topSecion.Height + 15 }; - entries.Add(entriesSection); - - BuildEntries(entriesSection); - - Add(entries); - } - - private void BuildEntries(SettingsSection parent) - { - for (int i = 0; i < AutoLootManager.Instance.AutoLootList.Count; i++) - { - AutoLootItem autoLootItem = AutoLootManager.Instance.AutoLootList[i]; - Area area = new Area() { Width = Width - 18, Height = 50 }; - - int x = 0; - if (autoLootItem.Graphic > 0) - { - ResizableStaticPic rsp; - area.Add(rsp = new ResizableStaticPic(autoLootItem.Graphic, 50, 50) { Hue = (ushort)(autoLootItem.Hue == ushort.MaxValue ? 0 : autoLootItem.Hue) }); - rsp.SetTooltip(autoLootItem.Name); - x += 55; - } - - InputField graphicInput = new InputField(0x0BB8, 0xFF, 0xFFF, true, 100, 50) { X = x }; - graphicInput.SetText(autoLootItem.Graphic.ToString()); - graphicInput.TextChanged += (s, e) => - { - if (graphicInput.Text.StartsWith("0x") && ushort.TryParse(graphicInput.Text.Substring(2), NumberStyles.AllowHexSpecifier, null, out var ngh)) - { - autoLootItem.Graphic = ngh; - } - else if (ushort.TryParse(graphicInput.Text, out var ng)) - { - autoLootItem.Graphic = ng; - } - }; - area.Add(graphicInput); - x += graphicInput.Width + 5; - - InputField hueInput = new InputField(0x0BB8, 0xFF, 0xFFF, true, 100, 50) { X = x }; - hueInput.SetText(autoLootItem.Hue == ushort.MaxValue ? "-1" : autoLootItem.Hue.ToString()); - hueInput.TextChanged += (s, e) => - { - if (hueInput.Text == "-1") - { - autoLootItem.Hue = ushort.MaxValue; - } - else if (ushort.TryParse(hueInput.Text, out var ng)) - { - autoLootItem.Hue = ng; - } - }; - area.Add(hueInput); - x += hueInput.Width + 5; - - NiceButton delete; - area.Add(delete = new NiceButton(x, 0, 100, 49, ButtonAction.Activate, "Delete") { IsSelectable = false, DisplayBorder = true }); - delete.MouseUp += (s, e) => - { - if (e.Button == Input.MouseButtonType.Left) - { - AutoLootManager.Instance.TryRemoveLootItem(autoLootItem.UID); - AddToUI(); - } - }; - x += delete.Width + 5; - - parent.Add(area); - } - } - - public static void AddToUI() - { - UIManager.GetGump()?.Dispose(); //Make sure only one is open at a time. - UIManager.Add(new AutoLootOptions()); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/BoatControl.cs b/src/ClassicUO.Client/Game/UI/Gumps/BoatControl.cs deleted file mode 100644 index 5d4add66c..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/BoatControl.cs +++ /dev/null @@ -1,156 +0,0 @@ -using ClassicUO.Game.UI.Controls; -using static System.Net.Mime.MediaTypeNames; -using System.Drawing; -using ClassicUO.Game.Managers; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class BoatControl : Gump - { - Checkbox reg, slow, one; - - public BoatControl() : base(0, 0) - { - Width = 200; - Height = 250; - CanCloseWithRightClick = true; - CanMove = true; - - BorderControl bc; - Add(bc = new BorderControl(0, 0, Width, Height, 10)); - bc.T_Left = 9270; - bc.H_Border = (ushort)(bc.T_Left + 1); - bc.T_Right = (ushort)(bc.T_Left + 2); - bc.V_Border = (ushort)(bc.T_Left + 3); - - bc.V_Right_Border = (ushort)(bc.T_Left + 5); - bc.B_Left = (ushort)(bc.T_Left + 6); - bc.H_Bottom_Border = (ushort)(bc.T_Left + 7); - bc.B_Right = (ushort)(bc.T_Left + 8); - - Add(new GumpPicTiled((ushort)(bc.T_Left + 4)) { X = 10, Y = 10, Width = Width - 20, Height = Height - 20 }); - - - - - GumpPic _; - - Add(_ = new GumpPic(10, 10, 4507, 0)); //West - _.MouseUp += (s, e) => { if (CheckDrivingBoat()) BoatMovingManager.MoveRequest(Data.Direction.West, Speed()); }; - - Add(_ = new GumpPic(75, 10, 4500, 0)); //NW - _.MouseUp += (s, e) => { if (CheckDrivingBoat()) BoatMovingManager.MoveRequest(Data.Direction.Up, Speed()); }; - - Add(_ = new GumpPic(140, 10, 4501, 0)); //North - _.MouseUp += (s, e) => { if (CheckDrivingBoat()) BoatMovingManager.MoveRequest(Data.Direction.North, Speed()); }; - - Add(_ = new GumpPic(10, 70, 4506, 0)); //SW - _.MouseUp += (s, e) => { if (CheckDrivingBoat()) BoatMovingManager.MoveRequest(Data.Direction.Left, Speed()); }; - - Add(_ = new GumpPic((Width / 2) - (29 / 2), 90, 5830, 0)); //Center stop button - _.MouseUp += (s, e) => { if (CheckDrivingBoat()) BoatMovingManager.MoveRequest(Data.Direction.Left, 0); }; - - Add(_ = new GumpPic(140, 70, 4502, 0)); //NE - _.MouseUp += (s, e) => { if (CheckDrivingBoat()) BoatMovingManager.MoveRequest(Data.Direction.Right, Speed()); }; - - Add(_ = new GumpPic(10, 140, 4505, 0)); //South - _.MouseUp += (s, e) => { if (CheckDrivingBoat()) BoatMovingManager.MoveRequest(Data.Direction.South, Speed()); }; - - Add(_ = new GumpPic(75, 140, 4504, 0)); //SE - _.MouseUp += (s, e) => { if (CheckDrivingBoat()) BoatMovingManager.MoveRequest(Data.Direction.Down, Speed()); }; - - Add(_ = new GumpPic(140, 140, 4503, 0)); // East - _.MouseUp += (s, e) => { if (CheckDrivingBoat()) BoatMovingManager.MoveRequest(Data.Direction.East, Speed()); }; - - - //Add(_ = new GumpPic(10, 190, 22406, 0)); //Rotate Clockwise - //Add(_ = new GumpPic(Width - 10 - 19, 190, 22400, 0)); //Rotate counter-clockwise - - Add(reg = new Checkbox - ( - 0x00D2, - 0x00D3, - "Reg", - 0xff, - 0xffff - ) - { - IsChecked = true, - X = 10, - Y = Height - 30 - }); - reg.MouseUp += Reg_MouseUp; - - Add(slow = new Checkbox - ( - 0x00D2, - 0x00D3, - "Slow", - 0xff, - 0xffff - ) - { - IsChecked = false, - Y = Height - 30 - }); - slow.X = (Width / 2) - (slow.Width / 2); - slow.MouseUp += Reg_MouseUp; - - Add(one = new Checkbox - ( - 0x00D2, - 0x00D3, - "One", - 0xff, - 0xffff - ) - { - IsChecked = false, - Y = Height - 30, - IsVisible = false - }); - one.X = Width - one.Width - 10; - one.MouseUp += Reg_MouseUp; - } - - private void Reg_MouseUp(object sender, Input.MouseEventArgs e) - { - if (sender is Checkbox) - { - if ((Checkbox)sender == reg) - { - slow.IsChecked = false; - one.IsChecked = false; - } - if ((Checkbox)sender == slow) - { - reg.IsChecked = false; - one.IsChecked = false; - } - if ((Checkbox)sender == one) - { - reg.IsChecked = false; - slow.IsChecked = false; - } - } - } - - private bool CheckDrivingBoat() - { - if (World.Player.IsDrivingBoat) - return true; - else - { - GameActions.Print("You need to be driving a boat to use this."); - return false; - } - } - private byte Speed() - { - if (one.IsChecked) return 1; - if (slow.IsChecked) return 1; - if (reg.IsChecked) return 2; - return 2; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/BuffGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/BuffGump.cs deleted file mode 100644 index 6bdf6ee2d..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/BuffGump.cs +++ /dev/null @@ -1,385 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Xml; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class BuffGump : Gump - { - private GumpPic _background; - private Button _button; - private GumpDirection _direction; - private ushort _graphic; - private DataBox _box; - - public BuffGump() : base(0, 0) - { - CanMove = true; - CanCloseWithRightClick = true; - AcceptMouseInput = true; - } - - public BuffGump(int x, int y) : this() - { - X = x; - Y = y; - - _direction = GumpDirection.LEFT_HORIZONTAL; - _graphic = 0x7580; - - SetInScreen(); - - BuildGump(); - } - - public override GumpType GumpType => GumpType.Buff; - - private void BuildGump() - { - WantUpdateSize = true; - - _box?.Clear(); - _box?.Children.Clear(); - - Clear(); - - Add(_background = new GumpPic(0, 0, _graphic, 0) { LocalSerial = 1 }); - - Add( - _button = new Button(0, 0x7585, 0x7589, 0x7589) - { - ButtonAction = ButtonAction.Activate - } - ); - - switch (_direction) - { - case GumpDirection.LEFT_HORIZONTAL: - _button.X = -2; - _button.Y = 36; - - break; - - case GumpDirection.RIGHT_VERTICAL: - _button.X = 34; - _button.Y = 78; - - break; - - case GumpDirection.RIGHT_HORIZONTAL: - _button.X = 76; - _button.Y = 36; - - break; - - case GumpDirection.LEFT_VERTICAL: - default: - _button.X = 0; - _button.Y = 0; - - break; - } - - Add(_box = new DataBox(0, 0, 0, 0) { WantUpdateSize = true }); - - if (World.Player != null) - { - foreach (KeyValuePair k in World.Player.BuffIcons) - { - _box.Add(new BuffControlEntry(World.Player.BuffIcons[k.Key])); - } - } - - _background.Graphic = _graphic; - _background.X = 0; - _background.Y = 0; - - UpdateElements(); - } - - public override void Save(XmlTextWriter writer) - { - base.Save(writer); - writer.WriteAttributeString("graphic", _graphic.ToString()); - writer.WriteAttributeString("direction", ((int)_direction).ToString()); - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - - _graphic = ushort.Parse(xml.GetAttribute("graphic")); - _direction = (GumpDirection)byte.Parse(xml.GetAttribute("direction")); - BuildGump(); - } - - protected override void UpdateContents() - { - BuildGump(); - } - - private void UpdateElements() - { - for (int i = 0, offset = 0; i < _box.Children.Count; i++, offset += 31) - { - Control e = _box.Children[i]; - - switch (_direction) - { - case GumpDirection.LEFT_VERTICAL: - e.X = 25; - e.Y = 26 + offset; - - break; - - case GumpDirection.LEFT_HORIZONTAL: - e.X = 26 + offset; - e.Y = 5; - - break; - - case GumpDirection.RIGHT_VERTICAL: - e.X = 5; - e.Y = _background.Height - 48 - offset; - - break; - - case GumpDirection.RIGHT_HORIZONTAL: - e.X = _background.Width - 48 - offset; - e.Y = 5; - - break; - } - } - } - - public override void OnButtonClick(int buttonID) - { - if (buttonID == 0) - { - _graphic++; - - if (_graphic > 0x7582) - { - _graphic = 0x757F; - } - - switch (_graphic) - { - case 0x7580: - _direction = GumpDirection.LEFT_HORIZONTAL; - - break; - - case 0x7581: - _direction = GumpDirection.RIGHT_VERTICAL; - - break; - - case 0x7582: - _direction = GumpDirection.RIGHT_HORIZONTAL; - - break; - - case 0x757F: - default: - _direction = GumpDirection.LEFT_VERTICAL; - - break; - } - - RequestUpdateContents(); - } - } - - private enum GumpDirection - { - LEFT_VERTICAL, - LEFT_HORIZONTAL, - RIGHT_VERTICAL, - RIGHT_HORIZONTAL - } - - private class BuffControlEntry : GumpPic - { - private byte _alpha; - private bool _decreaseAlpha; - private readonly RenderedText _gText; - private float _updateTooltipTime; - - public BuffControlEntry(BuffIcon icon) : base(0, 0, icon.Graphic, 0) - { - if (IsDisposed) - { - return; - } - - Icon = icon; - _alpha = 0xFF; - _decreaseAlpha = true; - - _gText = RenderedText.Create( - "", - 0xFFFF, - 2, - true, - FontStyle.Fixed | FontStyle.BlackBorder, - TEXT_ALIGN_TYPE.TS_CENTER, - Width - ); - - AcceptMouseInput = true; - WantUpdateSize = false; - CanMove = true; - - SetTooltip(icon.Text); - } - - public BuffIcon Icon { get; } - - public override void Update() - { - base.Update(); - - if (!IsDisposed && Icon != null) - { - int delta = (int)(Icon.Timer - Time.Ticks); - - if (_updateTooltipTime < Time.Ticks && delta > 0) - { - TimeSpan span = TimeSpan.FromMilliseconds(delta); - - SetTooltip( - string.Format( - ResGumps.TimeLeft, - Icon.Text, - span.Hours, - span.Minutes, - span.Seconds - ) - ); - - _updateTooltipTime = (float)Time.Ticks + 1000; - - if (span.Hours > 0) - { - _gText.Text = string.Format(ResGumps.Span0Hours, span.Hours); - } - else - { - _gText.Text = - span.Minutes > 0 - ? $"{span.Minutes}:{span.Seconds:00}" - : $"{span.Seconds:00}s"; - } - } - - if (Icon.Timer != 0xFFFF_FFFF && delta < 10000) - { - if (delta <= 0) - { - ((BuffGump)Parent.Parent)?.RequestUpdateContents(); - } - else - { - int alpha = _alpha; - int addVal = (10000 - delta) / 600; - - if (_decreaseAlpha) - { - alpha -= addVal; - - if (alpha <= 60) - { - _decreaseAlpha = false; - alpha = 60; - } - } - else - { - alpha += addVal; - - if (alpha >= 255) - { - _decreaseAlpha = true; - alpha = 255; - } - } - - _alpha = (byte)alpha; - } - } - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0, false, _alpha / 255f, true); - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(Graphic); - - if (gumpInfo.Texture != null) - { - batcher.Draw(gumpInfo.Texture, new Vector2(x, y), gumpInfo.UV, hueVector); - - if ( - ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.BuffBarTime - ) - { - _gText.Draw(batcher, x - 3, y + gumpInfo.UV.Height / 2 - 3, hueVector.Z); - } - } - - return true; - } - - public override void Dispose() - { - _gText?.Destroy(); - base.Dispose(); - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/BulletinBoardGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/BulletinBoardGump.cs deleted file mode 100644 index 0344f1f9a..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/BulletinBoardGump.cs +++ /dev/null @@ -1,582 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Network; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using ClassicUO.Utility; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class BulletinBoardGump : Gump - { - private readonly DataBox _databox; - - public BulletinBoardGump(uint serial, int x, int y, string name) : base(serial, 0) - { - X = x; - Y = y; - CanMove = true; - CanCloseWithRightClick = true; - - Add(new GumpPic(0, 0, 0x087A, 0)); - - Label label = new Label - ( - name, - true, - 1, - 170, - 1, - align: TEXT_ALIGN_TYPE.TS_CENTER - ) - { - X = 159, - Y = 36 - }; - - Add(label); - - HitBox hitbox = new HitBox(15, 170, 80, 80) - { - Alpha = 0f - }; - - hitbox.MouseUp += (sender, e) => - { - UIManager.GetGump(LocalSerial)?.Dispose(); - - UIManager.Add - ( - new BulletinBoardItem - ( - LocalSerial, - 0, - World.Player.Name, - string.Empty, - ResGumps.DateTime, - string.Empty, - 0 - ) { X = 400, Y = 335 } - ); - }; - - Add(hitbox); - - ScrollArea area = new ScrollArea - ( - 127, - 159, - 241, - 195, - false - ); - - Add(area); - - _databox = new DataBox(0, 0, 1, 1); - _databox.WantUpdateSize = true; - - area.Add(_databox); - - - // TODO: buuttons - } - - - public override void Dispose() - { - for (LinkedListNode g = UIManager.Gumps.Last; g != null; g = g.Previous) - { - if (g.Value is BulletinBoardItem) - { - g.Value.Dispose(); - } - } - - base.Dispose(); - } - - public void RemoveBulletinObject(uint serial) - { - foreach (Control child in _databox.Children) - { - if (child.LocalSerial == serial) - { - child.Dispose(); - _databox.WantUpdateSize = true; - _databox.ReArrangeChildren(); - - return; - } - } - } - - - public void AddBulletinObject(uint serial, string msg) - { - foreach (Control c in _databox.Children) - { - if (c.LocalSerial == serial) - { - c.Dispose(); - - break; - } - } - - BulletinBoardObject obj = new BulletinBoardObject(serial, msg); - _databox.Add(obj); - - _databox.WantUpdateSize = true; - _databox.ReArrangeChildren(); - } - } - - internal class BulletinBoardItem : Gump - { - private readonly ExpandableScroll _articleContainer; - private readonly Button _buttonPost; - private readonly Button _buttonRemove; - private readonly Button _buttonReply; - private readonly DataBox _databox; - private readonly string _datatime; - private readonly uint _msgSerial; - private readonly StbTextBox _subjectTextbox; - private readonly StbTextBox _textBox; - - public BulletinBoardItem - ( - uint serial, - uint msgSerial, - string poster, - string subject, - string datatime, - string data, - byte variant - ) : base(serial, 0) - { - _msgSerial = msgSerial; - AcceptKeyboardInput = true; - CanMove = true; - CanCloseWithRightClick = true; - _datatime = datatime; - - _articleContainer = new ExpandableScroll(0, 0, 408, 0x0820) - { - TitleGumpID = 0x0820, - AcceptMouseInput = true - }; - - Add(_articleContainer); - - ScrollArea area = new ScrollArea - ( - 0, - 120, - 272, - 224, - false - ); - - Add(area); - - _databox = new DataBox(0, 0, 1, 1); - area.Add(_databox); - - bool useUnicode = Client.Version >= ClientVersion.CV_305D; - byte unicodeFontIndex = 1; - int unicodeFontHeightOffset = 0; - - ushort textColor = 0x0386; - - if (useUnicode) - { - unicodeFontHeightOffset = -6; - textColor = 0; - } - - Label text = new Label(ResGumps.Author, useUnicode, textColor, font: useUnicode ? unicodeFontIndex : (byte) 6) - { - X = 30, - Y = 40 - }; - - Add(text); - - text = new Label(poster, useUnicode, textColor, font: useUnicode ? unicodeFontIndex : (byte) 9) - { - X = 30 + text.Width, - Y = 46 + unicodeFontHeightOffset - }; - - Add(text); - - - text = new Label(ResGumps.Date, useUnicode, textColor, font: useUnicode ? unicodeFontIndex : (byte) 6) - { - X = 30, - Y = 58 - }; - - Add(text); - - text = new Label(datatime, useUnicode, textColor, font: useUnicode ? unicodeFontIndex : (byte) 9) - { - X = 32 + text.Width, - Y = 64 + unicodeFontHeightOffset - }; - - Add(text); - - text = new Label(ResGumps.Title, useUnicode, textColor, font: useUnicode ? unicodeFontIndex : (byte) 6) - { - X = 30, - Y = 77 - }; - - Add(text); - - ushort subjectColor = textColor; - - if (variant == 0) - { - subjectColor = 0x0008; - } - - Add - ( - _subjectTextbox = new StbTextBox(useUnicode ? unicodeFontIndex : (byte) 9, maxWidth: 150, isunicode: useUnicode, hue: subjectColor) - { - X = 30 + text.Width, - Y = 83 + unicodeFontHeightOffset, - Width = 150, - IsEditable = variant == 0 - } - ); - - _subjectTextbox.SetText(subject); - - Add - ( - new GumpPicTiled - ( - 30, - 106, - 235, - 4, - 0x0835 - ) - ); - - _databox.Add - ( - _textBox = new StbTextBox - ( - useUnicode ? unicodeFontIndex : (byte) 9, - -1, - 220, - hue: textColor, - isunicode: useUnicode - ) - { - X = 40, - Y = 0, - Width = 220, - Height = 300, - IsEditable = variant == 0, - Multiline = true - } - ); - - _textBox.SetText(data); - _textBox.TextChanged += _textBox_TextChanged; - - switch (variant) - { - case 0: - Add(new GumpPic(97, 12, 0x0883, 0)); - - Add - ( - _buttonPost = new Button((int) ButtonType.Post, 0x0886, 0x0886) - { - X = 37, - Y = Height - 50, - ButtonAction = ButtonAction.Activate, - ContainsByBounds = true - } - ); - - break; - - case 1: - - Add - ( - _buttonReply = new Button((int) ButtonType.Reply, 0x0884, 0x0884) - { - X = 37, - Y = Height - 50, - ButtonAction = ButtonAction.Activate, - ContainsByBounds = true - } - ); - - break; - - case 2: - - Add - ( - _buttonRemove = new Button((int) ButtonType.Remove, 0x0885, 0x0885) //DISABLED - { - X = 235, - Y = Height - 50, - ButtonAction = ButtonAction.Activate, - ContainsByBounds = true - } - ); - - break; - } - - _databox.WantUpdateSize = true; - _databox.ReArrangeChildren(); - } - - private void _textBox_TextChanged(object sender, EventArgs e) - { - _textBox.Height = Math.Max - ( - FontsLoader.Instance.GetHeightUnicode - ( - 1, - _textBox.Text, - 220, - TEXT_ALIGN_TYPE.TS_LEFT, - 0x0 - ) + 5, - 20 - ); - - foreach (Control c in _databox.Children) - { - if (c is BulletinBoardItem) - { - c.OnPageChanged(); - } - } - } - - public override void Update() - { - if (_buttonPost != null) - { - _buttonPost.Y = Height - 50; - } - - if (_buttonReply != null) - { - _buttonReply.Y = Height - 50; - } - - if (_buttonRemove != null) - { - _buttonRemove.Y = Height - 50; - } - - //if (!_textBox.IsDisposed && _textBox.IsChanged) - //{ - // _textBox.Height = System.Math.Max(FontsLoader.Instance.GetHeightUnicode(1, _textBox.TxEntry.Text, 220, TEXT_ALIGN_TYPE.TS_LEFT, 0x0) + 20, 40); - - // foreach (Control c in _scrollArea.Children) - // { - // if (c is ScrollAreaItem) - // c.OnPageChanged(); - // } - //} - - base.Update(); - } - - - public override void OnButtonClick(int buttonID) - { - // necessary to avoid closing - if (_subjectTextbox == null) - { - return; - } - - switch ((ButtonType) buttonID) - { - case ButtonType.Post: - NetClient.Socket.Send_BulletinBoardPostMessage(LocalSerial, _msgSerial, _subjectTextbox.Text, _textBox.Text); - - Dispose(); - - break; - - case ButtonType.Reply: - UIManager.Add - ( - new BulletinBoardItem - ( - LocalSerial, - _msgSerial, - World.Player.Name, - ResGumps.RE + _subjectTextbox.Text, - _datatime, - string.Empty, - 0 - ) { X = 400, Y = 335 } - ); - - Dispose(); - - break; - - case ButtonType.Remove: - NetClient.Socket.Send_BulletinBoardRemoveMessage(LocalSerial, _msgSerial); - Dispose(); - - break; - } - } - - public override void OnPageChanged() - { - Height = _articleContainer.SpecialHeight; - _databox.Parent.Height = _databox.Height = _articleContainer.SpecialHeight - 184; - - foreach (Control c in _databox.Children) - { - if (c is BulletinBoardItem) - { - c.OnPageChanged(); - } - } - } - - //public override void OnKeyboardReturn(int textID, string text) - //{ - // if ((MultiLineBox.PasteRetnCmdID & textID) != 0 && !string.IsNullOrEmpty(text)) - // _textBox.TxEntry.InsertString(text.Replace("\r", string.Empty)); - //} - - - private enum ButtonType - { - Post, - Remove, - Reply - } - } - - internal class BulletinBoardObject : Control - { - public BulletinBoardObject(uint serial, string text) - { - LocalSerial = serial; //board - CanMove = true; - Width = 230; - Height = 18; - - Add(new GumpPic(0, 0, 0x1523, 0)); - - if (Client.Version >= ClientVersion.CV_305D) - { - Add - ( - new Label - ( - text, - true, - 0, - Width - 23, - 1, - FontStyle.Fixed - ) - { - X = 23, Y = 1 - } - ); - } - else - { - Add - ( - new Label - ( - text, - false, - 0x0386, - Width - 23, - 9, - FontStyle.Fixed - ) - { - X = 23, - Y = 1 - } - ); - } - - WantUpdateSize = false; - } - - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if (button != MouseButtonType.Left) - { - return false; - } - - Control root = RootParent; - - if (root != null) - { - NetClient.Socket.Send_BulletinBoardRequestMessage(root.LocalSerial, LocalSerial); - } - - return true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CharCreationGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CharCreationGump.cs deleted file mode 100644 index 7f3ff9a7c..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CharCreationGump.cs +++ /dev/null @@ -1,232 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Linq; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Game.UI.Gumps.Login; -using ClassicUO.Assets; -using ClassicUO.Utility; - -namespace ClassicUO.Game.UI.Gumps.CharCreation -{ - internal class CharCreationGump : Gump - { - private PlayerMobile _character; - private int _cityIndex; - private CharCreationStep _currentStep; - private LoadingGump _loadingGump; - private readonly LoginScene _loginScene; - private ProfessionInfo _selectedProfession; - - public CharCreationGump(LoginScene scene) : base(0, 0) - { - _loginScene = scene; - Add(new CreateCharAppearanceGump(), 1); - SetStep(CharCreationStep.Appearence); - CanCloseWithRightClick = false; - } - - internal static int _skillsCount => Client.Version >= ClientVersion.CV_70160 ? 4 : 3; - - public void SetCharacter(PlayerMobile character) - { - _character = character; - SetStep(CharCreationStep.ChooseProfession); - } - - public void SetAttributes(bool force = false) - { - SetStep(_selectedProfession.DescriptionIndex >= 0 || force ? CharCreationStep.ChooseCity : CharCreationStep.ChooseTrade); - } - - public void SetCity(int cityIndex) - { - _cityIndex = cityIndex; - } - - public void SetProfession(ProfessionInfo info) - { - for (int i = 0; i < _skillsCount; i++) - { - int skillIndex = info.SkillDefVal[i, 0]; - - if (skillIndex >= _character.Skills.Length) - { - continue; - } - - if (!CUOEnviroment.IsOutlands && (World.ClientFeatures.Flags & CharacterListFlags.CLF_SAMURAI_NINJA) == 0 && (skillIndex == 52 || skillIndex == 53)) - { - // reset skills if needed - for (int k = 0; k < i; k++) - { - Skill skill = _character.Skills[info.SkillDefVal[k, 0]]; - skill.ValueFixed = 0; - skill.BaseFixed = 0; - skill.CapFixed = 0; - skill.Lock = Lock.Locked; - } - - MessageBoxGump messageBox = new MessageBoxGump - ( - 400, - 300, - ClilocLoader.Instance.GetString(1063016), - null, - true - ) - { - X = 470 / 2 - 400 / 2 + 100, - Y = 372 / 2 - 300 / 2 + 20, - CanMove = false - }; - - UIManager.Add(messageBox); - - return; - } - - Skill skill2 = _character.Skills[skillIndex]; - skill2.ValueFixed = (ushort) info.SkillDefVal[i, 1]; - skill2.BaseFixed = 0; - skill2.CapFixed = 0; - skill2.Lock = Lock.Locked; - } - - _selectedProfession = info; - _character.Strength = (ushort) _selectedProfession.StatsVal[0]; - _character.Intelligence = (ushort) _selectedProfession.StatsVal[1]; - _character.Dexterity = (ushort) _selectedProfession.StatsVal[2]; - - SetAttributes(); - - SetStep(_selectedProfession.DescriptionIndex > 0 ? CharCreationStep.ChooseCity : CharCreationStep.ChooseTrade); - } - - public void CreateCharacter(byte profession) - { - _loginScene.CreateCharacter(_character, _cityIndex, profession); - } - - public void StepBack(int steps = 1) - { - if (_currentStep == CharCreationStep.Appearence) - { - _loginScene.StepBack(); - } - else - { - SetStep(_currentStep - steps); - } - } - - public void ShowMessage(string message) - { - int currentPage = ActivePage; - - if (_loadingGump != null) - { - Remove(_loadingGump); - } - - Add(_loadingGump = new LoadingGump(message, LoginButtons.OK, a => ChangePage(currentPage)), 4); - ChangePage(4); - } - - private void SetStep(CharCreationStep step) - { - _currentStep = step; - - switch (step) - { - default: - case CharCreationStep.Appearence: - ChangePage(1); - - break; - - case CharCreationStep.ChooseProfession: - Control existing = Children.FirstOrDefault(page => page.Page == 2); - - if (existing != null) - { - Remove(existing); - } - - Add(new CreateCharProfessionGump(), 2); - - ChangePage(2); - - break; - - case CharCreationStep.ChooseTrade: - existing = Children.FirstOrDefault(page => page.Page == 3); - - if (existing != null) - { - Remove(existing); - } - - Add(new CreateCharTradeGump(_character, _selectedProfession), 3); - ChangePage(3); - - break; - - case CharCreationStep.ChooseCity: - existing = Children.FirstOrDefault(page => page.Page == 4); - - if (existing != null) - { - Remove(existing); - } - - Add(new CreateCharSelectionCityGump((byte) _selectedProfession.DescriptionIndex, _loginScene), 4); - - ChangePage(4); - - break; - } - } - - private enum CharCreationStep - { - Appearence = 0, - ChooseProfession = 1, - ChooseTrade = 2, - ChooseCity = 3 - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CreateCharAppearanceGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CreateCharAppearanceGump.cs deleted file mode 100644 index 8a3c90f72..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CreateCharAppearanceGump.cs +++ /dev/null @@ -1,1172 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Linq; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; - -namespace ClassicUO.Game.UI.Gumps.CharCreation -{ - internal class CreateCharAppearanceGump : Gump - { - struct CharacterInfo - { - public bool IsFemale; - public RaceType Race; - } - - private PlayerMobile _character; - private CharacterInfo _characterInfo; - private readonly Button _humanRadio, _elfRadio, _gargoyleRadio; - private readonly Button _maleRadio, _femaleRadio; - private Combobox _hairCombobox, _facialCombobox; - private Label _hairLabel, _facialLabel; - private readonly StbTextBox _nameTextBox; - private PaperDollInteractable _paperDoll; - private readonly Button _nextButton; - private readonly Dictionary> CurrentColorOption = new Dictionary>(); - private readonly Dictionary CurrentOption = new Dictionary - { - { - Layer.Hair, 1 - }, - { - Layer.Beard, 0 - } - }; - - public CreateCharAppearanceGump() : base(0, 0) - { - Add - ( - new ResizePic(0x0E10) - { - X = 82, Y = 125, Width = 151, Height = 310 - }, - 1 - ); - - Add(new GumpPic(280, 53, 0x0709, 0), 1); - Add(new GumpPic(240, 73, 0x070A, 0), 1); - - Add - ( - new GumpPicTiled - ( - 248, - 73, - 215, - 16, - 0x070B - ), - 1 - ); - - Add(new GumpPic(463, 73, 0x070C, 0), 1); - Add(new GumpPic(238, 98, 0x0708, 0), 1); - - Add - ( - new ResizePic(0x0E10) - { - X = 475, Y = 125, Width = 151, Height = 310 - }, - 1 - ); - - // Male/Female Radios - Add - ( - _maleRadio = new Button((int)Buttons.MaleButton, 0x0768, 0x0767) - { - X = 425, Y = 435, ButtonAction = ButtonAction.Activate - }, - 1 - ); - - Add - ( - _femaleRadio = new Button((int)Buttons.FemaleButton, 0x0768, 0x0767) - { - X = 425, Y = 455, ButtonAction = ButtonAction.Activate - }, - 1 - ); - - Add - ( - new Button((int) Buttons.MaleButton, 0x0710, 0x0712, 0x0711) - { - X = 445, Y = 435, ButtonAction = ButtonAction.Activate - }, - 1 - ); - - Add - ( - new Button((int) Buttons.FemaleButton, 0x070D, 0x070F, 0x070E) - { - X = 445, Y = 455, ButtonAction = ButtonAction.Activate - }, - 1 - ); - - Add - ( - _nameTextBox = new StbTextBox - ( - 5, - 16, - 200, - false, - hue: 1, - style: FontStyle.Fixed - ) - { - X = 257, Y = 65, Width = 200, Height = 20 - //ValidationRules = (uint) (TEXT_ENTRY_RULES.LETTER | TEXT_ENTRY_RULES.SPACE) - }, - 1 - ); - - // Races - Add - ( - _humanRadio = new Button((int)Buttons.HumanButton, 0x0768, 0x0767) - { - X = 180, Y = 435, ButtonAction = ButtonAction.Activate - }, - 1 - ); - - Add - ( - new Button((int) Buttons.HumanButton, 0x0702, 0x0704, 0x0703) - { - X = 200, Y = 435, ButtonAction = ButtonAction.Activate - }, - 1 - ); - - Add - ( - _elfRadio = new Button((int)Buttons.ElfButton, 0x0768, 0x0767, 0x0768) - { - X = 180, Y = 455, ButtonAction = ButtonAction.Activate - }, - 1 - ); - - Add - ( - new Button((int) Buttons.ElfButton, 0x0705, 0x0707, 0x0706) - { - X = 200, Y = 455, ButtonAction = ButtonAction.Activate - }, - 1 - ); - - if (Client.Version >= ClientVersion.CV_60144) - { - Add - ( - _gargoyleRadio = new Button((int)Buttons.GargoyleButton, 0x0768, 0x0767) - { - X = 60, Y = 435, ButtonAction = ButtonAction.Activate - }, - 1 - ); - - Add - ( - new Button((int) Buttons.GargoyleButton, 0x07D3, 0x07D5, 0x07D4) - { - X = 80, Y = 435, ButtonAction = ButtonAction.Activate - }, - 1 - ); - } - - // Prev/Next - Add - ( - new Button((int) Buttons.Prev, 0x15A1, 0x15A3, 0x15A2) - { - X = 586, Y = 445, ButtonAction = ButtonAction.Activate - }, - 1 - ); - - Add - ( - _nextButton = new Button((int) Buttons.Next, 0x15A4, 0x15A6, 0x15A5) - { - X = 610, Y = 445, ButtonAction = ButtonAction.Activate - }, - 1 - ); - - _maleRadio.IsClicked = true; - _humanRadio.IsClicked = true; - _characterInfo.IsFemale = false; - _characterInfo.Race = RaceType.HUMAN; - - HandleGenreChange(); - HandleRaceChanged(); - } - - private void CreateCharacter(bool isFemale, RaceType race) - { - if (_character == null) - { - _character = new PlayerMobile(1); - World.Mobiles.Add(_character); - } - - LinkedObject first = _character.Items; - - while (first != null) - { - LinkedObject next = first.Next; - - World.RemoveItem((Item) first, true); - - first = next; - } - - _character.Clear(); - _character.Race = race; - _character.IsFemale = isFemale; - - if (isFemale) - { - _character.Flags |= Flags.Female; - } - else - { - _character.Flags &= ~Flags.Female; - } - - switch (race) - { - case RaceType.GARGOYLE: - _character.Graphic = isFemale ? (ushort) 0x029B : (ushort) 0x029A; - - Item it = CreateItem(0x4001, CurrentColorOption[Layer.Shirt].Item2, Layer.Robe); - - _character.PushToBack(it); - - break; - - case RaceType.ELF when isFemale: - _character.Graphic = 0x025E; - it = CreateItem(0x1710, 0x0384, Layer.Shoes); - _character.PushToBack(it); - - it = CreateItem(0x1531, CurrentColorOption[Layer.Pants].Item2, Layer.Skirt); - - _character.PushToBack(it); - - it = CreateItem(0x1518, CurrentColorOption[Layer.Shirt].Item2, Layer.Shirt); - - _character.PushToBack(it); - - break; - - case RaceType.ELF: - _character.Graphic = 0x025D; - it = CreateItem(0x1710, 0x0384, Layer.Shoes); - _character.PushToBack(it); - - it = CreateItem(0x152F, CurrentColorOption[Layer.Pants].Item2, Layer.Pants); - - _character.PushToBack(it); - - it = CreateItem(0x1518, CurrentColorOption[Layer.Shirt].Item2, Layer.Shirt); - - _character.PushToBack(it); - - break; - - default: - - { - if (isFemale) - { - _character.Graphic = 0x0191; - it = CreateItem(0x1710, 0x0384, Layer.Shoes); - _character.PushToBack(it); - - it = CreateItem(0x1531, CurrentColorOption[Layer.Pants].Item2, Layer.Pants); - - _character.PushToBack(it); - - it = CreateItem(0x1518, CurrentColorOption[Layer.Shirt].Item2, Layer.Shirt); - - _character.PushToBack(it); - } - else - { - _character.Graphic = 0x0190; - it = CreateItem(0x1710, 0x0384, Layer.Shoes); - _character.PushToBack(it); - - it = CreateItem(0x152F, CurrentColorOption[Layer.Pants].Item2, Layer.Pants); - - _character.PushToBack(it); - - it = CreateItem(0x1518, CurrentColorOption[Layer.Shirt].Item2, Layer.Shirt); - - _character.PushToBack(it); - } - - break; - } - } - } - - private void UpdateEquipments() - { - RaceType race = _characterInfo.Race; - Layer layer; - CharacterCreationValues.ComboContent content; - - _character.Hue = CurrentColorOption[Layer.Invalid].Item2; - - if (!_characterInfo.IsFemale && race != RaceType.ELF) - { - layer = Layer.Beard; - content = CharacterCreationValues.GetFacialHairComboContent(race); - - Item iti = CreateItem(content.GetGraphic(CurrentOption[layer]), CurrentColorOption[layer].Item2, layer); - - _character.PushToBack(iti); - } - - layer = Layer.Hair; - content = CharacterCreationValues.GetHairComboContent(_characterInfo.IsFemale, race); - - Item it = CreateItem(content.GetGraphic(CurrentOption[layer]), CurrentColorOption[layer].Item2, layer); - - _character.PushToBack(it); - } - - private void HandleRaceChanged() - { - CurrentColorOption.Clear(); - HandleGenreChange(); - RaceType race = _characterInfo.Race; - CharacterListFlags flags = World.ClientFeatures.Flags; - LockedFeatureFlags locks = World.ClientLockedFeatures.Flags; - - bool allowElf = (flags & CharacterListFlags.CLF_ELVEN_RACE) != 0 && locks.HasFlag(LockedFeatureFlags.ML); - bool allowGarg = locks.HasFlag(LockedFeatureFlags.SA); - - if (race == RaceType.ELF && !allowElf) - { - _nextButton.IsEnabled = false; - _nextButton.Hue = 944; - } - else if (race == RaceType.GARGOYLE && !allowGarg) - { - _nextButton.IsEnabled = false; - _nextButton.Hue = 944; - } - else - { - _nextButton.IsEnabled = true; - _nextButton.Hue = 0; - } - } - - private void HandleGenreChange() - { - RaceType race = _characterInfo.Race; - - CurrentOption[Layer.Beard] = 0; - CurrentOption[Layer.Hair] = 1; - - if (_paperDoll != null) - { - Remove(_paperDoll); - } - - if (_hairCombobox != null) - { - Remove(_hairCombobox); - Remove(_hairLabel); - } - - if (_facialCombobox != null) - { - Remove(_facialCombobox); - Remove(_facialLabel); - } - - foreach (CustomColorPicker customPicker in Children.OfType().ToList()) - { - Remove(customPicker); - } - - // Hair - CharacterCreationValues.ComboContent content = CharacterCreationValues.GetHairComboContent(_characterInfo.IsFemale, race); - - bool isAsianLang = string.Compare(Settings.GlobalSettings.Language, "CHT", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "KOR", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "JPN", StringComparison.InvariantCultureIgnoreCase) == 0; - - bool unicode = isAsianLang; - byte font = (byte)(isAsianLang ? 3 : 9); - ushort hue = (ushort)(isAsianLang ? 0xFFFF : 0); - - Add - ( - _hairLabel = new Label(ClilocLoader.Instance.GetString(race == RaceType.GARGOYLE ? 1112309 : 3000121), unicode, hue, font: font) - { - X = 98, Y = 140 - }, - 1 - ); - - Add - ( - _hairCombobox = new Combobox - ( - 97, - 155, - 120, - content.Labels, - CurrentOption[Layer.Hair] - ), - 1 - ); - - _hairCombobox.OnOptionSelected += Hair_OnOptionSelected; - - // Facial Hair - if (!_characterInfo.IsFemale && race != RaceType.ELF) - { - content = CharacterCreationValues.GetFacialHairComboContent(race); - - Add - ( - _facialLabel = new Label(ClilocLoader.Instance.GetString(race == RaceType.GARGOYLE ? 1112511 : 3000122), unicode, hue, font: font) - { - X = 98, Y = 184 - }, - 1 - ); - - Add - ( - _facialCombobox = new Combobox - ( - 97, - 199, - 120, - content.Labels, - CurrentOption[Layer.Beard] - ), - 1 - ); - - _facialCombobox.OnOptionSelected += Facial_OnOptionSelected; - } - else - { - _facialCombobox = null; - _facialLabel = null; - } - - // Skin - ushort[] pallet = CharacterCreationValues.GetSkinPallet(race); - - AddCustomColorPicker - ( - 489, - 141, - pallet, - Layer.Invalid, - 3000183, - 8, - pallet.Length >> 3 - ); - - // Shirt Color - AddCustomColorPicker - ( - 489, - 183, - null, - Layer.Shirt, - 3000440, - 10, - 20 - ); - - // Pants Color - if (race != RaceType.GARGOYLE) - { - AddCustomColorPicker - ( - 489, - 225, - null, - Layer.Pants, - 3000441, - 10, - 20 - ); - } - - // Hair - pallet = CharacterCreationValues.GetHairPallet(race); - - AddCustomColorPicker - ( - 489, - 267, - pallet, - Layer.Hair, - race == RaceType.GARGOYLE ? 1112322 : 3000184, - 8, - pallet.Length >> 3 - ); - - if (!_characterInfo.IsFemale && race != RaceType.ELF) - { - // Facial - pallet = CharacterCreationValues.GetHairPallet(race); - - AddCustomColorPicker - ( - 489, - 309, - pallet, - Layer.Beard, - race == RaceType.GARGOYLE ? 1112512 : 3000446, - 8, - pallet.Length >> 3 - ); - } - - CreateCharacter(_characterInfo.IsFemale, race); - - UpdateEquipments(); - - Add - ( - _paperDoll = new PaperDollInteractable(262, 135, _character, null) - { - AcceptMouseInput = false - }, - 1 - ); - - _paperDoll.RequestUpdate(); - } - - private void AddCustomColorPicker - ( - int x, - int y, - ushort[] pallet, - Layer layer, - int clilocLabel, - int rows, - int columns - ) - { - CustomColorPicker colorPicker; - - Add - ( - colorPicker = new CustomColorPicker - ( - layer, - clilocLabel, - pallet, - rows, - columns - ) - { - X = x, Y = y - }, - 1 - ); - - if (!CurrentColorOption.ContainsKey(layer)) - { - CurrentColorOption[layer] = new Tuple(0, colorPicker.HueSelected); - } - else - { - colorPicker.SetSelectedIndex(CurrentColorOption[layer].Item1); - } - - colorPicker.ColorSelected += ColorPicker_ColorSelected; - } - - private void ColorPicker_ColorSelected(object sender, ColorSelectedEventArgs e) - { - if (e.SelectedIndex == 0xFFFF) - { - return; - } - - CurrentColorOption[e.Layer] = new Tuple(e.SelectedIndex, e.SelectedHue); - - if (e.Layer != Layer.Invalid) - { - Item item; - - if (_character.Race == RaceType.GARGOYLE && e.Layer == Layer.Shirt) - { - item = _character.FindItemByLayer(Layer.Robe); - } - else - { - item = _character.FindItemByLayer(_characterInfo.IsFemale && e.Layer == Layer.Pants ? Layer.Skirt : e.Layer); - } - - if (item != null) - { - item.Hue = e.SelectedHue; - } - } - else - { - _character.Hue = e.SelectedHue; - } - - _paperDoll.RequestUpdate(); - } - - private void Facial_OnOptionSelected(object sender, int e) - { - CurrentOption[Layer.Beard] = e; - UpdateEquipments(); - _paperDoll.RequestUpdate(); - } - - private void Hair_OnOptionSelected(object sender, int e) - { - CurrentOption[Layer.Hair] = e; - UpdateEquipments(); - _paperDoll.RequestUpdate(); - } - - public override void OnButtonClick(int buttonID) - { - CharCreationGump charCreationGump = UIManager.GetGump(); - - switch ((Buttons) buttonID) - { - case Buttons.FemaleButton: - _femaleRadio.IsClicked = true; - _maleRadio.IsClicked = false; - _characterInfo.IsFemale = true; - - HandleGenreChange(); - - break; - - case Buttons.MaleButton: - _maleRadio.IsClicked = true; - _femaleRadio.IsClicked = false; - _characterInfo.IsFemale = false; - - HandleGenreChange(); - - break; - - case Buttons.HumanButton: - - _characterInfo.Race = RaceType.HUMAN; - - if (!_humanRadio.IsClicked) - { - _humanRadio.IsClicked = true; - - if (_elfRadio != null) - { - _elfRadio.IsClicked = false; - } - - if (_gargoyleRadio != null) - { - _gargoyleRadio.IsClicked = false; - } - - HandleRaceChanged(); - } - - break; - - case Buttons.ElfButton: - - _characterInfo.Race = RaceType.ELF; - - if (!_elfRadio.IsClicked) - { - _elfRadio.IsClicked = true; - _humanRadio.IsClicked = false; - - if (_gargoyleRadio != null) - { - _gargoyleRadio.IsClicked = false; - } - - HandleRaceChanged(); - } - - break; - - case Buttons.GargoyleButton: - - _characterInfo.Race = RaceType.GARGOYLE; - - if (!_gargoyleRadio.IsClicked) - { - _gargoyleRadio.IsClicked = true; - _elfRadio.IsClicked = false; - _humanRadio.IsClicked = false; - - HandleRaceChanged(); - } - - break; - - case Buttons.Next: - _character.Name = _nameTextBox.Text; - - if (ValidateCharacter(_character)) - { - charCreationGump.SetCharacter(_character); - } - - break; - - case Buttons.Prev: - charCreationGump.StepBack(); - - break; - } - - base.OnButtonClick(buttonID); - } - - private bool ValidateCharacter(PlayerMobile character) - { - int invalid = Validate(character.Name); - if (invalid > 0) - { - UIManager.GetGump()?.ShowMessage(ClilocLoader.Instance.GetString(invalid)); - - return false; - } - - return true; - } - - public static int Validate(string name) - { - return Validate(name, 2, 16, true, false, true, 1, _SpaceDashPeriodQuote, Client.Version >= ClientVersion.CV_5020 ? _Disallowed : new string[] { }, _StartDisallowed); - } - - public static int Validate(string name, int minLength, int maxLength, bool allowLetters, bool allowDigits, bool noExceptionsAtStart, int maxExceptions, char[] exceptions, string[] disallowed, string[] startDisallowed) - { - if (string.IsNullOrEmpty(name) || name.Length < minLength) - return 3000612; - else if (name.Length > maxLength) - return 3000611; - - int exceptCount = 0; - - name = name.ToLowerInvariant(); - - if (!allowLetters || !allowDigits || (exceptions.Length > 0 && (noExceptionsAtStart || maxExceptions < int.MaxValue))) - { - for (int i = 0; i < name.Length; ++i) - { - char c = name[i]; - - if (c >= 'a' && c <= 'z') - { - exceptCount = 0; - } - else if (c >= '0' && c <= '9') - { - if (!allowDigits) - return 3000611; - - exceptCount = 0; - } - else - { - bool except = false; - - for (int j = 0; !except && j < exceptions.Length; ++j) - if (c == exceptions[j]) - except = true; - - if (!except || (i == 0 && noExceptionsAtStart)) - return 3000611; - - if (exceptCount++ == maxExceptions) - return 3000611; - } - } - } - - for (int i = 0; i < disallowed.Length; ++i) - { - int indexOf = name.IndexOf(disallowed[i]); - - if (indexOf == -1) - continue; - - bool badPrefix = (indexOf == 0); - - for (int j = 0; !badPrefix && j < exceptions.Length; ++j) - badPrefix = (name[indexOf - 1] == exceptions[j]); - - if (!badPrefix) - continue; - - bool badSuffix = ((indexOf + disallowed[i].Length) >= name.Length); - - for (int j = 0; !badSuffix && j < exceptions.Length; ++j) - badSuffix = (name[indexOf + disallowed[i].Length] == exceptions[j]); - - if (badSuffix) - return 3000611; - } - - for (int i = 0; i < startDisallowed.Length; ++i) - { - if (name.StartsWith(startDisallowed[i])) - return 3000611; - } - - return 0; - } - - private static readonly char[] _SpaceDashPeriodQuote = new char[] - { - ' ', '-', '.', '\'' - }; - - private static string[] _StartDisallowed = new string[] - { - "seer", - "counselor", - "gm", - "admin", - "lady", - "lord" - }; - - private static readonly string[] _Disallowed = new string[] - { - "jigaboo", - "chigaboo", - "wop", - "kyke", - "kike", - "tit", - "spic", - "prick", - "piss", - "lezbo", - "lesbo", - "felatio", - "dyke", - "dildo", - "chinc", - "chink", - "cunnilingus", - "cum", - "cocksucker", - "cock", - "clitoris", - "clit", - "ass", - "hitler", - "penis", - "nigga", - "nigger", - "klit", - "kunt", - "jiz", - "jism", - "jerkoff", - "jackoff", - "goddamn", - "fag", - "blowjob", - "bitch", - "asshole", - "dick", - "pussy", - "snatch", - "cunt", - "twat", - "shit", - "fuck", - "tailor", - "smith", - "scholar", - "rogue", - "novice", - "neophyte", - "merchant", - "medium", - "master", - "mage", - "lb", - "journeyman", - "grandmaster", - "fisherman", - "expert", - "chef", - "carpenter", - "british", - "blackthorne", - "blackthorn", - "beggar", - "archer", - "apprentice", - "adept", - "gamemaster", - "frozen", - "squelched", - "invulnerable", - "osi", - "origin" - }; - - private Item CreateItem(int id, ushort hue, Layer layer) - { - Item existsItem = _character.FindItemByLayer(layer); - - if (existsItem != null) - { - World.RemoveItem(existsItem, true); - _character.Remove(existsItem); - } - - if (id == 0) - { - return null; - } - - // This is a workaround to avoid to see naked guy - // We are simulating server objects into World.Items map. - Item item = World.GetOrCreateItem(0x4000_0000 + (uint) layer); // use layer as unique Serial - _character.Remove(item); - item.Graphic = (ushort) id; - item.Hue = hue; - item.Layer = layer; - item.Container = _character; - // - - return item; - } - - private enum Buttons - { - MaleButton, - FemaleButton, - HumanButton, - ElfButton, - GargoyleButton, - Prev, - Next - } - - private class ColorSelectedEventArgs : EventArgs - { - public ColorSelectedEventArgs(Layer layer, ushort[] pallet, int selectedIndex) - { - Layer = layer; - Pallet = pallet; - SelectedIndex = selectedIndex; - } - - public Layer Layer { get; } - - private ushort[] Pallet { get; } - - public int SelectedIndex { get; } - - public ushort SelectedHue => Pallet != null && SelectedIndex >= 0 && SelectedIndex < Pallet.Length ? Pallet[SelectedIndex] : (ushort) 0xFFFF; - } - - private class CustomColorPicker : Control - { - //private readonly ColorBox _box; - private readonly int _cellH; - private readonly int _cellW; - private readonly ColorBox _colorPicker; - private ColorPickerBox _colorPickerBox; - private readonly int _columns, _rows; - private int _lastSelectedIndex; - private readonly Layer _layer; - private readonly ushort[] _pallet; - - public CustomColorPicker(Layer layer, int label, ushort[] pallet, int rows, int columns) - { - Width = 121; - Height = 25; - _cellW = 125 / columns; - _cellH = 280 / rows; - _columns = columns; - _rows = rows; - _layer = layer; - _pallet = pallet; - - bool isAsianLang = string.Compare(Settings.GlobalSettings.Language, "CHT", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "KOR", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "JPN", StringComparison.InvariantCultureIgnoreCase) == 0; - - bool unicode = isAsianLang; - byte font = (byte)(isAsianLang ? 3 : 9); - ushort hue = (ushort)(isAsianLang ? 0xFFFF : 0); - - Add - ( - new Label(ClilocLoader.Instance.GetString(label), unicode, hue, font: font) - { - X = 0, - Y = 0 - } - ); - - Add - ( - _colorPicker = new ColorBox(121, 23, (ushort) ((pallet?[0] ?? 1) + 1)) - { - X = 1, - Y = 15 - } - ); - - _colorPicker.MouseUp += ColorPicker_MouseClick; - } - - public ushort HueSelected => _colorPicker.Hue; - - public event EventHandler ColorSelected; - - public void SetSelectedIndex(int index) - { - if (_colorPickerBox != null) - { - _colorPickerBox.SelectedIndex = index; - - SetCurrentHue(); - } - } - - private void SetCurrentHue() - { - _colorPicker.Hue = _colorPickerBox.SelectedHue; - _lastSelectedIndex = _colorPickerBox.SelectedIndex; - - _colorPickerBox.Dispose(); - } - - private void ColorPickerBoxOnMouseUp(object sender, MouseEventArgs e) - { - int column = e.X / _cellW; - int row = e.Y / _cellH; - int selectedIndex = row * _columns + column; - - if (selectedIndex >= 0 && selectedIndex < _colorPickerBox.Hues.Length) - { - ColorSelected?.Invoke(this, new ColorSelectedEventArgs(_layer, _colorPickerBox.Hues, selectedIndex)); - SetCurrentHue(); - } - } - - private void ColorPicker_MouseClick(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtonType.Left) - { - _colorPickerBox?.Dispose(); - _colorPickerBox = null; - - if (_colorPickerBox == null) - { - _colorPickerBox = new ColorPickerBox - ( - 489, - 141, - _rows, - _columns, - _cellW, - _cellH, - _pallet - ) - { - IsModal = true, - LayerOrder = UILayer.Over, - ModalClickOutsideAreaClosesThisControl = true, - ShowLivePreview = false, - SelectedIndex = _lastSelectedIndex - }; - - UIManager.Add(_colorPickerBox); - - _colorPickerBox.ColorSelectedIndex += ColorPickerBoxOnColorSelectedIndex; - _colorPickerBox.MouseUp += ColorPickerBoxOnMouseUp; - } - } - } - - private void ColorPickerBoxOnColorSelectedIndex(object sender, EventArgs e) - { - ColorSelected?.Invoke(this, new ColorSelectedEventArgs(_layer, _colorPickerBox.Hues, _colorPickerBox.SelectedIndex)); - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CreateCharCityGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CreateCharCityGump.cs deleted file mode 100644 index ece95bb5f..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CreateCharCityGump.cs +++ /dev/null @@ -1,409 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using Microsoft.Xna.Framework; -using MathHelper = ClassicUO.Utility.MathHelper; - -namespace ClassicUO.Game.UI.Gumps.CharCreation -{ - internal class CreateCharSelectionCityGump : Gump - { - private readonly List _cityControls = new List(); - private readonly string[] _cityNames = { "Felucca", "Trammel", "Ilshenar", "Malas", "Tokuno", "Ter Mur" }; - private readonly Label _facetName; - private readonly HtmlControl _htmlControl; - private readonly LoginScene _scene; - private CityInfo _selectedCity; - private readonly byte _selectedProfession; - - private readonly Point[] _townButtonsText = - { - new Point(105, 130), - new Point(245, 90), - new Point(165, 200), - new Point(395, 160), - new Point(200, 305), - new Point(335, 250), - new Point(160, 395), - new Point(100, 250), - new Point(270, 130) - }; - - public CreateCharSelectionCityGump(byte profession, LoginScene scene) : base(0, 0) - { - CanMove = false; - CanCloseWithRightClick = false; - CanCloseWithEsc = false; - - _scene = scene; - _selectedProfession = profession; - - CityInfo city; - - if (Client.Version >= ClientVersion.CV_70130) - { - city = scene.GetCity(0); - } - else - { - city = scene.GetCity(3); - - if (city == null) - { - city = scene.GetCity(0); - } - } - - if (city == null) - { - Log.Error(ResGumps.NoCityFound); - Dispose(); - - return; - } - - uint map = 0; - - if (city.IsNewCity) - { - map = city.Map; - } - - _facetName = new Label - ( - "", - true, - 0x0481, - font: 0, - style: FontStyle.BlackBorder - ) - { - X = 240, - Y = 440 - }; - - - if (Client.Version >= ClientVersion.CV_70130) - { - Add(new GumpPic(62, 54, (ushort) (0x15D9 + map), 0)); - Add(new GumpPic(57, 49, 0x15DF, 0)); - _facetName.Text = _cityNames[map]; - } - else - { - Add(new GumpPic(57, 49, 0x1598, 0)); - _facetName.IsVisible = false; - } - - if (CUOEnviroment.IsOutlands) - { - _facetName.IsVisible = false; - } - - Add(_facetName); - - - Add - ( - new Button((int) Buttons.PreviousScreen, 0x15A1, 0x15A3, 0x15A2) - { - X = 586, - Y = 445, - ButtonAction = ButtonAction.Activate - } - ); - - Add - ( - new Button((int) Buttons.Finish, 0x15A4, 0x15A6, 0x15A5) - { - X = 610, - Y = 445, - ButtonAction = ButtonAction.Activate - } - ); - - - _htmlControl = new HtmlControl - ( - 452, - 60, - 175, - 367, - true, - true, - ishtml: true, - text: city.Description - ); - - Add(_htmlControl); - - if (CUOEnviroment.IsOutlands) - { - _htmlControl.IsVisible = false; - } - - for (int i = 0; i < scene.Cities.Length; i++) - { - CityInfo c = scene.GetCity(i); - - if (c == null) - { - continue; - } - - int x = 0; - int y = 0; - - if (c.IsNewCity) - { - uint cityFacet = c.Map; - - if (cityFacet > 5) - { - cityFacet = 5; - } - - x = 62 + MathHelper.PercetangeOf(MapLoader.Instance.MapsDefaultSize[cityFacet, 0] - 2048, c.X, 383); - y = 54 + MathHelper.PercetangeOf(MapLoader.Instance.MapsDefaultSize[cityFacet, 1], c.Y, 384); - } - else if (i < _townButtonsText.Length) - { - x = _townButtonsText[i].X; - - y = _townButtonsText[i].Y; - } - - CityControl control = new CityControl(c, x, y, i); - Add(control); - _cityControls.Add(control); - - if (CUOEnviroment.IsOutlands) - { - control.IsVisible = false; - } - } - - SetCity(city); - } - - - private void SetCity(int index) - { - SetCity(_scene.GetCity(index)); - } - - private void SetCity(CityInfo city) - { - if (city == null) - { - return; - } - - _selectedCity = city; - _htmlControl.Text = city.Description; - SetFacet(city.Map); - } - - private void SetFacet(uint index) - { - if (Client.Version < ClientVersion.CV_70130) - { - return; - } - - if (index >= _cityNames.Length) - { - index = (uint) (_cityNames.Length - 1); - } - - _facetName.Text = _cityNames[index]; - } - - - public override void OnButtonClick(int buttonID) - { - CharCreationGump charCreationGump = UIManager.GetGump(); - - if (charCreationGump == null) - { - return; - } - - switch ((Buttons) buttonID) - { - case Buttons.PreviousScreen: - charCreationGump.StepBack(_selectedProfession > 0 ? 2 : 1); - - return; - - case Buttons.Finish: - - if (_selectedCity != null) - { - charCreationGump.SetCity(_selectedCity.Index); - } - - charCreationGump.CreateCharacter(_selectedProfession); - charCreationGump.IsVisible = false; - - return; - } - - if (buttonID >= 2) - { - buttonID -= 2; - SetCity(buttonID); - SetSelectedLabel(buttonID); - } - } - - private void SetSelectedLabel(int index) - { - for (int i = 0; i < _cityControls.Count; i++) - { - _cityControls[i].IsSelected = index == i; - } - } - - private enum Buttons - { - PreviousScreen, - Finish - } - - private class CityControl : Control - { - private readonly Button _button; - private bool _isSelected; - private readonly HoveredLabel _label; - - public CityControl(CityInfo c, int x, int y, int index) - { - CanMove = false; - - - Add - ( - _button = new Button(2 + index, 0x04B9, 0x04BA, 0x04BA) - { - ButtonAction = ButtonAction.Activate, - X = x, - Y = y - } - ); - - y -= 20; - - _label = new HoveredLabel - ( - c.City, - false, - 0x0058, - 0x0099, - 0x0481, - font: 3 - ) - { - X = x, - Y = y, - Tag = index - }; - - if (_label.X + _label.Width >= 383) - { - _label.X -= 60; - } - - _label.MouseUp += (sender, e) => - { - _label.IsSelected = true; - int idx = (int) _label.Tag; - OnButtonClick(idx + 2); - }; - - Add(_label); - } - - - public bool IsSelected - { - get => _isSelected; - set - { - if (_isSelected != value) - { - _isSelected = value; - _label.IsSelected = value; - _button.IsClicked = value; - } - } - } - - - public override void Update() - { - base.Update(); - - if (!_isSelected) - { - _button.IsClicked = _button.MouseIsOver || _label.MouseIsOver; - _label.ForceHover = _button.MouseIsOver; - } - } - - public override bool Contains(int x, int y) - { - Control c = null; - _label.HitTest(x, y, ref c); - - if (c != null) - { - return true; - } - - _button.HitTest(x, y, ref c); - - return c != null; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CreateCharProfessionGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CreateCharProfessionGump.cs deleted file mode 100644 index bc4ed5d3d..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CreateCharProfessionGump.cs +++ /dev/null @@ -1,210 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Configuration; -using System.Collections.Generic; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; - -namespace ClassicUO.Game.UI.Gumps.CharCreation -{ - internal class CreateCharProfessionGump : Gump - { - private readonly ProfessionInfo _Parent; - - public CreateCharProfessionGump(ProfessionInfo parent = null) : base(0, 0) - { - _Parent = parent; - - if (parent == null || !ProfessionLoader.Instance.Professions.TryGetValue(parent, out List professions) || professions == null) - { - professions = new List(ProfessionLoader.Instance.Professions.Keys); - } - - /* Build the gump */ - Add - ( - new ResizePic(2600) - { - X = 100, - Y = 80, - Width = 470, - Height = 372 - } - ); - - Add(new GumpPic(291, 42, 0x0589, 0)); - Add(new GumpPic(214, 58, 0x058B, 0)); - Add(new GumpPic(300, 51, 0x15A9, 0)); - - ClilocLoader localization = ClilocLoader.Instance; - - bool isAsianLang = string.Compare(Settings.GlobalSettings.Language, "CHT", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "KOR", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "JPN", StringComparison.InvariantCultureIgnoreCase) == 0; - - bool unicode = isAsianLang; - byte font = (byte)(isAsianLang ? 1 : 2); - ushort hue = (ushort)(isAsianLang ? 0xFFFF : 0x0386); - - Add - ( - new Label(localization.GetString(3000326, "Choose a Trade for Your Character"), unicode, hue, font: font) - { - X = 158, - Y = 132 - } - ); - - for (int i = 0; i < professions.Count; i++) - { - int cx = i % 2; - int cy = i >> 1; - - Add - ( - new ProfessionInfoGump(professions[i]) - { - X = 145 + cx * 195, - Y = 168 + cy * 70, - - Selected = SelectProfession - } - ); - } - - Add - ( - new Button((int) Buttons.Prev, 0x15A1, 0x15A3, 0x15A2) - { - X = 586, - Y = 445, - ButtonAction = ButtonAction.Activate - } - ); - } - - public void SelectProfession(ProfessionInfo info) - { - if (info.Type == ProfessionLoader.PROF_TYPE.CATEGORY && ProfessionLoader.Instance.Professions.TryGetValue(info, out List list) && list != null) - { - Parent.Add(new CreateCharProfessionGump(info)); - Parent.Remove(this); - } - else - { - CharCreationGump charCreationGump = UIManager.GetGump(); - - charCreationGump?.SetProfession(info); - } - } - - public override void OnButtonClick(int buttonID) - { - switch ((Buttons) buttonID) - { - case Buttons.Prev: - - { - if (_Parent != null && _Parent.TopLevel) - { - Parent.Add(new CreateCharProfessionGump()); - Parent.Remove(this); - } - else - { - Parent.Remove(this); - CharCreationGump charCreationGump = UIManager.GetGump(); - charCreationGump?.StepBack(); - } - - break; - } - } - - base.OnButtonClick(buttonID); - } - - private enum Buttons - { - Prev - } - } - - internal class ProfessionInfoGump : Control - { - private readonly ProfessionInfo _info; - - public ProfessionInfoGump(ProfessionInfo info) - { - _info = info; - - ClilocLoader localization = ClilocLoader.Instance; - - ResizePic background = new ResizePic(3000) - { - Width = 175, - Height = 34 - }; - - background.SetTooltip(localization.GetString(info.Description), 250); - - Add(background); - - Add - ( - new Label(localization.GetString(info.Localization), true, 0x00, font: 1) - { - X = 7, - Y = 8 - } - ); - - Add(new GumpPic(121, -12, info.Graphic, 0)); - } - - public Action Selected; - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - base.OnMouseUp(x, y, button); - - if (button == MouseButtonType.Left) - { - Selected?.Invoke(_info); - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CreateCharTradeGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CreateCharTradeGump.cs deleted file mode 100644 index eb6d01cc3..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/CharCreation/CreateCharTradeGump.cs +++ /dev/null @@ -1,370 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Linq; -using System; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Assets; -using ClassicUO.Resources; -using System.Collections.Generic; -using ClassicUO.Utility; - -namespace ClassicUO.Game.UI.Gumps.CharCreation -{ - internal class CreateCharTradeGump : Gump - { - private readonly HSliderBar[] _attributeSliders; - private readonly PlayerMobile _character; - private readonly Combobox[] _skillsCombobox; - private readonly HSliderBar[] _skillSliders; - private readonly List _skillList; - - - - public CreateCharTradeGump(PlayerMobile character, ProfessionInfo profession) : base(0, 0) - { - _character = character; - - foreach (Skill skill in _character.Skills) - { - skill.ValueFixed = 0; - skill.BaseFixed = 0; - skill.CapFixed = 0; - skill.Lock = Lock.Locked; - } - - Add - ( - new ResizePic(2600) - { - X = 100, Y = 80, Width = 470, Height = 372 - } - ); - - // center menu with fancy top - // public GumpPic(AControl parent, int x, int y, int gumpID, int hue) - Add(new GumpPic(291, 42, 0x0589, 0)); - Add(new GumpPic(214, 58, 0x058B, 0)); - Add(new GumpPic(300, 51, 0x15A9, 0)); - - bool isAsianLang = string.Compare(Settings.GlobalSettings.Language, "CHT", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "KOR", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "JPN", StringComparison.InvariantCultureIgnoreCase) == 0; - - bool unicode = isAsianLang; - byte font = (byte)(isAsianLang ? 1 : 2); - ushort hue = (ushort)(isAsianLang ? 0xFFFF : 0x0386); - - // title text - //TextLabelAscii(AControl parent, int x, int y, int font, int hue, string text, int width = 400) - Add - ( - new Label(ClilocLoader.Instance.GetString(3000326), unicode, hue, font: font) - { - X = 148, Y = 132 - } - ); - - // strength, dexterity, intelligence - Add - ( - new Label(ClilocLoader.Instance.GetString(3000111), unicode, 1, font: 1) - { - X = 158, Y = 170 - } - ); - - Add - ( - new Label(ClilocLoader.Instance.GetString(3000112), unicode, 1, font: 1) - { - X = 158, Y = 250 - } - ); - - Add - ( - new Label(ClilocLoader.Instance.GetString(3000113), unicode, 1, font: 1) - { - X = 158, Y = 330 - } - ); - - // sliders for attributes - _attributeSliders = new HSliderBar[3]; - - Add - ( - _attributeSliders[0] = new HSliderBar - ( - 164, - 196, - 93, - 10, - 60, - ProfessionInfo._VoidStats[0], - HSliderBarStyle.MetalWidgetRecessedBar, - true - ) - ); - - Add - ( - _attributeSliders[1] = new HSliderBar - ( - 164, - 276, - 93, - 10, - 60, - ProfessionInfo._VoidStats[1], - HSliderBarStyle.MetalWidgetRecessedBar, - true - ) - ); - - Add - ( - _attributeSliders[2] = new HSliderBar - ( - 164, - 356, - 93, - 10, - 60, - ProfessionInfo._VoidStats[2], - HSliderBarStyle.MetalWidgetRecessedBar, - true - ) - ); - - var clientFlags = World.ClientLockedFeatures.Flags; - - _skillList = SkillsLoader.Instance.SortedSkills - .Where(s => - // All standard client versions ignore these skills by defualt - //s.Index != 26 && // MagicResist - s.Index != 47 && // Stealth - s.Index != 48 && // RemoveTrap - s.Index != 54 && // Spellweaving - (character.Race == RaceType.GARGOYLE || s.Index != 57) // Throwing for gargoyle only - ) - .Where(s => - clientFlags.HasFlag(LockedFeatureFlags.ExpansionAOS) || - ( - s.Index != 51 && // Chivlary - s.Index != 50 && // Focus - s.Index != 49 // Necromancy - ) - ) - - .Where(s => - clientFlags.HasFlag(LockedFeatureFlags.ExpansionSE) || - ( - s.Index != 52 && // Bushido - s.Index != 53 // Ninjitsu - ) - ) - - .Where(s => - clientFlags.HasFlag(LockedFeatureFlags.ExpansionSA) || - ( - s.Index != 55 && // Mysticism - s.Index != 56 // Imbuing - ) - ) - .ToList(); - - // do not include archer if it's a gargoyle - if (character.Race == RaceType.GARGOYLE) - { - var archeryEntry = _skillList.FirstOrDefault(s => s.Index == 31); - if (archeryEntry != null) - { - _skillList.Remove(archeryEntry); - } - } - - var skillNames = _skillList.Select(s => s.Name).ToArray(); - - int y = 172; - _skillSliders = new HSliderBar[CharCreationGump._skillsCount]; - _skillsCombobox = new Combobox[CharCreationGump._skillsCount]; - - for (int i = 0; i < CharCreationGump._skillsCount; i++) - { - Add - ( - _skillsCombobox[i] = new Combobox - ( - 344, - y, - 182, - skillNames, - -1, - 200, - false, - "Click here" - ) - ); - - Add - ( - _skillSliders[i] = new HSliderBar - ( - 344, - y + 32, - 93, - 0, - 50, - ProfessionInfo._VoidSkills[i, 1], - HSliderBarStyle.MetalWidgetRecessedBar, - true - ) - ); - - y += 70; - } - - Add - ( - new Button((int) Buttons.Prev, 0x15A1, 0x15A3, 0x15A2) - { - X = 586, Y = 445, ButtonAction = ButtonAction.Activate - } - ); - - Add - ( - new Button((int) Buttons.Next, 0x15A4, 0x15A6, 0x15A5) - { - X = 610, Y = 445, ButtonAction = ButtonAction.Activate - } - ); - - for (int i = 0; i < _attributeSliders.Length; i++) - { - for (int j = 0; j < _attributeSliders.Length; j++) - { - if (i != j) - { - _attributeSliders[i].AddParisSlider(_attributeSliders[j]); - } - } - } - - for (int i = 0; i < _skillSliders.Length; i++) - { - for (int j = 0; j < _skillSliders.Length; j++) - { - if (i != j) - { - _skillSliders[i].AddParisSlider(_skillSliders[j]); - } - } - } - } - - public override void OnButtonClick(int buttonID) - { - CharCreationGump charCreationGump = UIManager.GetGump(); - - switch ((Buttons) buttonID) - { - case Buttons.Prev: - charCreationGump.StepBack(); - - break; - - case Buttons.Next: - - if (ValidateValues()) - { - for (int i = 0; i < _skillsCombobox.Length; i++) - { - if (_skillsCombobox[i].SelectedIndex != -1) - { - Skill skill = _character.Skills[_skillList[_skillsCombobox[i].SelectedIndex].Index]; - skill.ValueFixed = (ushort) _skillSliders[i].Value; - skill.BaseFixed = 0; - skill.CapFixed = 0; - skill.Lock = Lock.Locked; - } - } - - _character.Strength = (ushort) _attributeSliders[0].Value; - _character.Intelligence = (ushort) _attributeSliders[1].Value; - _character.Dexterity = (ushort) _attributeSliders[2].Value; - - charCreationGump.SetAttributes(true); - } - - break; - } - - base.OnButtonClick(buttonID); - } - - private bool ValidateValues() - { - if (_skillsCombobox.All(s => s.SelectedIndex >= 0)) - { - int duplicated = _skillsCombobox.GroupBy(o => o.SelectedIndex).Count(o => o.Count() > 1); - - if (duplicated > 0) - { - UIManager.GetGump()?.ShowMessage(ClilocLoader.Instance.GetString(1080032)); - - return false; - } - } - else - { - UIManager.GetGump()?.ShowMessage(Client.Version <= ClientVersion.CV_5090 ? ResGumps.YouMustHaveThreeUniqueSkillsChosen : ClilocLoader.Instance.GetString(1080032)); - - return false; - } - - return true; - } - - private enum Buttons - { - Prev, - Next - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/ChatGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/ChatGump.cs deleted file mode 100644 index 5affaa89f..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/ChatGump.cs +++ /dev/null @@ -1,537 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Network; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class ChatGump : Gump - { - private ChannelCreationBox _channelCreationBox; - - private readonly List _channelList = new List(); - private readonly Label _currentChannelLabel; - private readonly DataBox _databox; - private string _selectedChannelText; - - public ChatGump() : base(0, 0) - { - CanMove = true; - AcceptMouseInput = true; - CanCloseWithRightClick = true; - WantUpdateSize = false; - Width = 345; - Height = 390; - - Add - ( - new ResizePic(0x0A28) - { - Width = Width, - Height = Height - } - ); - - int startY = 25; - - Label text = new Label - ( - ResGumps.Channels, - false, - 0x0386, - 345, - 2, - FontStyle.None, - TEXT_ALIGN_TYPE.TS_CENTER - ) - { - Y = startY - }; - - Add(text); - - startY += 40; - - Add - ( - new BorderControl - ( - 61, - startY - 3, - 220 + 8, - 200 + 6, - 3 - ) - ); - - Add(new AlphaBlendControl(1f) { X = 64, Y = startY, Width = 220, Height = 200 }); - - ScrollArea area = new ScrollArea - ( - 64, - startY, - 220, - 200, - true - ) - { - ScrollbarBehaviour = ScrollbarBehaviour.ShowAlways - }; - - Add(area); - - _databox = new DataBox(0, 0, 1, 1); - _databox.WantUpdateSize = true; - area.Add(_databox); - - foreach (KeyValuePair k in ChatManager.Channels) - { - ChannelListItemControl chan = new ChannelListItemControl(k.Key, 195); - _databox.Add(chan); - _channelList.Add(chan); - } - - _databox.ReArrangeChildren(); - - startY = 275; - - text = new Label - ( - ResGumps.YourCurrentChannel, - false, - 0x0386, - 345, - 2, - FontStyle.None, - TEXT_ALIGN_TYPE.TS_CENTER - ) - { - Y = startY - }; - - Add(text); - - startY += 25; - - _currentChannelLabel = new Label - ( - ChatManager.CurrentChannelName, - false, - 0x0386, - 345, - 2, - FontStyle.None, - TEXT_ALIGN_TYPE.TS_CENTER - ) - { - Y = startY - }; - - Add(_currentChannelLabel); - - - startY = 337; - - Button button = new Button(0, 0x0845, 0x0846, 0x0845) - { - X = 48, - Y = startY + 5, - ButtonAction = ButtonAction.Activate - }; - - Add(button); - - button = new Button(1, 0x0845, 0x0846, 0x0845) - { - X = 123, - Y = startY + 5, - ButtonAction = ButtonAction.Activate - }; - - Add(button); - - button = new Button(2, 0x0845, 0x0846, 0x0845) - { - X = 216, - Y = startY + 5, - ButtonAction = ButtonAction.Activate - }; - - Add(button); - - text = new Label - ( - ResGumps.Join, - false, - 0x0386, - 0, - 2 - ) - { - X = 65, - Y = startY - }; - - Add(text); - - text = new Label - ( - ResGumps.Leave, - false, - 0x0386, - 0, - 2 - ) - { - X = 140, - Y = startY - }; - - Add(text); - - text = new Label - ( - ResGumps.Create, - false, - 0x0386, - 0, - 2 - ) - { - X = 233, - Y = startY - }; - - Add(text); - } - - public override void OnButtonClick(int buttonID) - { - switch (buttonID) - { - case 0: // join - if (!string.IsNullOrEmpty(_selectedChannelText)) - { - NetClient.Socket.Send_ChatJoinCommand(_selectedChannelText); - } - - break; - - case 1: // leave - NetClient.Socket.Send_ChatLeaveChannelCommand(); - - break; - - case 2: // create - if (_channelCreationBox == null || _channelCreationBox.IsDisposed) - { - _channelCreationBox = new ChannelCreationBox(Width / 2, Height / 2); - Add(_channelCreationBox); - } - - break; - } - } - - public void UpdateConference() - { - if (_currentChannelLabel.Text != ChatManager.CurrentChannelName) - { - _currentChannelLabel.Text = ChatManager.CurrentChannelName; - } - } - - protected override void UpdateContents() - { - foreach (ChannelListItemControl control in _channelList) - { - control.Dispose(); - } - - _channelList.Clear(); - - foreach (KeyValuePair k in ChatManager.Channels) - { - ChannelListItemControl c = new ChannelListItemControl(k.Key, 195); - _databox.Add(c); - _channelList.Add(c); - } - - _databox.WantUpdateSize = true; - _databox.ReArrangeChildren(); - } - - private void OnChannelSelected(string text) - { - _selectedChannelText = text; - - foreach (ChannelListItemControl control in _channelList) - { - control.IsSelected = control.Text == text; - } - } - - private class ChannelCreationBox : Control - { - private readonly StbTextBox _textBox; - - public ChannelCreationBox(int x, int y) - { - CanMove = true; - AcceptMouseInput = true; - AcceptKeyboardInput = false; - - Width = 200; - Height = 60; - X = x - Width / 2; - Y = y - Height / 2; - - - const int BORDER_SIZE = 3; - const int ROW_HEIGHT = 25; - - Add(new AlphaBlendControl(1f) { Width = Width, Height = Height }); - - Add - ( - new BorderControl - ( - 0, - 0, - Width, - ROW_HEIGHT, - BORDER_SIZE - ) - ); - - Label text = new Label - ( - ResGumps.CreateAChannel, - true, - 0x23, - Width - 4, - 1 - ) - { - X = 6, - Y = BORDER_SIZE - }; - - Add(text); - - Add - ( - new BorderControl - ( - 0, - ROW_HEIGHT - BORDER_SIZE, - Width, - ROW_HEIGHT, - BORDER_SIZE - ) - ); - - text = new Label - ( - ResGumps.Name, - true, - 0x23, - Width - 4, - 1 - ) - { - X = 6, - Y = ROW_HEIGHT - }; - - Add(text); - - _textBox = new StbTextBox - ( - 1, - -1, - Width - 50, - hue: 0x0481, - style: FontStyle.Fixed - ) - { - X = 45, - Y = ROW_HEIGHT, - Width = Width - 50, - Height = ROW_HEIGHT - BORDER_SIZE * 2 - }; - - Add(_textBox); - - Add - ( - new BorderControl - ( - 0, - ROW_HEIGHT * 2 - BORDER_SIZE * 2, - Width, - ROW_HEIGHT, - BORDER_SIZE - ) - ); - - // close - Add - ( - new Button(0, 0x0A94, 0x0A95, 0x0A94) - { - X = Width - 19 - BORDER_SIZE, - Y = Height - 19 + BORDER_SIZE * 2, - ButtonAction = ButtonAction.Activate - } - ); - - // ok - Add - ( - new Button(1, 0x0A9A, 0x0A9B, 0x0A9A) - { - X = Width - 19 * 2 - BORDER_SIZE, - Y = Height - 19 + BORDER_SIZE * 2, - ButtonAction = ButtonAction.Activate - } - ); - } - - - public override void OnButtonClick(int buttonID) - { - if (buttonID == 0) // close - { - } - else if (buttonID == 1) // ok - { - NetClient.Socket.Send_ChatCreateChannelCommand(_textBox.Text); - } - - Dispose(); - } - } - - private class ChannelListItemControl : Control - { - private bool _isSelected; - private readonly Label _label; - - public ChannelListItemControl(string text, int width) - { - Text = text; - Width = width; - - Add - ( - _label = new Label - ( - text, - false, - 0x49, - Width, - 3 - ) - { - X = 3 - } - ); - - Height = _label.Height; - } - - public bool IsSelected - { - get => _isSelected; - set - { - if (_isSelected != value) - { - _isSelected = value; - _label.Hue = (ushort) (value ? 0x22 : 0x49); - } - } - } - - public readonly string Text; - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - base.OnMouseUp(x, y, button); - - if (RootParent is ChatGump g) - { - g.OnChannelSelected(Text); - } - } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - base.OnButtonClick(0); - - return true; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - if (MouseIsOver) - { - batcher.Draw - ( - SolidColorTextureCache.GetTexture(Color.Cyan), - new Rectangle - ( - x, - y, - Width, - Height - ), - hueVector - ); - } - - return base.Draw(batcher, x, y); - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/ChatGumpChooseName.cs b/src/ClassicUO.Client/Game/UI/Gumps/ChatGumpChooseName.cs deleted file mode 100644 index d1210219e..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/ChatGumpChooseName.cs +++ /dev/null @@ -1,193 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.UI.Controls; -using ClassicUO.Network; -using ClassicUO.Renderer; -using ClassicUO.Resources; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class ChatGumpChooseName : Gump - { - private readonly StbTextBox _textBox; - - public ChatGumpChooseName() : base(0, 0) - { - CanMove = false; - AcceptKeyboardInput = true; - AcceptMouseInput = true; - WantUpdateSize = true; - - X = 250; - Y = 100; - Width = 210; - Height = 330; - - Add - ( - new AlphaBlendControl - { - Alpha = 1f, - Width = Width, - Height = Height - } - ); - - Add - ( - new BorderControl - ( - 0, - 0, - Width, - Height, - 4 - ) - ); - - Label text = new Label - ( - ResGumps.ChooseName, - true, - 23, - Width - 17, - 3 - ) - { - X = 6, - Y = 6 - }; - - Add(text); - - int BORDER_SIZE = 4; - - BorderControl border = new BorderControl - ( - 0, - text.Y + text.Height, - Width, - 27, - BORDER_SIZE - ); - - Add(border); - - text = new Label - ( - ResGumps.Name, - true, - 0x033, - 0, - 3 - ) - { - X = 6, - Y = border.Y + 2 - }; - - Add(text); - - int x = text.X + text.Width + 2; - - _textBox = new StbTextBox - ( - 1, - -1, - Width - x - 17, - true, - FontStyle.Fixed, - 0x0481 - ) - { - X = x, - Y = text.Y, - Width = Width - -x - 17, - Height = 27 - BORDER_SIZE * 2 - }; - - Add(_textBox); - - Add - ( - new BorderControl - ( - 0, - text.Y + text.Height, - Width, - 27, - BORDER_SIZE - ) - ); - - // close - Add - ( - new Button(0, 0x0A94, 0x0A95, 0x0A94) - { - X = Width - 19 - BORDER_SIZE, - Y = Height - 19 - BORDER_SIZE * 1, - ButtonAction = ButtonAction.Activate - } - ); - - // ok - Add - ( - new Button(1, 0x0A9A, 0x0A9B, 0x0A9A) - { - X = Width - 19 * 2 - BORDER_SIZE, - Y = Height - 19 - BORDER_SIZE * 1, - ButtonAction = ButtonAction.Activate - } - ); - } - - - public override void OnButtonClick(int buttonID) - { - if (buttonID == 0) // close - { - } - else if (buttonID == 1) // ok - { - if (!string.IsNullOrWhiteSpace(_textBox.Text)) - { - NetClient.Socket.Send_OpenChat(_textBox.Text); - } - } - - Dispose(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/ColorPickerGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/ColorPickerGump.cs deleted file mode 100644 index 878f7ad35..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/ColorPickerGump.cs +++ /dev/null @@ -1,119 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Network; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class ColorPickerGump : Gump - { - private const int SLIDER_MIN = 0; - private const int SLIDER_MAX = 4; - private readonly ColorPickerBox _box; - private readonly StaticPic _dyeTybeImage; - - private readonly ushort _graphic; - private readonly Action _okClicked; - - public ColorPickerGump(uint serial, ushort graphic, int x, int y, Action okClicked) : base(serial, 0) - { - CanCloseWithRightClick = serial == 0; - _graphic = graphic; - CanMove = true; - AcceptMouseInput = false; - X = x; - Y = y; - Add(new GumpPic(0, 0, 0x0906, 0)); - - Add - ( - new Button(0, 0x0907, 0x0908, 0x909) - { - X = 208, Y = 138, ButtonAction = ButtonAction.Activate - } - ); - - HSliderBar slider; - - Add - ( - slider = new HSliderBar - ( - 39, - 142, - 145, - SLIDER_MIN, - SLIDER_MAX, - 1, - HSliderBarStyle.BlueWidgetNoBar - ) - ); - - slider.ValueChanged += (sender, e) => { _box.Graduation = slider.Value; }; - Add(_box = new ColorPickerBox(34, 34)); - _box.ColorSelectedIndex += (sender, e) => { _dyeTybeImage.Hue = _box.SelectedHue; }; - - Add - ( - _dyeTybeImage = new StaticPic(0x0FAB, 0) - { - X = 200, Y = 58 - } - ); - - _okClicked = okClicked; - _dyeTybeImage.Hue = _box.SelectedHue; - } - - public ushort Graphic => _graphic; - - public override void OnButtonClick(int buttonID) - { - switch (buttonID) - { - case 0: - - if (LocalSerial != 0) - { - NetClient.Socket.Send_DyeDataResponse(LocalSerial, _graphic, _box.SelectedHue); - } - - _okClicked?.Invoke(_box.SelectedHue); - Dispose(); - - break; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/CombatBookGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/CombatBookGump.cs deleted file mode 100644 index b6b023848..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/CombatBookGump.cs +++ /dev/null @@ -1,843 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class CombatBookGump : Gump - { - private readonly int _abilityCount = Constants.MAX_ABILITIES_COUNT; - private int _dictionaryPagesCount = 3; - private GumpPic _pageCornerLeft, _pageCornerRight, _primAbility, _secAbility; - private int _enqueuePage = -1; - - public CombatBookGump(int x, int y) : base(0, 0) - { - X = x; - Y = y; - - CanMove = true; - CanCloseWithRightClick = true; - - if (Client.Version < ClientVersion.CV_7000) - { - if (Client.Version < ClientVersion.CV_500A) - { - _abilityCount = 29; - } - else - { - _abilityCount = 13; - _dictionaryPagesCount = 1; - } - } - - BuildGump(); - SetActivePage(1); - } - - private void BuildGump() - { - Add(new GumpPic(0, 0, 0x2B02, 0)); - - - Add(_pageCornerLeft = new GumpPic(50, 8, 0x08BB, 0)); - _pageCornerLeft.LocalSerial = 0; - _pageCornerLeft.Page = int.MaxValue; - _pageCornerLeft.MouseUp += PageCornerOnMouseClick; - _pageCornerLeft.MouseDoubleClick += PageCornerOnMouseDoubleClick; - Add(_pageCornerRight = new GumpPic(321, 8, 0x08BC, 0)); - _pageCornerRight.LocalSerial = 1; - _pageCornerRight.Page = 1; - _pageCornerRight.MouseUp += PageCornerOnMouseClick; - _pageCornerRight.MouseDoubleClick += PageCornerOnMouseDoubleClick; - - int offs = 0; - - int maxPages = _dictionaryPagesCount + 1; - - for (int page = 1; page <= _dictionaryPagesCount; page++) - { - for (int j = 0; j < 2; j++) - { - int indexX = 96; - int dataX = 52; - int y = 0; - int spellsOnPage = 9; - - if (j % 2 != 0) - { - indexX = 259; - dataX = 215; - spellsOnPage = 4; - } - - Label text = new Label(ResGumps.Index, false, 0x0288, font: 6) { X = indexX, Y = 6 }; - Add(text, page); - - for (int i = 0; i < spellsOnPage; i++) - { - if (offs >= _abilityCount) - { - break; - } - - text = new HoveredLabel - ( - AbilityData.Abilities[offs].Name, - false, - 0x0288, - 0x33, - 0x0288, - font: 9 - ) - { - X = dataX, Y = 42 + y, AcceptMouseInput = true, - LocalSerial = (uint) maxPages++, - Tag = offs - }; - - text.MouseUp += (s, e) => - { - if (s is HoveredLabel l && e.Button == MouseButtonType.Left) - { - _enqueuePage = (int)l.LocalSerial; - } - }; - - Add(text, page); - text.SetTooltip(ClilocLoader.Instance.GetString(1061693 + offs), 150); - - y += 15; - offs++; - } - - if (spellsOnPage == 4) - { - if(_primAbility == null) - { - byte bab1 = (byte)(((byte)World.Player.PrimaryAbility & 0x7F) - 1); - _primAbility = new GumpPic(215, 105, (ushort)(0x5200 + bab1), (ushort)(((byte)World.Player.PrimaryAbility & 0x80) != 0 ? 38 : 0)); - _primAbility.SetTooltip(ClilocLoader.Instance.GetString(1028838 + bab1)); - _primAbility.DragBegin += OnGumpicDragBeginPrimary; - _primAbility.MouseDoubleClick += PrimaryAbilityMouseDoubleClick; - } - - text = new Label - ( - ResGumps.PrimaryAbilityIcon, - false, - 0x0288, - 80, - 6 - ) { X = 265, Y = 105 }; - - Add(text, page); - Add(_primAbility, page); - - - if (_secAbility == null) - { - byte bab2 = (byte)(((byte)World.Player.SecondaryAbility & 0x7F) - 1); - _secAbility = new GumpPic(215, 150, (ushort)(0x5200 + bab2), (ushort)(((byte)World.Player.SecondaryAbility & 0x80) != 0 ? 38 : 0)); - _secAbility.SetTooltip(ClilocLoader.Instance.GetString(1028838 + bab2)); - _secAbility.DragBegin += OnGumpicDragBeginSecondary; - _secAbility.MouseDoubleClick += SecondaryAbilityMouseDoubleClick; - } - - text = new Label - ( - ResGumps.SecondaryAbilityIcon, - false, - 0x0288, - 80, - 6 - ) { X = 265, Y = 150 }; - - - Add(text, page); - Add(_secAbility, page); - } - } - } - - - int pageW = _dictionaryPagesCount + 1; - - _dictionaryPagesCount += _abilityCount; - - for (int i = 0; i < _abilityCount; i++, pageW++) - { - if (i >= AbilityData.Abilities.Length) - { - break; - } - - GumpPic icon = new GumpPic(62, 40, (ushort) (0x5200 + i), 0); - Add(icon, pageW); - icon.SetTooltip(ClilocLoader.Instance.GetString(1061693 + i), 150); - - Label text = new Label - ( - StringHelper.CapitalizeAllWords(AbilityData.Abilities[i].Name), - false, - 0x0288, - 80, - 6 - ) - { - X = 110, - Y = 34 - }; - - Add(text, pageW); - - Add - ( - new GumpPicTiled(0x0835) - { - X = 62, - Y = 88, - Width = 128 - }, - pageW - ); - - - List list = GetItemsList((byte) i); - int maxStaticCount = TileDataLoader.Instance.StaticData.Length; - - int textX = 62; - int textY = 98; - - - for (int j = 0; j < list.Count; j++) - { - if (j == 6) - { - textX = 215; - textY = 34; - } - - ushort id = list[j]; - - if (id >= maxStaticCount) - { - continue; - } - - text = new Label(StringHelper.CapitalizeAllWords(TileDataLoader.Instance.StaticData[id].Name), false, 0x0288, font: 9) - { - X = textX, - Y = textY - }; - - Add(text, pageW); - - textY += 16; - } - } - } - - - private void PrimaryAbilityMouseDoubleClick(object sender, MouseDoubleClickEventArgs e) - { - if (e.Button == MouseButtonType.Left) - { - GameActions.UsePrimaryAbility(); - - e.Result = true; - } - } - - private void SecondaryAbilityMouseDoubleClick(object sender, MouseDoubleClickEventArgs e) - { - if (e.Button == MouseButtonType.Left) - { - GameActions.UseSecondaryAbility(); - - e.Result = true; - } - } - - protected override void OnDragBegin(int x, int y) - { - if (UIManager.MouseOverControl?.RootParent == this) - { - UIManager.MouseOverControl.InvokeDragBegin(new Point(x, y)); - } - - base.OnDragBegin(x, y); - } - - protected override void OnDragEnd(int x, int y) - { - if (UIManager.MouseOverControl?.RootParent == this) - { - UIManager.MouseOverControl.InvokeDragEnd(new Point(x, y)); - } - - base.OnDragEnd(x, y); - } - - private void OnGumpicDragBeginPrimary(object sender, EventArgs e) - { - if (UIManager.DraggingControl != this || UIManager.MouseOverControl != sender) - { - return; - } - - ref readonly AbilityDefinition def = ref AbilityData.Abilities[((byte) World.Player.PrimaryAbility & 0x7F) - 1]; - - GetSpellFloatingButton(def.Index)?.Dispose(); - - UseAbilityButtonGump gump = new UseAbilityButtonGump(true) - { - X = Mouse.LClickPosition.X - 22, - Y = Mouse.LClickPosition.Y - 22 - }; - - UIManager.Add(gump); - UIManager.AttemptDragControl(gump, true); - } - - private void OnGumpicDragBeginSecondary(object sender, EventArgs e) - { - if (UIManager.DraggingControl != this || UIManager.MouseOverControl != sender) - { - return; - } - - ref readonly AbilityDefinition def = ref AbilityData.Abilities[((byte) World.Player.SecondaryAbility & 0x7F) - 1]; - - GetSpellFloatingButton(def.Index)?.Dispose(); - - UseAbilityButtonGump gump = new UseAbilityButtonGump(false) - { - X = Mouse.LClickPosition.X - 22, - Y = Mouse.LClickPosition.Y - 22 - }; - - UIManager.Add(gump); - UIManager.AttemptDragControl(gump, true); - } - - private static UseAbilityButtonGump GetSpellFloatingButton(int id) - { - for (LinkedListNode i = UIManager.Gumps.Last; i != null; i = i.Previous) - { - if (i.Value is UseAbilityButtonGump g && g.Index == id) - { - return g; - } - } - - return null; - } - - public override void Update() - { - base.Update(); - - if (IsDisposed) - { - return; - } - - - byte index = (byte)World.Player.Abilities[0]; - ref readonly AbilityDefinition def = ref AbilityData.Abilities[(index & 0x7F) - 1]; - - if ((index & 0x80) != 0) - { - _primAbility.Hue = 38; - } - else if (_primAbility.Hue != 0) - { - _primAbility.Hue = 0; - } - - if (_primAbility.Graphic != def.Icon) - { - _primAbility.Graphic = def.Icon; - } - - index = (byte)World.Player.Abilities[1]; - def = ref AbilityData.Abilities[(index & 0x7F) - 1]; - - if ((index & 0x80) != 0) - { - _secAbility.Hue = 38; - } - else if (_secAbility.Hue != 0) - { - _secAbility.Hue = 0; - } - - if (_secAbility.Graphic != def.Icon) - { - _secAbility.Graphic = def.Icon; - } - - - if (IsDisposed) - { - return; - } - - if (_enqueuePage >= 0 && Time.Ticks - Mouse.LastLeftButtonClickTime >= Mouse.MOUSE_DELAY_DOUBLE_CLICK) - { - SetActivePage(_enqueuePage); - _enqueuePage = -1; - } - } - - private void PageCornerOnMouseClick(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtonType.Left && sender is Control ctrl) - { - SetActivePage(ctrl.LocalSerial == 0 ? ActivePage - 1 : ActivePage + 1); - } - } - - private void PageCornerOnMouseDoubleClick(object sender, MouseDoubleClickEventArgs e) - { - if (e.Button == MouseButtonType.Left && sender is Control ctrl) - { - SetActivePage(ctrl.LocalSerial == 0 ? 1 : _dictionaryPagesCount); - } - } - - private void SetActivePage(int page) - { - if (page < 1) - { - page = 1; - } - else if (page > _dictionaryPagesCount) - { - page = _dictionaryPagesCount; - } - - ActivePage = page; - _pageCornerLeft.Page = ActivePage != 1 ? 0 : int.MaxValue; - _pageCornerRight.Page = ActivePage != _dictionaryPagesCount ? 0 : int.MaxValue; - - _primAbility.Page = page; - _secAbility.Page = page; - - _primAbility.IsVisible = _secAbility.IsVisible = page <= _dictionaryPagesCount - _abilityCount; - - Client.Game.Audio.PlaySound(0x0055); - } - - - private List GetItemsList(byte index) - { - List list = new List(); - - - switch (index) - { - case 0: - { - list.Add(3908); - list.Add(5048); - list.Add(3935); - list.Add(5119); - list.Add(9927); - list.Add(5181); - list.Add(5040); - list.Add(5121); - list.Add(3939); - list.Add(9932); - list.Add(11554); - list.Add(16497); - list.Add(16502); - list.Add(16494); - list.Add(16491); - - break; - } - - case 1: - { - list.Add(3779); - list.Add(5115); - list.Add(3912); - list.Add(3910); - list.Add(5185); - list.Add(9924); - list.Add(5127); - list.Add(5040); - list.Add(3720); - list.Add(5125); - list.Add(11552); - list.Add(16499); - list.Add(16498); - - break; - } - - case 2: - { - list.Add(5048); - list.Add(3912); - list.Add(5183); - list.Add(5179); - list.Add(3933); - list.Add(5113); - list.Add(3722); - list.Add(9930); - list.Add(3920); - list.Add(11556); - list.Add(16487); - list.Add(16500); - - break; - } - - case 3: - { - list.Add(5050); - list.Add(3914); - list.Add(3935); - list.Add(3714); - list.Add(5092); - list.Add(5179); - list.Add(5127); - list.Add(5177); - list.Add(9926); - list.Add(4021); - list.Add(10146); - list.Add(11556); - list.Add(11560); - list.Add(5109); - list.Add(16500); - list.Add(16495); - - break; - } - - case 4: - { - list.Add(5111); - list.Add(3718); - list.Add(3781); - list.Add(3908); - list.Add(3573); - list.Add(3714); - list.Add(3933); - list.Add(5125); - list.Add(11558); - list.Add(11560); - list.Add(5109); - list.Add(9934); - list.Add(16493); - list.Add(16494); - - break; - } - - case 5: - { - list.Add(3918); - list.Add(3914); - list.Add(9927); - list.Add(3573); - list.Add(5044); - list.Add(3720); - list.Add(9930); - list.Add(5117); - list.Add(16501); - list.Add(16495); - - break; - } - - case 6: - { - list.Add(3718); - list.Add(5187); - list.Add(3916); - list.Add(5046); - list.Add(5119); - list.Add(9931); - list.Add(3722); - list.Add(9929); - list.Add(9933); - list.Add(10148); - list.Add(10153); - list.Add(16488); - list.Add(16493); - list.Add(16496); - - break; - } - - case 7: - { - list.Add(5111); - list.Add(3779); - list.Add(3922); - list.Add(9928); - list.Add(5121); - list.Add(9929); - list.Add(11553); - list.Add(16490); - list.Add(16488); - - break; - } - - case 8: - { - list.Add(3910); - list.Add(9925); - list.Add(9931); - list.Add(5181); - list.Add(9926); - list.Add(5123); - list.Add(3920); - list.Add(5042); - list.Add(16499); - list.Add(16502); - list.Add(16496); - list.Add(16491); - - break; - } - - case 9: - { - list.Add(5117); - list.Add(9932); - list.Add(9933); - list.Add(16492); - - break; - } - - case 10: - { - list.Add(5050); - list.Add(3918); - list.Add(5046); - list.Add(9924); - list.Add(9925); - list.Add(5113); - list.Add(3569); - list.Add(9928); - list.Add(3939); - list.Add(5042); - list.Add(16497); - list.Add(16498); - - break; - } - - case 11: - { - list.Add(3781); - list.Add(5187); - list.Add(5185); - list.Add(5092); - list.Add(5044); - list.Add(3922); - list.Add(5123); - list.Add(4021); - list.Add(11553); - list.Add(16490); - - break; - } - - case 12: - { - list.Add(5115); - list.Add(5183); - list.Add(3916); - list.Add(5177); - list.Add(3569); - list.Add(10157); - list.Add(11559); - list.Add(9934); - list.Add(16501); - - break; - } - - case 13: - { - list.Add(10146); - - break; - } - - case 14: - { - list.Add(10148); - list.Add(10150); - list.Add(10151); - - break; - } - - case 15: - { - list.Add(10147); - list.Add(10158); - list.Add(10159); - list.Add(11557); - - break; - } - - case 16: - { - list.Add(10151); - list.Add(10157); - list.Add(11561); - - break; - } - - case 17: - { - list.Add(10152); - - break; - } - - case 18: - case 20: - { - list.Add(10155); - - break; - } - - case 19: - { - list.Add(10152); - list.Add(10153); - list.Add(10158); - list.Add(11554); - - break; - } - - case 21: - { - list.Add(10149); - - break; - } - - case 22: - { - list.Add(10149); - list.Add(10159); - - break; - } - - case 23: - { - list.Add(11555); - list.Add(11558); - list.Add(11559); - list.Add(11561); - - break; - } - - case 24: - case 27: - { - list.Add(11550); - - break; - } - - case 25: - { - list.Add(11551); - - break; - } - - case 26: - { - list.Add(11551); - list.Add(11552); - - break; - } - - case 28: - { - list.Add(11557); - - break; - } - - case 29: - { - list.Add(16492); - - break; - } - - case 30: - { - list.Add(16487); - - break; - } - } - - return list; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/ContainerGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/ContainerGump.cs deleted file mode 100644 index 12ff0b947..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/ContainerGump.cs +++ /dev/null @@ -1,818 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.IO; -using System.Xml; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class ContainerGump : TextContainerGump - { - private long _corpseEyeTicks; - private ContainerData _data; - private int _eyeCorspeOffset; - private GumpPic _eyeGumpPic; - private GumpPicContainer _gumpPicContainer; - private readonly bool _hideIfEmpty; - private readonly bool showGridToggle = false; - private HitBox _hitBox; - private bool _isMinimized; - private NiceButton returnToGridView; - private bool firstItemsLoaded = false; - - internal const int CORPSES_GUMP = 0x0009; - - public ContainerGump() : base(0, 0) { } - - public ContainerGump(uint serial, ushort gumpid, bool playsound) : base(serial, 0) - { - Item item = World.Items.Get(serial); - - if (item == null) - { - Dispose(); - - return; - } - - Graphic = gumpid; - - // New Backpack gumps. Client Version 7.0.53.1 - if ( - item == World.Player.FindItemByLayer(Layer.Backpack) - && Client.Version >= ClassicUO.Utility.ClientVersion.CV_705301 - && ProfileManager.CurrentProfile != null - ) - { - var gumps = Client.Game.Gumps; - - switch (ProfileManager.CurrentProfile.BackpackStyle) - { - case 1: - if (gumps.GetGump(0x775E).Texture != null) - { - Graphic = 0x775E; // Suede Backpack - } - - break; - case 2: - if (gumps.GetGump(0x7760).Texture != null) - { - Graphic = 0x7760; // Polar Bear Backpack - } - - break; - case 3: - if (gumps.GetGump(0x7762).Texture != null) - { - Graphic = 0x7762; // Ghoul Skin Backpack - } - - break; - default: - if (gumps.GetGump(0x003C).Texture != null) - { - Graphic = 0x003C; // Default Backpack - } - - break; - } - } - - BuildGump(); - - if (Graphic == CORPSES_GUMP) - { - if (World.Player.ManualOpenedCorpses.Contains(LocalSerial)) - { - World.Player.ManualOpenedCorpses.Remove(LocalSerial); - } - else if ( - World.Player.AutoOpenedCorpses.Contains(LocalSerial) - && ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.SkipEmptyCorpse - ) - { - IsVisible = false; - _hideIfEmpty = true; - } - } - - if (_data.OpenSound != 0 && playsound) - { - Client.Game.Audio.PlaySound(_data.OpenSound); - } - } - - public ContainerGump(uint serial, ushort gumpid, bool playsound, bool showGridToggle) : this(serial, gumpid, playsound) - { - this.showGridToggle = showGridToggle; - } - - public ushort Graphic { get; } - - public override GumpType GumpType => GumpType.Container; - - public bool IsMinimized - { - get => _isMinimized; - set - { - //if (_isMinimized != value) - { - _isMinimized = value; - _gumpPicContainer.Graphic = value ? _data.IconizedGraphic : Graphic; - float scale = GetScale(); - - Width = _gumpPicContainer.Width = (int)(_gumpPicContainer.Width * scale); - Height = _gumpPicContainer.Height = (int)(_gumpPicContainer.Height * scale); - - foreach (Control c in Children) - { - c.IsVisible = !value; - } - - _gumpPicContainer.IsVisible = true; - - SetInScreen(); - } - } - } - - public bool IsChessboard => - Graphic - == 0x091A /*|| Graphic == 0x092E*/ - ; - - private void BuildGump() - { - CanMove = true; - CanCloseWithRightClick = true; - WantUpdateSize = false; - - Item item = World.Items.Get(LocalSerial); - - if (item == null) - { - Dispose(); - - return; - } - - float scale = GetScale(); - - _data = ContainerManager.Get(Graphic); - ushort g = _data.Graphic; - - _gumpPicContainer?.Dispose(); - _hitBox?.Dispose(); - - _hitBox = new HitBox( - (int)(_data.MinimizerArea.X * scale), - (int)(_data.MinimizerArea.Y * scale), - (int)(_data.MinimizerArea.Width * scale), - (int)(_data.MinimizerArea.Height * scale) - ); - - _hitBox.MouseUp += HitBoxOnMouseUp; - Add(_hitBox); - - Add(_gumpPicContainer = new GumpPicContainer(0, 0, g, 0)); - _gumpPicContainer.MouseDoubleClick += GumpPicContainerOnMouseDoubleClick; - - if (Graphic == CORPSES_GUMP) - { - _eyeGumpPic?.Dispose(); - Add(_eyeGumpPic = new GumpPic((int)(45 * scale), (int)(30 * scale), 0x0045, 0)); - - _eyeGumpPic.Width = (int)(_eyeGumpPic.Width * scale); - _eyeGumpPic.Height = (int)(_eyeGumpPic.Height * scale); - } - else if (ProfileManager.CurrentProfile.HueContainerGumps) - { - _gumpPicContainer.Hue = item.Hue; - } - - Width = _gumpPicContainer.Width = (int)(_gumpPicContainer.Width * scale); - Height = _gumpPicContainer.Height = (int)(_gumpPicContainer.Height * scale); - - if (showGridToggle) - { - returnToGridView = new NiceButton(0, 0, 20, 20, ButtonAction.Activate, "#") { IsSelectable = false }; - returnToGridView.SetTooltip("Return to grid container view"); - returnToGridView.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - UIManager.GetGump(LocalSerial)?.Dispose(); - GridContainer c; - UIManager.Add(c = new GridContainer(LocalSerial, Graphic, true)); - Dispose(); - } - }; - - Add(returnToGridView); - } - } - - private void HitBoxOnMouseUp(object sender, MouseEventArgs e) - { - if ( - e.Button == MouseButtonType.Left - && !IsMinimized - && !Client.Game.GameCursor.ItemHold.Enabled - ) - { - Point offset = Mouse.LDragOffset; - - if ( - Math.Abs(offset.X) < Constants.MIN_PICKUP_DRAG_DISTANCE_PIXELS - && Math.Abs(offset.Y) < Constants.MIN_PICKUP_DRAG_DISTANCE_PIXELS - ) - { - IsMinimized = true; - } - } - } - - private void GumpPicContainerOnMouseDoubleClick(object sender, MouseDoubleClickEventArgs e) - { - if (e.Button == MouseButtonType.Left && IsMinimized) - { - IsMinimized = false; - e.Result = true; - } - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button != MouseButtonType.Left || UIManager.IsMouseOverWorld) - { - return; - } - - Entity it = SelectedObject.Object as Entity; - uint serial = it != null ? it.Serial : 0; - uint dropcontainer = LocalSerial; - - if ( - TargetManager.IsTargeting - && !Client.Game.GameCursor.ItemHold.Enabled - && SerialHelper.IsValid(serial) - ) - { - TargetManager.Target(serial); - Mouse.CancelDoubleClick = true; - - if (TargetManager.TargetingState == CursorTarget.SetTargetClientSide) - { - UIManager.Add(new InspectorGump(World.Get(serial))); - } - } - else - { - Entity thisCont = World.Items.Get(dropcontainer); - - if (thisCont == null) - { - return; - } - - thisCont = World.Get(((Item)thisCont).RootContainer); - - if (thisCont == null) - { - return; - } - - bool candrop = thisCont.Distance <= Constants.DRAG_ITEMS_DISTANCE; - - if (candrop && SerialHelper.IsValid(serial)) - { - candrop = false; - - if ( - Client.Game.GameCursor.ItemHold.Enabled - && !Client.Game.GameCursor.ItemHold.IsFixedPosition - ) - { - candrop = true; - - Item target = World.Items.Get(serial); - - if (target != null) - { - if (target.ItemData.IsContainer) - { - dropcontainer = target.Serial; - x = 0xFFFF; - y = 0xFFFF; - } - else if ( - target.ItemData.IsStackable - && target.Graphic == Client.Game.GameCursor.ItemHold.Graphic - ) - { - dropcontainer = target.Serial; - x = target.X; - y = target.Y; - } - else - { - switch (target.Graphic) - { - case 0x0EFA: - case 0x2253: - case 0x2252: - case 0x238C: - case 0x23A0: - case 0x2D50: - { - dropcontainer = target.Serial; - x = target.X; - y = target.Y; - - break; - } - } - } - } - } - } - - if ( - !candrop - && Client.Game.GameCursor.ItemHold.Enabled - && !Client.Game.GameCursor.ItemHold.IsFixedPosition - ) - { - Client.Game.Audio.PlaySound(0x0051); - } - - if ( - candrop - && Client.Game.GameCursor.ItemHold.Enabled - && !Client.Game.GameCursor.ItemHold.IsFixedPosition - ) - { - ContainerGump gump = UIManager.GetGump(dropcontainer); - - if ( - gump != null - && ( - it == null - || it.Serial != dropcontainer - && it is Item item - && !item.ItemData.IsContainer - ) - ) - { - if (gump.IsChessboard) - { - y += 20; - } - - Rectangle containerBounds = ContainerManager.Get(gump.Graphic).Bounds; - - ref readonly var spriteInfo = ref ( - gump.IsChessboard - ? ref Client.Game.Gumps.GetGump( - (ushort)( - Client.Game.GameCursor.ItemHold.DisplayedGraphic - - Constants.ITEM_GUMP_TEXTURE_OFFSET - ) - ) - : ref Client.Game.Arts.GetArt(Client.Game.GameCursor.ItemHold.DisplayedGraphic) - ); - - float scale = GetScale(); - - containerBounds.X = (int)(containerBounds.X * scale); - containerBounds.Y = (int)(containerBounds.Y * scale); - containerBounds.Width = (int)(containerBounds.Width * scale); - containerBounds.Height = (int)( - (containerBounds.Height + (gump.IsChessboard ? 20 : 0)) * scale - ); - - if (spriteInfo.Texture != null) - { - int textureW, - textureH; - - if ( - ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.ScaleItemsInsideContainers - ) - { - textureW = (int)(spriteInfo.UV.Width * scale); - textureH = (int)(spriteInfo.UV.Height * scale); - } - else - { - textureW = spriteInfo.UV.Width; - textureH = spriteInfo.UV.Height; - } - - if ( - ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.RelativeDragAndDropItems - ) - { - x += Client.Game.GameCursor.ItemHold.MouseOffset.X; - y += Client.Game.GameCursor.ItemHold.MouseOffset.Y; - } - - x -= textureW >> 1; - y -= textureH >> 1; - - if (x + textureW > containerBounds.Width) - { - x = containerBounds.Width - textureW; - } - - if (y + textureH > containerBounds.Height) - { - y = containerBounds.Height - textureH; - } - } - - if (x < containerBounds.X) - { - x = containerBounds.X; - } - - if (y < containerBounds.Y) - { - y = containerBounds.Y; - } - - x = (int)(x / scale); - y = (int)(y / scale); - } - - GameActions.DropItem( - Client.Game.GameCursor.ItemHold.Serial, - x, - y, - 0, - dropcontainer - ); - - Mouse.CancelDoubleClick = true; - } - else if (!Client.Game.GameCursor.ItemHold.Enabled && SerialHelper.IsValid(serial)) - { - if (!DelayedObjectClickManager.IsEnabled) - { - Point off = Mouse.LDragOffset; - - DelayedObjectClickManager.Set( - serial, - Mouse.Position.X - off.X - ScreenCoordinateX, - Mouse.Position.Y - off.Y - ScreenCoordinateY, - Time.Ticks + Mouse.MOUSE_DELAY_DOUBLE_CLICK - ); - } - } - } - } - - public override void Update() - { - base.Update(); - - if (IsDisposed) - { - return; - } - - Item item = World.Items.Get(LocalSerial); - - if (item == null || item.IsDestroyed) - { - Dispose(); - return; - } - - if ( - UIManager.MouseOverControl != null - && UIManager.MouseOverControl.RootParent == this - && ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.HighlightContainerWhenSelected - ) - { - SelectedObject.SelectedContainer = item; - } - - if (Graphic == CORPSES_GUMP && _corpseEyeTicks < Time.Ticks) - { - _eyeCorspeOffset = _eyeCorspeOffset == 0 ? 1 : 0; - _corpseEyeTicks = (long)Time.Ticks + 750; - _eyeGumpPic.Graphic = (ushort)(0x0045 + _eyeCorspeOffset); - float scale = GetScale(); - _eyeGumpPic.Width = (int)(_eyeGumpPic.Width * scale); - _eyeGumpPic.Height = (int)(_eyeGumpPic.Height * scale); - } - } - - protected override void UpdateContents() - { - Clear(); - BuildGump(); - IsMinimized = IsMinimized; - ItemsOnAdded(); - } - - public override void Save(XmlTextWriter writer) - { - base.Save(writer); - writer.WriteAttributeString("graphic", Graphic.ToString()); - writer.WriteAttributeString("isminimized", IsMinimized.ToString()); - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - // skip loading - - Client.Game.GetScene()?.DoubleClickDelayed(LocalSerial); - - Dispose(); - } - - private float GetScale() - { - return IsChessboard ? 1f : UIManager.ContainerScale; - } - - private void ItemsOnAdded() - { - Entity container = World.Get(LocalSerial); - - if (container == null) - { - return; - } - - bool is_corpse = container.Graphic == 0x2006; - - if (!container.IsEmpty && _hideIfEmpty && !IsVisible) - { - IsVisible = true; - } - - for (LinkedObject i = container.Items; i != null; i = i.Next) - { - Item item = (Item)i; - - // NOTE: Switched from 'item.Layer' property which comes from server to 'ItemData.Layer' from tiledata.mul. - // In the past I found some issues using the server property. - // Probably lack of knowledge about some client behaviour. - // Remember it. - - if (item.Amount <= 0) - { - continue; - } - - var layer = (Layer)item.ItemData.Layer; - - if (is_corpse && item.Layer > 0 && !Constants.BAD_CONTAINER_LAYERS[(int)layer]) - { - continue; - } - - // some items has layer = [face | beard | hair] and we need to check if it's a wearable item or not. - // when the item is wearable we dont add it to the container. - // Tested with --> client = 7.0.95.0 | graphic = 0x0A02 - if ( - item.ItemData.IsWearable - && (layer == Layer.Face || layer == Layer.Beard || layer == Layer.Hair) - ) - { - continue; - } - - ItemGump itemControl = new ItemGump( - item.Serial, - (ushort)( - item.DisplayedGraphic - - (IsChessboard ? Constants.ITEM_GUMP_TEXTURE_OFFSET : 0) - ), - item.Hue, - item.X, - item.Y, - IsChessboard - ); - - itemControl.IsVisible = !IsMinimized; - - float scale = GetScale(); - - if ( - ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.ScaleItemsInsideContainers - ) - { - itemControl.Width = (int)(itemControl.Width * scale); - itemControl.Height = (int)(itemControl.Height * scale); - } - - itemControl.X = (int)((short)item.X * scale); - itemControl.Y = (int)(((short)item.Y - (IsChessboard ? 20 : 0)) * scale); - - Add(itemControl); - } - - if (!firstItemsLoaded) - { - firstItemsLoaded = true; - AutoLootManager.Instance.HandleCorpse(World.Items.Get(LocalSerial)); - } - } - - public void CheckItemControlPosition(Item item) - { - Rectangle dataBounds = _data.Bounds; - - int boundX = dataBounds.X; - int boundY = dataBounds.Y; - int boundWidth = dataBounds.Width; - int boundHeight = dataBounds.Height + (IsChessboard ? 20 : 0); - - ref readonly var spriteInfo = ref ( - IsChessboard - ? ref Client.Game.Gumps.GetGump( - (ushort)( - item.DisplayedGraphic - - Constants.ITEM_GUMP_TEXTURE_OFFSET - ) - ) - : ref Client.Game.Arts.GetArt(item.DisplayedGraphic) - ); - - if (spriteInfo.Texture != null) - { - float scale = GetScale(); - - boundWidth -= (int)(spriteInfo.UV.Width / scale); - boundHeight -= (int)(spriteInfo.UV.Height / scale); - } - - if (item.X < boundX) - { - item.X = (ushort)boundX; - } - else if (item.X > boundWidth) - { - item.X = (ushort)boundWidth; - } - - if (item.Y < boundY) - { - item.Y = (ushort)boundY; - } - else if (item.Y > boundHeight) - { - item.Y = (ushort)boundHeight; - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - if (CUOEnviroment.Debug && !IsMinimized) - { - Rectangle bounds = _data.Bounds; - float scale = GetScale(); - ushort boundX = (ushort)(bounds.X * scale); - ushort boundY = (ushort)(bounds.Y * scale); - ushort boundWidth = (ushort)(bounds.Width * scale); - ushort boundHeight = (ushort)(bounds.Height * scale); - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - batcher.DrawRectangle( - SolidColorTextureCache.GetTexture(Color.Red), - x + boundX, - y + boundY, - boundWidth - boundX, - boundHeight - boundY, - hueVector - ); - } - - return true; - } - - public override void Dispose() - { - Item item = World.Items.Get(LocalSerial); - - if (item != null) - { - if ( - World.Player != null - && ProfileManager.CurrentProfile?.OverrideContainerLocationSetting == 3 - ) - { - UIManager.SavePosition(item, Location); - } - - for (LinkedObject i = item.Items; i != null; i = i.Next) - { - Item child = (Item)i; - - if (child.Container == item) - { - UIManager.GetGump(child)?.Dispose(); - } - } - } - - base.Dispose(); - } - - protected override void CloseWithRightClick() - { - base.CloseWithRightClick(); - - if (_data.ClosedSound != 0) - { - Client.Game.Audio.PlaySound(_data.ClosedSound); - } - } - - protected override void OnDragEnd(int x, int y) - { - if ( - ProfileManager.CurrentProfile.OverrideContainerLocation - && ProfileManager.CurrentProfile.OverrideContainerLocationSetting >= 2 - ) - { - Point gumpCenter = new Point(X + (Width >> 1), Y + (Height >> 1)); - ProfileManager.CurrentProfile.OverrideContainerLocationPosition = gumpCenter; - } - - base.OnDragEnd(x, y); - } - - private class GumpPicContainer : GumpPic - { - public GumpPicContainer(int x, int y, ushort graphic, ushort hue) - : base(x, y, graphic, hue) { } - - public override bool Contains(int x, int y) - { - float scale = - Graphic == 0x091A || Graphic == 0x092E ? 1f : UIManager.ContainerScale; - - x = (int)(x / scale); - y = (int)(y / scale); - - return base.Contains(x, y); - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/CoolDownBar.cs b/src/ClassicUO.Client/Game/UI/Gumps/CoolDownBar.cs deleted file mode 100644 index fa08ea746..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/CoolDownBar.cs +++ /dev/null @@ -1,254 +0,0 @@ -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using System; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class CoolDownBar : Gump - { - public const int COOL_DOWN_WIDTH = 180, COOL_DOWN_HEIGHT = 30; - public static int DEFAULT_X { get { return ProfileManager.CurrentProfile.CoolDownX; } } - public static int DEFAULT_Y { get { return ProfileManager.CurrentProfile.CoolDownY; } } - - private AlphaBlendControl background, foreground; - public readonly Label textLabel, cooldownLabel; - private DateTime expire; - private TimeSpan duration; - private int startX, startY; - private readonly bool isBuffBar; - - private GumpPic gumpPic; - - public BuffIconType buffIconType; - - public CoolDownBar(TimeSpan _duration, string _name, ushort _hue, int x, int y, ushort graphic = ushort.MaxValue, BuffIconType type = BuffIconType.Unknown2, bool isBuffBar = false) : base(0, 0) - { - #region VARS - Width = COOL_DOWN_WIDTH; - Height = COOL_DOWN_HEIGHT; - X = x; - startX = x; - Y = y; - startY = y; - expire = DateTime.Now + _duration; - duration = _duration; - CanCloseWithRightClick = true; - CanMove = true; - AcceptMouseInput = true; - buffIconType = type; - this.isBuffBar = isBuffBar; - #endregion - - #region BACK/FORE GROUND - background = new AlphaBlendControl(0.3f); - background.Width = COOL_DOWN_WIDTH; - background.Height = COOL_DOWN_HEIGHT; - background.Hue = _hue; - - foreground = new AlphaBlendControl(0.8f); - foreground.Width = COOL_DOWN_WIDTH; - foreground.Height = COOL_DOWN_HEIGHT; - foreground.Hue = _hue; - #endregion - - if (graphic != ushort.MaxValue) - { - gumpPic = new GumpPic(0, 2, graphic, 0); - background.X = gumpPic.Width; - background.Width = COOL_DOWN_WIDTH - gumpPic.Width; - - foreground.X = gumpPic.Width; - foreground.Width = COOL_DOWN_WIDTH - gumpPic.Width; - } - - #region LABELS - textLabel = new Label(_name, true, _hue, background.Width, style: FontStyle.BlackBorder, align: Assets.TEXT_ALIGN_TYPE.TS_CENTER) - { - X = background.X - }; - - cooldownLabel = new Label("------", true, _hue, background.Width, style: FontStyle.BlackBorder, align: Assets.TEXT_ALIGN_TYPE.TS_CENTER) - { - X = background.X, - Y = 0 - }; - cooldownLabel.Y = COOL_DOWN_HEIGHT - cooldownLabel.Height - 2; - cooldownLabel.Text = ""; - #endregion - - #region ADD CONTROLS - if (graphic != ushort.MaxValue) - Add(gumpPic); - Add(background); - Add(foreground); - Add(textLabel); - Add(cooldownLabel); - #endregion - } - - public override void Update() - { - base.Update(); - - if ( - !isBuffBar && - (ProfileManager.CurrentProfile?.UseLastMovedCooldownPosition ?? false) && - (X != startX || Y != startY) - ) - { - ProfileManager.CurrentProfile.CoolDownX = X; - ProfileManager.CurrentProfile.CoolDownY = Y; - startX = X; - startY = Y; - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsDisposed) - return false; - - if (DateTime.Now >= expire) - Dispose(); - - TimeSpan remaing = expire - DateTime.Now; - - if (remaing < TimeSpan.FromMinutes(60)) - { - int offset = 0; - if (gumpPic != null) - offset = gumpPic.Width; - foreground.Width = (int)((remaing.TotalSeconds / duration.TotalSeconds) * (COOL_DOWN_WIDTH - offset)); - cooldownLabel.Text = ((int)remaing.TotalSeconds).ToString(); - } - - base.Draw(batcher, x, y); - - batcher.DrawRectangle( - SolidColorTextureCache.GetTexture(Color.Black), - x, y, - COOL_DOWN_WIDTH, - COOL_DOWN_HEIGHT, - ShaderHueTranslator.GetHueVector(background.Hue, false, 1f) - ); - batcher.DrawRectangle( - SolidColorTextureCache.GetTexture(Color.Black), - x + 1, y + 1, - COOL_DOWN_WIDTH - 2, - COOL_DOWN_HEIGHT - 2, - ShaderHueTranslator.GetHueVector(background.Hue, false, 1f) - ); - - return true; - } - - public class CoolDownConditionData - { - public ushort hue; - public string label; - public string trigger; - public int cooldown; - public int message_type; - public bool replace_if_exists; - - private CoolDownConditionData(ushort hue = 42, string label = "Label", string trigger = "Text to trigger", int cooldown = 10, int message_type = (int)MESSAGE_TYPE.ALL, bool replace_if_exists = false) - { - this.hue = hue; - this.label = label; - this.trigger = trigger; - this.cooldown = cooldown; - this.message_type = message_type; - this.replace_if_exists = replace_if_exists; - } - - public static CoolDownConditionData GetConditionData(int key, bool createIfNotExist) - { - CoolDownConditionData data = new CoolDownConditionData(); - if (ProfileManager.CurrentProfile.CoolDownConditionCount > key) - { - data.hue = ProfileManager.CurrentProfile.Condition_Hue[key]; - data.label = ProfileManager.CurrentProfile.Condition_Label[key]; - data.trigger = ProfileManager.CurrentProfile.Condition_Trigger[key]; - data.cooldown = ProfileManager.CurrentProfile.Condition_Duration[key]; - data.message_type = ProfileManager.CurrentProfile.Condition_Type[key]; - - if (ProfileManager.CurrentProfile.Condition_ReplaceIfExists.Count > key) //Remove me after a while to prevent index not found - data.replace_if_exists = ProfileManager.CurrentProfile.Condition_ReplaceIfExists[key]; - else - { - while (ProfileManager.CurrentProfile.Condition_ReplaceIfExists.Count <= key) - { - ProfileManager.CurrentProfile.Condition_ReplaceIfExists.Add(false); - } - } - } - else if (createIfNotExist) - { - ProfileManager.CurrentProfile.Condition_Hue.Add(data.hue); - ProfileManager.CurrentProfile.Condition_Label.Add(data.label); - ProfileManager.CurrentProfile.Condition_Trigger.Add(data.trigger); - ProfileManager.CurrentProfile.Condition_Duration.Add(data.cooldown); - ProfileManager.CurrentProfile.Condition_Type.Add(data.message_type); - ProfileManager.CurrentProfile.Condition_ReplaceIfExists.Add(data.replace_if_exists); - } - return data; - } - - public static void SaveCondition(int key, ushort hue, string label, string trigger, int cooldown, bool createIfNotExist, int message_type, bool replace_if_exists) - { - if (ProfileManager.CurrentProfile.CoolDownConditionCount > key) - { - ProfileManager.CurrentProfile.Condition_Hue[key] = hue; - ProfileManager.CurrentProfile.Condition_Label[key] = label; - ProfileManager.CurrentProfile.Condition_Trigger[key] = trigger; - ProfileManager.CurrentProfile.Condition_Duration[key] = cooldown; - ProfileManager.CurrentProfile.Condition_Type[key] = message_type; - - if (ProfileManager.CurrentProfile.Condition_ReplaceIfExists.Count > key) //Remove me after a while to prevent index not found - ProfileManager.CurrentProfile.Condition_ReplaceIfExists[key] = replace_if_exists; - else - { - while (ProfileManager.CurrentProfile.Condition_ReplaceIfExists.Count <= key) - { - ProfileManager.CurrentProfile.Condition_ReplaceIfExists.Add(false); - } - ProfileManager.CurrentProfile.Condition_ReplaceIfExists[key] = replace_if_exists; - } - } - else if (createIfNotExist) - { - ProfileManager.CurrentProfile.Condition_Hue.Add(hue); - ProfileManager.CurrentProfile.Condition_Label.Add(label); - ProfileManager.CurrentProfile.Condition_Trigger.Add(trigger); - ProfileManager.CurrentProfile.Condition_Duration.Add(cooldown); - ProfileManager.CurrentProfile.Condition_Type.Add(message_type); - ProfileManager.CurrentProfile.Condition_ReplaceIfExists.Add(createIfNotExist); - } - } - - public static void RemoveCondition(int key) - { - if (ProfileManager.CurrentProfile.CoolDownConditionCount > key) - { - ProfileManager.CurrentProfile.Condition_Hue.RemoveAt(key); - ProfileManager.CurrentProfile.Condition_Label.RemoveAt(key); - ProfileManager.CurrentProfile.Condition_Trigger.RemoveAt(key); - ProfileManager.CurrentProfile.Condition_Duration.RemoveAt(key); - ProfileManager.CurrentProfile.Condition_Type.RemoveAt(key); - ProfileManager.CurrentProfile.Condition_ReplaceIfExists.RemoveAt(key); - } - } - - public enum MESSAGE_TYPE - { - ALL, - SELF, - OTHER - } - - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/CounterBarGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/CounterBarGump.cs deleted file mode 100644 index 6f4474ad9..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/CounterBarGump.cs +++ /dev/null @@ -1,689 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using System.IO; -using System.Xml; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class CounterBarGump : Gump - { - private AlphaBlendControl _background; - - public static CounterBarGump CurrentCounterBarGump { get; private set; } - - private int _rows, - _columns, - _rectSize; - - //private bool _isVertical; - - public CounterBarGump() : base(0, 0) - { - CurrentCounterBarGump = this; - } - - public CounterBarGump( - int x, - int y, - int rectSize = 30, - int rows = 1, - int columns = 1 /*, bool vertical = false*/ - ) : base(0, 0) - { - X = x; - Y = y; - - if (rectSize < 30) - { - rectSize = 30; - } - else if (rectSize > 80) - { - rectSize = 80; - } - - if (rows < 1) - { - rows = 1; - } - - if (columns < 1) - { - columns = 1; - } - - _rows = rows; - _columns = columns; - _rectSize = rectSize; - //_isVertical = vertical; - - BuildGump(); - - CurrentCounterBarGump = this; - } - - public override GumpType GumpType => GumpType.CounterBar; - - private void BuildGump() - { - CanMove = true; - AcceptMouseInput = true; - AcceptKeyboardInput = false; - CanCloseWithRightClick = false; - WantUpdateSize = false; - - Width = _rectSize * _columns + 1; - Height = _rectSize * _rows + 1; - - Add(_background = new AlphaBlendControl(0.7f) { Width = Width, Height = Height }); - - for (int row = 0; row < _rows; row++) - { - for (int col = 0; col < _columns; col++) - { - Add( - new CounterItem( - col * _rectSize + 2, - row * _rectSize + 2, - _rectSize - 4, - _rectSize - 4 - ) - ); - } - } - } - - public void SetLayout(int size, int rows, int columns) - { - bool ok = false; - - //if (_isVertical != isvertical) - //{ - // _isVertical = isvertical; - // int temp = _rows; - // _rows = _columns; - // _columns = temp; - // ok = true; - //} - - if (rows > 30) - { - rows = 30; - } - - if (columns > 30) - { - columns = 30; - } - - if (size < 30) - { - size = 30; - } - else if (size > 80) - { - size = 80; - } - - if (_rectSize != size) - { - ok = true; - _rectSize = size; - } - - if (rows < 1) - { - rows = 1; - } - - if (_rows != rows) - { - ok = true; - _rows = rows; - } - - if (columns < 1) - { - columns = 1; - } - - if (_columns != columns) - { - ok = true; - _columns = columns; - } - - if (ok) - { - ApplyLayout(); - } - } - - private void ApplyLayout() - { - Width = _rectSize * _columns + 1; - Height = _rectSize * _rows + 1; - - _background.Width = Width; - _background.Height = Height; - - CounterItem[] items = GetControls(); - - int[] indices = new int[items.Length]; - - for (int row = 0; row < _rows; row++) - { - for (int col = 0; col < _columns; col++) - { - int index = /*_isVertical ? col * _rows + row :*/ - row * _columns + col; - - if (index < items.Length) - { - CounterItem c = items[index]; - - c.X = col * _rectSize + 2; - c.Y = row * _rectSize + 2; - c.Width = _rectSize - 4; - c.Height = _rectSize - 4; - - c.SetGraphic(c.Graphic, c.Hue); - - indices[index] = -1; - } - else - { - Add( - new CounterItem( - col * _rectSize + 2, - row * _rectSize + 2, - _rectSize - 4, - _rectSize - 4 - ) - ); - } - } - } - - for (int i = 0; i < indices.Length; i++) - { - int index = indices[i]; - - if (index >= 0 && index < items.Length) - { - items[i].Parent = null; - - items[i].Dispose(); - } - } - - SetInScreen(); - } - - public CounterItem GetCounterItem(int index) - { - CounterItem[] items = GetControls(); - - if(items == null) - { - return null; - } - - if(items.Length > index) - { - return items[index]; - } - - return null; - } - - public override void Save(XmlTextWriter writer) - { - base.Save(writer); - - writer.WriteAttributeString("rows", _rows.ToString()); - writer.WriteAttributeString("columns", _columns.ToString()); - writer.WriteAttributeString("rectsize", _rectSize.ToString()); - - IEnumerable controls = FindControls(); - - writer.WriteStartElement("controls"); - - foreach (CounterItem control in controls) - { - writer.WriteStartElement("control"); - writer.WriteAttributeString("graphic", control.Graphic.ToString()); - writer.WriteAttributeString("hue", control.Hue.ToString()); - writer.WriteEndElement(); - } - - writer.WriteEndElement(); - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - - _rows = int.Parse(xml.GetAttribute("rows")); - _columns = int.Parse(xml.GetAttribute("columns")); - _rectSize = int.Parse(xml.GetAttribute("rectsize")); - - BuildGump(); - - XmlElement controlsXml = xml["controls"]; - - if (controlsXml != null) - { - CounterItem[] items = GetControls(); - int index = 0; - - foreach (XmlElement controlXml in controlsXml.GetElementsByTagName("control")) - { - if (index < items.Length) - { - items[index++]?.SetGraphic( - ushort.Parse(controlXml.GetAttribute("graphic")), - ushort.Parse(controlXml.GetAttribute("hue")) - ); - } - else - { - Log.Error(ResGumps.IndexOutOfbounds); - } - } - } - - IsEnabled = IsVisible = ProfileManager.CurrentProfile.CounterBarEnabled; - } - - public override void Dispose() - { - if (CurrentCounterBarGump == this) - { - CurrentCounterBarGump = null; - } - base.Dispose(); - } - - public class CounterItem : Control - { - private int _amount; - - private readonly ImageWithText _image; - private uint _time; - private const uint HIGHLIGHT_DURATION = 1000; - private uint _endHighlight; - private bool _highlight; - - public CounterItem(int x, int y, int w, int h) - { - AcceptMouseInput = true; - WantUpdateSize = false; - CanMove = true; - CanCloseWithRightClick = false; - - X = x; - Y = y; - Width = w; - Height = h; - - _image = new ImageWithText(); - Add(_image); - - ContextMenu = new ContextMenuControl(); - ContextMenu.Add(ResGumps.UseObject, Use); - ContextMenu.Add(ResGumps.Remove, RemoveItem); - } - - public ushort Graphic { get; private set; } - - public ushort Hue { get; private set; } - - public void SetGraphic(ushort graphic, ushort hue) - { - _image.ChangeGraphic(graphic, hue); - - if (graphic == 0) - { - return; - } - - Graphic = graphic; - Hue = hue; - } - - public void RemoveItem() - { - _image?.ChangeGraphic(0, 0); - _amount = 0; - Graphic = 0; - } - - public void Use() - { - if (Graphic == 0) - { - return; - } - - Item backpack = World.Player.FindItemByLayer(Layer.Backpack); - - if (backpack == null) - { - return; - } - - Item item = backpack.FindItem(Graphic, Hue); - - if (item != null) - { - GameActions.DoubleClick(item); - } - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - if (Client.Game.GameCursor.ItemHold.Enabled) - { - SetGraphic( - Client.Game.GameCursor.ItemHold.Graphic, - Client.Game.GameCursor.ItemHold.Hue - ); - - GameActions.DropItem( - Client.Game.GameCursor.ItemHold.Serial, - Client.Game.GameCursor.ItemHold.X, - Client.Game.GameCursor.ItemHold.Y, - 0, - Client.Game.GameCursor.ItemHold.Container - ); - } - else if (ProfileManager.CurrentProfile.CastSpellsByOneClick) - { - Use(); - } - } - else if (button == MouseButtonType.Right && Keyboard.Alt && Graphic != 0) - { - RemoveItem(); - } - else if (Graphic != 0) - { - base.OnMouseUp(x, y, button); - } - } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if ( - button == MouseButtonType.Left - && !ProfileManager.CurrentProfile.CastSpellsByOneClick - ) - { - Use(); - } - - return true; - } - - public override void Update() - { - base.Update(); - - if (Parent != null && Parent.IsEnabled && _time < Time.Ticks) - { - _time = Time.Ticks + 100; - - if (Graphic == 0) - { - _image.SetAmount(string.Empty); - } - else - { - _amount = 0; - - for ( - Item item = (Item)World.Player.Items; - item != null; - item = (Item)item.Next - ) - { - if ( - item.ItemData.IsContainer - && !item.IsEmpty - && item.Layer >= Layer.OneHanded - && item.Layer <= Layer.Legs - ) - { - GetAmount(item, Graphic, Hue, ref _amount); - } - } - - if (ProfileManager.CurrentProfile.CounterBarDisplayAbbreviatedAmount) - { - if ( - _amount >= ProfileManager.CurrentProfile.CounterBarAbbreviatedAmount - ) - { - _image.SetAmount(StringHelper.IntToAbbreviatedString(_amount)); - - return; - } - } - - if (ProfileManager.CurrentProfile.CounterBarHighlightOnUse) - { - if (int.TryParse(_image.GetText(), out int cAmt)) - { - if (cAmt > _amount) - { - _highlight = true; - _endHighlight = Time.Ticks + HIGHLIGHT_DURATION; - } - } - } - _image.SetAmount(_amount.ToString()); - } - } - } - - private static void GetAmount(Item parent, ushort graphic, ushort hue, ref int amount) - { - if (parent == null) - { - return; - } - - for (LinkedObject i = parent.Items; i != null; i = i.Next) - { - Item item = (Item)i; - - GetAmount(item, graphic, hue, ref amount); - - if (item.Graphic == graphic && item.Hue == hue && item.Exists) - { - amount += item.Amount; - } - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - Texture2D color = SolidColorTextureCache.GetTexture( - MouseIsOver - ? Color.Yellow - : ProfileManager.CurrentProfile.CounterBarHighlightOnAmount - && _amount < ProfileManager.CurrentProfile.CounterBarHighlightAmount - && Graphic != 0 - ? Color.Red - : Color.Gray - ); - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - if (_highlight && Time.Ticks > _endHighlight) - { - _highlight = false; - } - - if (_highlight) - { - hueVector.Z = ((float)_endHighlight - (float)Time.Ticks) / (float)HIGHLIGHT_DURATION; - batcher.Draw(SolidColorTextureCache.GetTexture(Color.Yellow), new Rectangle(x, y, Width, Height), hueVector); - } - - hueVector.Z = 1; - - batcher.DrawRectangle(color, x, y, Width, Height, hueVector); - - return true; - } - - private class ImageWithText : Control - { - private readonly Label _label; - private ushort _graphic; - private ushort _hue; - private bool _partial; - - public ImageWithText() - { - CanMove = true; - WantUpdateSize = true; - AcceptMouseInput = false; - - _label = new Label("", true, 0x35, 0, 1, FontStyle.BlackBorder) - { - X = 2, - Y = Height - 15 - }; - - Add(_label); - } - - public void ChangeGraphic(ushort graphic, ushort hue) - { - if (graphic != 0) - { - _graphic = graphic; - _hue = hue; - _partial = TileDataLoader.Instance.StaticData[graphic].IsPartialHue; - _label.Y = Parent.Height - 15; - } - else - { - _graphic = 0; - } - } - - public override void Update() - { - base.Update(); - - if (Parent != null) - { - Width = Parent.Width; - Height = Parent.Height; - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (_graphic != 0) - { - ref readonly var artInfo = ref Client.Game.Arts.GetArt(_graphic); - var rect = Client.Game.Arts.GetRealArtBounds(_graphic); - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(_hue, _partial, 1f); - - Point originalSize = new Point(Width, Height); - Point point = new Point(); - - if (rect.Width < Width) - { - originalSize.X = rect.Width; - point.X = (Width >> 1) - (originalSize.X >> 1); - } - - if (rect.Height < Height) - { - originalSize.Y = rect.Height; - point.Y = (Height >> 1) - (originalSize.Y >> 1); - } - - batcher.Draw( - artInfo.Texture, - new Rectangle(x + point.X, y + point.Y, originalSize.X, originalSize.Y), - new Rectangle( - artInfo.UV.X + rect.X, - artInfo.UV.Y + rect.Y, - rect.Width, - rect.Height - ), - hueVector - ); - } - - return base.Draw(batcher, x, y); - } - - public void SetAmount(string amount) - { - _label.Text = amount; - } - - public string GetText() - { - return _label?.Text ?? ""; - } - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/CreditsGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/CreditsGump.cs deleted file mode 100644 index 5d88b9517..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/CreditsGump.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - class CreditsGump : Gump - { - private const ushort BACKGROUND_IMG = 0x0500; - private Point _offset; - private uint _lastUpdate; - - //TODO - private const string CREDITS = -@" -Copyright(R) ClassicUO 2021 - -This project does not distribute any copyrighted game assets. -In order to run this client you'll need to legally obtain a -copy of the Ultima Online Classic Client. - -Using a custom client to connect to official UO servers is -strictly forbidden. -We do not assume any responsibility of the usage of this client. - - -Ultima Online(R) 2021 Electronic Arts Inc. All Rights Reserved. - - - - - [Lead Developer] - Karasho' - https://github.com/andreakarasho -"; - - public CreditsGump() : base(0, 0) - { - Client.Game.Audio.PlayMusic(8, false, true); - - LayerOrder = UILayer.Over; - CanCloseWithRightClick = true; - - GumpPic background = new GumpPic(0, 0, BACKGROUND_IMG, 0); - Width = background.Width; - Height = background.Height; - - Add(new AlphaBlendControl(1f) { Width = background.Width, Height = background.Height}); - - Add(background); - - Vector2 size = Fonts.Regular.MeasureString(CREDITS); - _offset.X = (int) (Width / 2f - size.X / 2); - _offset.Y = Height; - } - - public override void Update() - { - base.Update(); - - if (_lastUpdate < Time.Ticks) - { - _offset.Y -= 1; - _lastUpdate = Time.Ticks + 25; - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - batcher.DrawString(Fonts.Bold, CREDITS, x + _offset.X, y + _offset.Y, hueVector); - - return true; - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/CustomToolTip.cs b/src/ClassicUO.Client/Game/UI/Gumps/CustomToolTip.cs deleted file mode 100644 index 79c14c46e..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/CustomToolTip.cs +++ /dev/null @@ -1,187 +0,0 @@ -using ClassicUO.Configuration; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using System.Threading.Tasks; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class CustomToolTip : Gump - { - private readonly Item item; - private Control hoverReference; - private readonly string prepend; - private readonly string append; - private readonly Item compareTo; - private TextBox text; - private readonly uint hue = 0xFFFF; - - public event FinishedLoadingEvent OnOPLLoaded; - - public CustomToolTip(Item item, int x, int y, Control hoverReference, string prepend = "", string append = "", Item compareTo = null) : base(0, 0) - { - this.item = item; - this.hoverReference = hoverReference; - this.prepend = prepend; - this.append = append; - this.compareTo = compareTo; - X = x; - Y = y; - if (ProfileManager.CurrentProfile != null) - { - hue = ProfileManager.CurrentProfile.TooltipTextHue; - } - BuildGump(); - } - - public void RemoveHoverReference() - { - hoverReference = null; - } - - private void BuildGump() - { - text = new TextBox( - "Loading item data...", - ProfileManager.CurrentProfile.SelectedToolTipFont, - ProfileManager.CurrentProfile.SelectedToolTipFontSize, - 150, - (int)hue, - align: ProfileManager.CurrentProfile.LeftAlignToolTips ? FontStashSharp.RichText.TextHorizontalAlignment.Left : FontStashSharp.RichText.TextHorizontalAlignment.Center - ); - - Height = text.Height; - Width = text.Width; - - LoadOPLData(0); - } - - private void LoadOPLData(int attempt) - { - if (attempt > 4 || IsDisposed) - return; - if (item == null) - { - Dispose(); - return; - } - - if (World.OPL.Contains(item.Serial)) - { - if (World.OPL.TryGetNameAndData(item.Serial, out string name, out string data)) - { - string finalString = FormatTooltip(name, data); - if (SerialHelper.IsItem(item.Serial)) - { - finalString = Managers.ToolTipOverrideData.ProcessTooltipText(item.Serial, compareTo == null ? uint.MinValue : compareTo.Serial); - if (finalString == null) - finalString = FormatTooltip(name, data); - } - - text?.Dispose(); - text = new TextBox( - TextBox.ConvertHtmlToFontStashSharpCommand(finalString).Trim(), - ProfileManager.CurrentProfile.SelectedToolTipFont, - ProfileManager.CurrentProfile.SelectedToolTipFontSize, - 600, - (int)hue, - align: ProfileManager.CurrentProfile.LeftAlignToolTips ? FontStashSharp.RichText.TextHorizontalAlignment.Left : FontStashSharp.RichText.TextHorizontalAlignment.Center - ); - - if (text.MeasuredSize.X + 10 < 600) - text.Width = text.MeasuredSize.X + 10; - - Height = text.Height; - Width = text.Width; - OnOPLLoaded?.Invoke(); - } - } - else - { - Task.Factory.StartNew(() => - { - Task.Delay(1500).Wait(); - LoadOPLData(attempt++); - }); - } - - - - } - - private string FormatTooltip(string name, string data) - { - string text = - prepend + - "" + - name + - "\n" + - data + - append; - - return text; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - if (IsDisposed) - return false; - if (hoverReference != null && !hoverReference.MouseIsOver) - { - Dispose(); - return false; - } - //if (text == null) //Waiting for opl data to load the text tooltip - // return true; - - float alpha = 0.7f; - - if (ProfileManager.CurrentProfile != null) - { - alpha = ProfileManager.CurrentProfile.TooltipBackgroundOpacity / 100f; - if (float.IsNaN(alpha)) - { - alpha = 0f; - } - } - - Vector3 hue_vec = ShaderHueTranslator.GetHueVector(1, false, alpha); - - if (ProfileManager.CurrentProfile != null) - hue_vec.X = ProfileManager.CurrentProfile.ToolTipBGHue - 1; - - batcher.Draw - ( - SolidColorTextureCache.GetTexture(Color.White), - new Rectangle - ( - x - 4, - y - 2, - (int)(Width + 8), - (int)(Height + 8) - ), - hue_vec - ); - - hue_vec = ShaderHueTranslator.GetHueVector(0, false, alpha); - - batcher.DrawRectangle - ( - SolidColorTextureCache.GetTexture(Color.Gray), - x - 4, - y - 2, - (int)(Width + 8), - (int)(Height + 8), - hue_vec - ); - - text.Draw(batcher, x, y); - - return true; - } - } - - public delegate void FinishedLoadingEvent(); -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/DebugGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/DebugGump.cs deleted file mode 100644 index 2b686c4f3..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/DebugGump.cs +++ /dev/null @@ -1,277 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Xml; -using ClassicUO.Configuration; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class DebugGump : Gump - { - private const string DEBUG_STRING_0 = "- FPS: {0} (Min={1}, Max={2}), Zoom: {3:0.00}, Total Objs: {4}\n"; - private const string DEBUG_STRING_1 = "- Mobiles: {0} Items: {1} Statics: {2} Multi: {3} Lands: {4} Effects: {5}\n"; - private const string DEBUG_STRING_2 = "- CharPos: {0}\n- Mouse: {1}\n- InGamePos: {2}\n"; - private const string DEBUG_STRING_3 = "- Selected: {0}"; - - private const string DEBUG_STRING_SMALL = "FPS: {0}\nZoom: {1:0.00}"; - private const string DEBUG_STRING_SMALL_NO_ZOOM = "FPS: {0}"; - private static Point _last_position = new Point(-1, -1); - - private uint _timeToUpdate; - private readonly AlphaBlendControl _alphaBlendControl; - private string _cacheText = string.Empty; - - public DebugGump(int x, int y) : base(0, 0) - { - CanMove = true; - CanCloseWithEsc = false; - CanCloseWithRightClick = true; - AcceptMouseInput = true; - AcceptKeyboardInput = false; - - Width = 100; - Height = 50; - X = _last_position.X <= 0 ? x : _last_position.X; - Y = _last_position.Y <= 0 ? y : _last_position.Y; - - Add - ( - _alphaBlendControl = new AlphaBlendControl(.7f) - { - Width = Width, Height = Height - } - ); - - LayerOrder = UILayer.Over; - - WantUpdateSize = true; - } - - public bool IsMinimized { get; set; } - - public override GumpType GumpType => GumpType.Debug; - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - IsMinimized = !IsMinimized; - - return true; - } - - return false; - } - - public override void Update() - { - base.Update(); - - if (IsDisposed) - { - return; - } - - if (Time.Ticks > _timeToUpdate) - { - _timeToUpdate = Time.Ticks + 100; - - GameScene scene = Client.Game.GetScene(); - Span span = stackalloc char[256]; - ValueStringBuilder sb = new ValueStringBuilder(span); - - if (IsMinimized && scene != null) - { - sb.Append - (string.Format( - DEBUG_STRING_0, - CUOEnviroment.CurrentRefreshRate, - 0, - 0, - !World.InGame ? 1f : scene.Camera.Zoom, - scene.RenderedObjectsCount - ) - ); - - sb.Append($"- CUO version: {CUOEnviroment.Version}, Client version: {Settings.GlobalSettings.ClientVersion}\n"); - - //_sb.AppendFormat(DEBUG_STRING_1, Engine.DebugInfo.MobilesRendered, Engine.DebugInfo.ItemsRendered, Engine.DebugInfo.StaticsRendered, Engine.DebugInfo.MultiRendered, Engine.DebugInfo.LandsRendered, Engine.DebugInfo.EffectsRendered); - sb.Append(string.Format(DEBUG_STRING_2, World.InGame ? $"{World.Player.X}, {World.Player.Y}, {World.Player.Z}" : "0xFFFF, 0xFFFF, 0", Mouse.Position, SelectedObject.Object is GameObject gobj ? $"{gobj.X}, {gobj.Y}, {gobj.Z}" : "0xFFFF, 0xFFFF, 0")); - - sb.Append(string.Format(DEBUG_STRING_3, ReadObject(SelectedObject.Object))); - - if (Profiler.Enabled) - { - double timeDraw = Profiler.GetContext("RenderFrame").TimeInContext; - - double timeUpdate = Profiler.GetContext("Update").TimeInContext; - - double timeFixedUpdate = Profiler.GetContext("FixedUpdate").TimeInContext; - - double timeOutOfContext = Profiler.GetContext("OutOfContext").TimeInContext; - - //double timeTotalCheck = timeOutOfContext + timeDraw + timeUpdate; - double timeTotal = Profiler.TrackedTime; - - double avgDrawMs = Profiler.GetContext("RenderFrame").AverageTime; - - sb.Append("- Profiling\n"); - - sb.Append - ( - string.Format - ( - " Draw:{0:0.0}% Update:{1:0.0}% FixedUpd:{2:0.0} AvgDraw:{3:0.0}ms {4}\n", - 100d * (timeDraw / timeTotal), - 100d * (timeUpdate / timeTotal), - 100d * (timeFixedUpdate / timeTotal), - avgDrawMs, - CUOEnviroment.CurrentRefreshRate - ) - ); - } - } - else - { - var cameraZoomCount = (int)((scene.Camera.ZoomMax - scene.Camera.ZoomMin) / scene.Camera.ZoomStep); - var cameraZoomIndex = cameraZoomCount - (int)((scene.Camera.ZoomMax - scene.Camera.Zoom) / scene.Camera.ZoomStep); - - if (scene != null && cameraZoomIndex != 5) - { - sb.Append(string.Format(DEBUG_STRING_SMALL, CUOEnviroment.CurrentRefreshRate, !World.InGame ? 1f : scene.Camera.Zoom)); - } - else - { - sb.Append(string.Format(DEBUG_STRING_SMALL_NO_ZOOM, CUOEnviroment.CurrentRefreshRate)); - } - } - - - _cacheText = sb.ToString(); - - sb.Dispose(); - - Vector2 size = Fonts.Bold.MeasureString(_cacheText); - - _alphaBlendControl.Width = Width = (int) (size.X + 20); - _alphaBlendControl.Height = Height = (int) (size.Y + 20); - - WantUpdateSize = true; - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (!base.Draw(batcher, x, y)) - { - return false; - } - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - batcher.DrawString - ( - Fonts.Bold, - _cacheText, - x + 10, - y + 10, - hueVector - ); - - return true; - } - - private string ReadObject(BaseGameObject obj) - { - if (obj != null && IsMinimized) - { - switch (obj) - { - case Mobile mob: return $"Mobile (0x{mob.Serial:X8}) graphic: 0x{mob.Graphic:X4} flags: {mob.Flags} noto: {mob.NotorietyFlag}"; - - case Item item: return $"Item (0x{item.Serial:X8}) graphic: 0x{item.Graphic:X4} flags: {item.Flags} amount: {item.Amount} itemdata: {item.ItemData.Flags}"; - - case Static st: return $"Static (0x{st.Graphic:X4}) height: {st.ItemData.Height} flags: {st.ItemData.Flags} Alpha: {st.AlphaHue}"; - - case Multi multi: return $"Multi (0x{multi.Graphic:X4}) height: {multi.ItemData.Height} flags: {multi.ItemData.Flags}"; - - case GameEffect effect: return "GameEffect"; - - case TextObject overhead: return $"TextOverhead type: {overhead.Type} hue: 0x{overhead.Hue:X4}"; - - case Land land: return $"Land (0x{land.Graphic:X4}) flags: {land.TileData.Flags} stretched: {land.IsStretched} avgZ: {land.AverageZ} minZ: {land.MinZ}"; - } - } - - return string.Empty; - } - - - public override void Save(XmlTextWriter writer) - { - base.Save(writer); - - writer.WriteAttributeString("minimized", IsMinimized.ToString()); - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - - bool.TryParse(xml.GetAttribute("minimized"), out bool b); - IsMinimized = b; - } - - protected override void OnDragEnd(int x, int y) - { - base.OnDragEnd(x, y); - _last_position.X = ScreenCoordinateX; - _last_position.Y = ScreenCoordinateY; - } - - protected override void OnMove(int x, int y) - { - base.OnMove(x, y); - - _last_position.X = ScreenCoordinateX; - _last_position.Y = ScreenCoordinateY; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/DurabilityGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/DurabilityGump.cs deleted file mode 100644 index bb70d54b5..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/DurabilityGump.cs +++ /dev/null @@ -1,219 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Xml; -using ClassicUO.Assets; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class DurabilityGumpMinimized : Gump - { - public uint Graphic { get; set; } = 5587; - - public DurabilityGumpMinimized() : base(0, 0) - { - SetTooltip("Open Equipment Durability Tracker"); - - WantUpdateSize = true; - AcceptMouseInput = true; - Width = 30; - Height = 30; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - ref readonly var texture = ref Client.Game.Gumps.GetGump(Graphic); - if (texture.Texture != null) - { - Rectangle rect = new Rectangle(x, y, Width, Height); - batcher.Draw - ( - texture.Texture, - rect, - texture.UV, - ShaderHueTranslator.GetHueVector(0) - ); - } - - return base.Draw(batcher, x, y); ; - } - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - UIManager.GetGump()?.Dispose(); - UIManager.Add(new DurabilitysGump()); - } - } - internal class DurabilitysGump : Gump - { - private const int WIDTH = 300, HEIGHT = 400; - - - private enum DurabilityColors - { - RED = 0x0805, - BLUE = 0x0806, - GREEN = 0x0808, - YELLOW = 0x0809 - } - - private readonly Dictionary _menuItems = new Dictionary(); - private DataBox _dataBox; - public override GumpType GumpType => GumpType.DurabilityGump; - - public DurabilitysGump() : base(0, 0) - { - - LayerOrder = UILayer.Default; - CanCloseWithRightClick = true; - CanMove = true; - - Width = WIDTH; - Height = HEIGHT; - X = Client.Game.Scene.Camera.Bounds.Width - Width - 10; - Y = Client.Game.Scene.Camera.Bounds.Y + 10; - - - var _borderControl = new BorderControl - ( - 0, - 0, - Width, - Height, - 4 - ); - - Add(_borderControl); - Add(new AlphaBlendControl(0.9f) { Width = Width, Height = Height }); - BuildHeader(); - ScrollArea area = new ScrollArea - ( - 10, - 30, - Width - 20, - Height - 50, - true - ) - { - ScrollbarBehaviour = ScrollbarBehaviour.ShowAlways - }; - - Add(area); - - - _dataBox = new DataBox(0, 0, Width - 40, Height - 20); - area.Add(_dataBox); - UpdateContents(); - } - - - private void BuildHeader() - { - var a = new Area(); - a.Width = Width; - a.WantUpdateSize = false; - a.CanMove = true; - - Label l; - a.Add(l = new Label("Equipment Durability", true, 0xFF)); - l.X = (Width >> 1) - (l.Width >> 1); - l.Y = (l.Height >> 1) >> 1; - a.Height = l.Y + l.Height; - - Add(a); - } - - protected override void UpdateContents() - { - _dataBox.Clear(); - _dataBox.WantUpdateSize = true; - Rectangle barBounds = Client.Game.Gumps.GetGump((uint)DurabilityColors.RED).UV; - var startY = 0; - - var items = World.DurabilityManager?.Durabilities ?? new List(); - - foreach (var durability in items.OrderBy(d => d.Percentage)) - { - if (durability.MaxDurabilty <= 0) - { - continue; - } - var item = World.Items.Get((uint)durability.Serial); - if (item == null) - { - continue; - } - - var a = new Area(); - a.AcceptMouseInput = true; - a.WantUpdateSize = false; - a.CanMove = true; - a.Height = 44; - a.Width = Width - (a.X * 2) - 40; - a.Y = startY; - - Label name; - a.Add(name = new Label($"{(string.IsNullOrWhiteSpace(item.Name) ? item.Layer : item.Name)}", true, 0xFFFF)); - GumpPic red; - a.Add(red = new GumpPic(0, name.Y + name.Height + 5, (ushort)DurabilityColors.RED, 0)); - - DurabilityColors statusGump = DurabilityColors.GREEN; - - if (durability.Percentage < 0.7) - { - statusGump = DurabilityColors.YELLOW; - } - else if (durability.Percentage < 0.95) - { - statusGump = DurabilityColors.BLUE; - } - - if (durability.Percentage > 0) - { - a.Add(new GumpPicTiled(0, red.Y, (int)Math.Floor(barBounds.Width * durability.Percentage), barBounds.Height, (ushort)statusGump)); - } - - var durWidth = FontsLoader.Instance.GetWidthUnicode(0, $"{durability.Durabilty} / {durability.MaxDurabilty}"); - - a.Add(new Label($"{durability.Durabilty} / {durability.MaxDurabilty}", true, 0xFFFF) - { - Y = red.Y - 2, - X = Width - 38 - durWidth - }); - _dataBox.Add(a); - - startY += a.Height + 4; - } - } - - public override void Update() - { - base.Update(); - } - public override void Save(XmlTextWriter writer) - { - base.Save(writer); - - writer.WriteAttributeString("lastX", X.ToString()); - writer.WriteAttributeString("lastY", Y.ToString()); - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - - int.TryParse(xml.GetAttribute("lastX"), out X); - int.TryParse(xml.GetAttribute("lastY"), out Y); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - return base.Draw(batcher, x, y); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/GridContainer.cs b/src/ClassicUO.Client/Game/UI/Gumps/GridContainer.cs deleted file mode 100644 index a80001f2a..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/GridContainer.cs +++ /dev/null @@ -1,2115 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Renderer; -using ClassicUO.Utility.Logging; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using System.Xml; -using System.Xml.Linq; -using static ClassicUO.Game.UI.Gumps.GridHightlightMenu; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class GridContainer : ResizableGump - { - #region CONSTANTS - private const int X_SPACING = 1, Y_SPACING = 1; - private const int TOP_BAR_HEIGHT = 20; - #endregion - - #region private static vars - private static int lastX = 100, lastY = 100, lastCorpseX = 100, lastCorpseY = 100; - private static int gridItemSize { get { return (int)Math.Round(50 * (ProfileManager.CurrentProfile.GridContainersScale / 100f)); } } - private static int borderWidth = 4; - #endregion - - #region private readonly vars - private readonly AlphaBlendControl background; - private readonly Label containerNameLabel; - private readonly StbTextBox searchBox; - private readonly GumpPic openRegularGump, sortContents; - private readonly ResizableStaticPic quickDropBackpack; - private readonly GumpPicTiled backgroundTexture; - private readonly NiceButton setLootBag; - private readonly bool isCorpse = false; - #endregion - - #region private vars - private Item container { get { return World.Items.Get(LocalSerial); } } - private float lastGridItemScale = (ProfileManager.CurrentProfile.GridContainersScale / 100f); - private int lastWidth = GetWidth(), lastHeight = GetHeight(); - private bool quickLootThisContainer = false; - private bool? UseOldContainerStyle = null; - private bool autoSortContainer = false; - private bool firstItemsLoaded = false; - - private readonly bool skipSave = false; - private readonly ushort originalContainerItemGraphic; - - private GridScrollArea scrollArea; - private GridSlotManager gridSlotManager; - #endregion - - #region private tooltip vars - private string quickLootStatus { get { return ProfileManager.CurrentProfile.CorpseSingleClickLoot ? "Enabled" : "Disabled"; } } - private string quickLootTooltip - { - get - { - if (isCorpse) - return $"Drop an item here to send it to your backpack.

Click this icon to enable/disable single-click looting for corpses.
Currently {quickLootStatus}"; - else - return $"Drop an item here to send it to your backpack.

Click this icon to enable/disable single-click loot for this container while it remains open.
Currently " + (quickLootThisContainer ? "Enabled" : "Disabled"); - } - - } - private string sortButtonTooltip - { - get - { - string status = autoSortContainer ? "Enabled" : "Disabled"; - return $"Sort this container.
Alt + Click to enable auto sort
Auto sort currently {status}"; - } - } - #endregion - - #region public vars - public readonly bool IsPlayerBackpack = false; - #endregion - - public GridContainer(uint local, ushort originalContainerGraphic, bool? useGridStyle = null) : base(GetWidth(), GetHeight(), GetWidth(2), GetHeight(1), local, 0) - { - if (container == null) - { - Dispose(); - return; - } - - #region SET VARS - isCorpse = container.IsCorpse || container.Graphic == 0x0009; - if (useGridStyle != null) - UseOldContainerStyle = !useGridStyle; - - IsPlayerBackpack = LocalSerial == World.Player.FindItemByLayer(Layer.Backpack).Serial; - - autoSortContainer = GridSaveSystem.Instance.AutoSortContainer(LocalSerial); - - Point lastPos = IsPlayerBackpack ? ProfileManager.CurrentProfile.BackpackGridPosition : GridSaveSystem.Instance.GetLastPosition(LocalSerial); - Point savedSize = IsPlayerBackpack ? ProfileManager.CurrentProfile.BackpackGridSize : GridSaveSystem.Instance.GetLastSize(LocalSerial); - IsLocked = IsPlayerBackpack && ProfileManager.CurrentProfile.BackPackLocked; - - lastWidth = Width = savedSize.X; - lastHeight = Height = savedSize.Y; - - X = isCorpse ? lastCorpseX : lastX = lastPos.X; - Y = isCorpse ? lastCorpseY : lastY = lastPos.Y; - - if (isCorpse) - { - World.Player.ManualOpenedCorpses.Remove(LocalSerial); - - if (World.Player.AutoOpenedCorpses.Contains(LocalSerial) && ProfileManager.CurrentProfile != null && ProfileManager.CurrentProfile.SkipEmptyCorpse && container.IsEmpty) - { - IsVisible = false; - Dispose(); - } - } - - AnchorType = ProfileManager.CurrentProfile.EnableGridContainerAnchor ? ANCHOR_TYPE.NONE : ANCHOR_TYPE.DISABLED; - originalContainerItemGraphic = originalContainerGraphic; - - CanMove = true; - AcceptMouseInput = true; - #endregion - - #region background - background = new AlphaBlendControl() - { - Width = Width - (borderWidth * 2), - Height = Height - (borderWidth * 2), - X = borderWidth, - Y = borderWidth, - Alpha = (float)ProfileManager.CurrentProfile.ContainerOpacity / 100, - Hue = ProfileManager.CurrentProfile.Grid_UseContainerHue ? container.Hue : ProfileManager.CurrentProfile.AltGridContainerBackgroundHue - }; - - backgroundTexture = new GumpPicTiled(0); - #endregion - - #region TOP BAR AREA - containerNameLabel = new Label(GetContainerName(), true, 0x0481) - { - X = borderWidth, - Y = -20 - }; - - searchBox = new StbTextBox(0xFF, 20, 150, true, FontStyle.None, 0x0481) - { - X = borderWidth, - Y = borderWidth, - Multiline = false, - Width = 150, - Height = 20 - }; - searchBox.TextChanged += (sender, e) => { UpdateItems(); }; - - var regularGumpIcon = Client.Game.Gumps.GetGump(5839).Texture; - openRegularGump = new GumpPic(background.Width - 25 - borderWidth, borderWidth, regularGumpIcon == null ? (ushort)1209 : (ushort)5839, 0); - openRegularGump.MouseUp += (sender, e) => - { - if (e.Button == MouseButtonType.Left) - { - UseOldContainerStyle = true; - OpenOldContainer(LocalSerial); - } - }; - openRegularGump.MouseEnter += (sender, e) => { openRegularGump.Graphic = regularGumpIcon == null ? (ushort)1210 : (ushort)5840; }; - openRegularGump.MouseExit += (sender, e) => { openRegularGump.Graphic = regularGumpIcon == null ? (ushort)1209 : (ushort)5839; }; - openRegularGump.SetTooltip("Open the original style container.\n\n" + - "/c[orange]Grid Container Controls:/cd\n" + - "Ctrl + Click to lock an item in place\n" + - "Alt + Click to add an item to the quick move queue\n" + - "Shift + Click to add an item to your auto loot list\n" + - "Sort and single click looting can be enabled with the icons on the right side"); - - quickDropBackpack = new ResizableStaticPic(World.Player.FindItemByLayer(Layer.Backpack).DisplayedGraphic, 20, 20) - { - X = Width - openRegularGump.Width - 20 - borderWidth, - Y = borderWidth - }; - quickDropBackpack.MouseUp += (sender, e) => - { - if (e.Button == MouseButtonType.Left && quickDropBackpack.MouseIsOver) - { - if (Client.Game.GameCursor.ItemHold.Enabled) - { - GameActions.DropItem(Client.Game.GameCursor.ItemHold.Serial, 0xFFFF, 0xFFFF, 0, World.Player.FindItemByLayer(Layer.Backpack)); - } - else if (isCorpse) - { - ProfileManager.CurrentProfile.CorpseSingleClickLoot ^= true; - quickDropBackpack.SetTooltip(quickLootTooltip); - } - else - { - quickLootThisContainer ^= true; - quickDropBackpack.SetTooltip(quickLootTooltip); - } - } - }; - quickDropBackpack.MouseEnter += (sender, e) => { quickDropBackpack.Hue = 0x34; }; - quickDropBackpack.MouseExit += (sender, e) => { quickDropBackpack.Hue = 0; }; - quickDropBackpack.SetTooltip(quickLootTooltip); - - sortContents = new GumpPic(quickDropBackpack.X - 20, borderWidth, 1210, 0); - sortContents.MouseUp += (sender, e) => - { - if (e.Button == MouseButtonType.Left && Keyboard.Alt) - { - autoSortContainer ^= true; - sortContents.SetTooltip(sortButtonTooltip); - } - UpdateItems(true); - }; - sortContents.MouseEnter += (sender, e) => { sortContents.Graphic = 1209; }; - sortContents.MouseExit += (sender, e) => { sortContents.Graphic = 1210; }; - sortContents.SetTooltip(sortButtonTooltip); - #endregion - - #region Scroll Area - scrollArea = new GridScrollArea( - background.X, - TOP_BAR_HEIGHT + background.Y, - background.Width, - background.Height - (containerNameLabel.Height + 1) - ); - - scrollArea.MouseUp += ScrollArea_MouseUp; - #endregion - - #region Set loot bag - setLootBag = new NiceButton(0, Height - 20, 100, 20, ButtonAction.Default, "Set loot bag") { IsSelectable = false }; - setLootBag.IsVisible = isCorpse; - setLootBag.SetTooltip("For double click looting only"); - setLootBag.MouseUp += (s, e) => - { - GameActions.Print(Resources.ResGumps.TargetContainerToGrabItemsInto); - TargetManager.SetTargeting(CursorTarget.SetGrabBag, 0, TargetType.Neutral); - }; - #endregion - - #region Add controls - Add(background); - Add(backgroundTexture); - Add(containerNameLabel); - searchBox.Add(new AlphaBlendControl(0.5f) - { - Hue = 0x0481, - Width = searchBox.Width, - Height = searchBox.Height - }); - Add(searchBox); - Add(openRegularGump); - Add(quickDropBackpack); - Add(sortContents); - Add(scrollArea); - Add(setLootBag); - #endregion - - gridSlotManager = new GridSlotManager(LocalSerial, this, scrollArea); //Must come after scroll area - - if (GridSaveSystem.Instance.UseOriginalContainerGump(LocalSerial) && (UseOldContainerStyle == null || UseOldContainerStyle == true)) - { - skipSave = true; //Avoid unsaving item slots because they have not be set up yet - OpenOldContainer(local); - return; - } - - BuildBorder(); - ResizeWindow(savedSize); - } - - public override GumpType GumpType => GumpType.GridContainer; - - private static int GetWidth(int columns = -1) - { - if (columns < 0) - columns = ProfileManager.CurrentProfile.Grid_DefaultColumns; - return (borderWidth * 2) //The borders around the container, one on the left and one on the right - + 15 //The width of the scroll bar - + (gridItemSize * columns) //How many items to fit in left to right - + (X_SPACING * columns); //Spacing between each grid item(x columns) - } - - private static int GetHeight(int rows = -1) - { - if (rows < 0) - rows = ProfileManager.CurrentProfile.Grid_DefaultRows; - return TOP_BAR_HEIGHT + (borderWidth * 2) + ((gridItemSize + Y_SPACING) * rows); - } - - public override void Save(XmlTextWriter writer) - { - base.Save(writer); - - if (!skipSave) - { - GridSaveSystem.Instance.SaveContainer(LocalSerial, gridSlotManager.GridSlots, Width, Height, X, Y, UseOldContainerStyle, autoSortContainer); - } - - if (IsPlayerBackpack) - { - ProfileManager.CurrentProfile.BackpackGridPosition = Location; - ProfileManager.CurrentProfile.BackpackGridSize = new Point(Width, Height); - } - - writer.WriteAttributeString("ogContainer", originalContainerItemGraphic.ToString()); - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - GameActions.DoubleClickQueued(LocalSerial); - } - - private void ScrollArea_MouseUp(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtonType.Left && scrollArea.MouseIsOver) - { - if (Client.Game.GameCursor.ItemHold.Enabled) - { - GameActions.DropItem(Client.Game.GameCursor.ItemHold.Serial, 0xFFFF, 0xFFFF, 0, LocalSerial); - } - else if (TargetManager.IsTargeting) - { - TargetManager.Target(LocalSerial); - } - } - else if (e.Button == MouseButtonType.Right) - { - InvokeMouseCloseGumpWithRClick(); - } - } - - private void OpenOldContainer(uint serial) - { - ContainerGump container; - - UIManager.GetGump(serial)?.Dispose(); - - ushort graphic = originalContainerItemGraphic; - if (Client.Version >= Utility.ClientVersion.CV_706000 && ProfileManager.CurrentProfile != null && ProfileManager.CurrentProfile.UseLargeContainerGumps) - { - switch (graphic) - { - case 0x0048: - if (Client.Game.Gumps.GetGump(0x06E8).Texture != null) - { - graphic = 0x06E8; - } - - break; - - case 0x0049: - if (Client.Game.Gumps.GetGump(0x9CDF).Texture != null) - { - graphic = 0x9CDF; - } - - break; - - case 0x0051: - if (Client.Game.Gumps.GetGump(0x06E7).Texture != null) - { - graphic = 0x06E7; - } - - break; - - case 0x003E: - if (Client.Game.Gumps.GetGump(0x06E9).Texture != null) - { - graphic = 0x06E9; - } - - break; - - case 0x004D: - if (Client.Game.Gumps.GetGump(0x06EA).Texture != null) - { - graphic = 0x06EA; - } - - break; - - case 0x004E: - if (Client.Game.Gumps.GetGump(0x06E6).Texture != null) - { - graphic = 0x06E6; - } - - break; - - case 0x004F: - if (Client.Game.Gumps.GetGump(0x06E5).Texture != null) - { - graphic = 0x06E5; - } - - break; - - case 0x004A: - if (Client.Game.Gumps.GetGump(0x9CDD).Texture != null) - { - graphic = 0x9CDD; - } - - break; - - case 0x0044: - if (Client.Game.Gumps.GetGump(0x9CE3).Texture != null) - { - graphic = 0x9CE3; - } - - break; - } - } - - ContainerManager.CalculateContainerPosition(serial, graphic); - - container = new ContainerGump(this.container.Serial, graphic, true, true) - { - X = ContainerManager.X, - Y = ContainerManager.Y, - InvalidateContents = true - }; - UIManager.Add(container); - Dispose(); - } - - private void UpdateItems(bool overrideSort = false) - { - //Container doesn't exist or has no items - if (container == null) - { - Dispose(); - return; - } - UpdateContainerName(); - - if (autoSortContainer) overrideSort = true; - - List sortedContents = ProfileManager.CurrentProfile.GridContainerSearchMode == 0 ? gridSlotManager.SearchResults(searchBox.Text) : GridSlotManager.GetItemsInContainer(container); - gridSlotManager.RebuildContainer(sortedContents, searchBox.Text, overrideSort); - - InvalidateContents = false; - } - - public static bool FindContainer(uint serial, out GridContainer? gridContainer) - { - return (gridContainer = UIManager.GetGump(serial)) == null ? false : true; - } - - protected override void UpdateContents() - { - if (InvalidateContents && !IsDisposed && IsVisible) - { - UpdateItems(); - } - if (!firstItemsLoaded) - { - firstItemsLoaded = true; - if (isCorpse) - { - AutoLootManager.Instance.HandleCorpse(container); - } - } - } - - protected override void OnMouseExit(int x, int y) - { - if (isCorpse && container != null && container == SelectedObject.CorpseObject) - { - SelectedObject.CorpseObject = null; - } - } - - public override void Dispose() - { - if (isCorpse) - { - lastCorpseX = X; - lastCorpseY = Y; - } - else - { - lastX = X; - lastY = Y; - } - - Item _c = container; - if (_c != null) - { - if (_c == SelectedObject.CorpseObject) - { - SelectedObject.CorpseObject = null; - } - - Item bank = World.Player.FindItemByLayer(Layer.Bank); - - if (bank != null) - if (_c.Serial == bank.Serial || _c.Container == bank.Serial) - { - for (LinkedObject i = _c.Items; i != null; i = i.Next) - { - Item child = (Item)i; - - if (child.Container == _c) - { - UIManager.GetGump(child)?.Dispose(); - UIManager.GetGump(child)?.Dispose(); - } - } - } - } - - if (gridSlotManager != null && !skipSave) - if (gridSlotManager.ItemPositions.Count > 0 && !isCorpse) - GridSaveSystem.Instance.SaveContainer(LocalSerial, gridSlotManager.GridSlots, Width, Height, X, Y, UseOldContainerStyle, autoSortContainer); - - base.Dispose(); - } - - public override void Update() - { - base.Update(); - - if (IsDisposed) - return; - - Item item = container; - - if (item == null || item.IsDestroyed) - { - Dispose(); - return; - } - - if (item.IsCorpse && item.OnGround) - { - if (item.Distance > 3) - { - Dispose(); - return; - } - } - - if ((lastWidth != Width || lastHeight != Height) || lastGridItemScale != gridItemSize) - { - lastGridItemScale = gridItemSize; - background.Width = Width - (borderWidth * 2); - background.Height = Height - (borderWidth * 2); - scrollArea.Width = background.Width; - scrollArea.Height = background.Height - TOP_BAR_HEIGHT; - openRegularGump.X = Width - openRegularGump.Width - borderWidth; - quickDropBackpack.X = openRegularGump.X - quickDropBackpack.Width; - sortContents.X = quickDropBackpack.X - sortContents.Width; - lastHeight = Height; - lastWidth = Width; - searchBox.Width = Math.Min(Width - (borderWidth * 2) - openRegularGump.Width - quickDropBackpack.Width - sortContents.Width, 150); - backgroundTexture.Width = background.Width; - backgroundTexture.Height = background.Height; - backgroundTexture.Alpha = background.Alpha; - backgroundTexture.Hue = background.Hue; - setLootBag.Y = Height - 20; - if (IsPlayerBackpack) - ProfileManager.CurrentProfile.BackpackGridSize = new Point(Width, Height); - RequestUpdateContents(); - } - - if (IsPlayerBackpack) - if (Location != ProfileManager.CurrentProfile.BackpackGridPosition) - ProfileManager.CurrentProfile.BackpackGridPosition = Location; - - - if (item != null && !item.IsDestroyed && UIManager.MouseOverControl != null && (UIManager.MouseOverControl == this || UIManager.MouseOverControl.RootParent == this)) - { - SelectedObject.Object = item; - if (item.IsCorpse) - SelectedObject.CorpseObject = item; - } - } - - private string GetContainerName() - { - string containerName = container.Name?.Length > 0 ? container.Name : "a container"; - - if (gridSlotManager != null) - { - gridSlotManager.UpdateItems(); - containerName += $" ({gridSlotManager.ContainerContents.Count})"; - } - - return containerName; - } - - public void UpdateContainerName() - { - containerNameLabel.Text = GetContainerName(); - } - - public void OptionsUpdated() - { - var newAlpha = (float)ProfileManager.CurrentProfile.ContainerOpacity / 100; - var newHue = ProfileManager.CurrentProfile.Grid_UseContainerHue ? container.Hue : ProfileManager.CurrentProfile.AltGridContainerBackgroundHue; - background.Hue = newHue; - background.Alpha = newAlpha; - backgroundTexture.Alpha = background.Alpha; - backgroundTexture.Hue = background.Hue; - BorderControl.Hue = background.Hue; - BorderControl.Alpha = background.Alpha; - AnchorType = ProfileManager.CurrentProfile.EnableGridContainerAnchor ? ANCHOR_TYPE.NONE : ANCHOR_TYPE.DISABLED; - BuildBorder(); - } - - public static void UpdateAllGridContainers() - { - foreach (GridContainer _ in UIManager.Gumps.OfType()) - { - _.OptionsUpdated(); - } - } - - public void HandleObjectMessage(Entity parent, string text, ushort hue) - { - if (parent != null) - { - GridItem item = gridSlotManager.FindItem(parent.Serial); - if (item != null) - { - UIManager.Add(new SimpleTimedTextGump(text, (uint)hue, TimeSpan.FromSeconds(2), 200) { X = item.ScreenCoordinateX, Y = item.ScreenCoordinateY }); - } - } - } - - public void BuildBorder() - { - int graphic = 0, borderSize = 0; - switch ((BorderStyle)ProfileManager.CurrentProfile.Grid_BorderStyle) - { - case BorderStyle.Style1: - graphic = 3500; borderSize = 26; - break; - case BorderStyle.Style2: - graphic = 5054; borderSize = 12; - break; - case BorderStyle.Style3: - graphic = 5120; borderSize = 10; - break; - case BorderStyle.Style4: - graphic = 9200; borderSize = 7; - break; - case BorderStyle.Style5: - graphic = 9270; borderSize = 10; - break; - case BorderStyle.Style6: - graphic = 9300; borderSize = 4; - break; - case BorderStyle.Style7: - graphic = 9260; borderSize = 17; - break; - case BorderStyle.Style8: - if (Client.Game.Gumps.GetGump(40303).Texture != null) - graphic = 40303; - else - graphic = 83; - borderSize = 16; - break; - - default: - case BorderStyle.Default: - BorderControl.DefaultGraphics(); - backgroundTexture.IsVisible = false; - background.IsVisible = true; - borderWidth = 4; - break; - } - - if ((BorderStyle)ProfileManager.CurrentProfile.Grid_BorderStyle != BorderStyle.Default) - { - BorderControl.T_Left = (ushort)graphic; - BorderControl.H_Border = (ushort)(graphic + 1); - BorderControl.T_Right = (ushort)(graphic + 2); - BorderControl.V_Border = (ushort)(graphic + 3); - - backgroundTexture.Graphic = (ushort)(graphic + 4); - backgroundTexture.IsVisible = true; - backgroundTexture.Hue = background.Hue; - BorderControl.Hue = background.Hue; - BorderControl.Alpha = background.Alpha; - background.IsVisible = false; - - BorderControl.V_Right_Border = (ushort)(graphic + 5); - BorderControl.B_Left = (ushort)(graphic + 6); - BorderControl.H_Bottom_Border = (ushort)(graphic + 7); - BorderControl.B_Right = (ushort)(graphic + 8); - BorderControl.BorderSize = borderSize; - borderWidth = borderSize; - } - UpdateUIPositions(); - OnResize(); - - BorderControl.IsVisible = !ProfileManager.CurrentProfile.Grid_HideBorder; - } - - private void UpdateUIPositions() - { - background.X = borderWidth; - background.Y = borderWidth; - scrollArea.X = background.X; - scrollArea.Y = TOP_BAR_HEIGHT + background.Y; - searchBox.Y = borderWidth; - quickDropBackpack.Y = borderWidth; - sortContents.Y = borderWidth; - openRegularGump.Y = borderWidth; - searchBox.X = borderWidth; - backgroundTexture.X = background.X; - backgroundTexture.Y = background.Y; - backgroundTexture.Width = Width - (borderWidth * 2); - backgroundTexture.Height = Height - (borderWidth * 2); - background.Width = Width - (borderWidth * 2); - background.Height = Height - (borderWidth * 2); - scrollArea.Width = background.Width; - scrollArea.Height = background.Height - TOP_BAR_HEIGHT; - } - - public enum BorderStyle - { - Default, - Style1, - Style2, - Style3, - Style4, - Style5, - Style6, - Style7, - Style8 - } - - public static void ClearInstance() - { - GridSaveSystem.Instance.Clear(); - } - - private class GridItem : Control - { - private readonly HitBox hit; - private bool mousePressedWhenEntered = false; - private readonly Item container; - private Item _item; - private readonly GridContainer gridContainer; - public bool ItemGridLocked = false; - private readonly int slot; - private GridContainerPreview preview; - Label count; - AlphaBlendControl background; - private CustomToolTip toolTipThis, toolTipitem1, toolTipitem2; - - private bool borderHighlight = false; - private ushort borderHighlightHue = 0; - - public bool Hightlight = false; - public bool SelectHighlight = false; - public Item SlotItem { get { return _item; } set { _item = value; LocalSerial = value.Serial; } } - - private readonly int[] spellbooks = { 0x0EFA, 0x2253, 0x2252, 0x238C, 0x23A0, 0x2D50, 0x2D9D, 0x225A }; - - public GridItem(uint serial, int size, Item _container, GridContainer gridContainer, int count) - { - #region VARS - slot = count; - container = _container; - this.gridContainer = gridContainer; - LocalSerial = serial; - _item = World.Items.Get(serial); - CanMove = true; - if (_item != null) - { - ref readonly var text = ref Client.Game.Arts.GetArt((uint)(_item.DisplayedGraphic)); - texture = text.Texture; - bounds = text.UV; - - rect = Client.Game.Arts.GetRealArtBounds((uint)_item.DisplayedGraphic); - } - #endregion - - background = new AlphaBlendControl(0.25f); - background.Width = size; - background.Height = size; - Width = Height = size; - Add(background); - - hit = new HitBox(0, 0, size, size, null, 0f); - Add(hit); - - SetGridItem(_item); - - hit.MouseEnter += _hit_MouseEnter; - hit.MouseExit += _hit_MouseExit; - hit.MouseUp += _hit_MouseUp; - hit.MouseDoubleClick += _hit_MouseDoubleClick; - } - - public void SetHighLightBorder(ushort hue) - { - borderHighlight = hue == 0 ? false : true; - borderHighlightHue = hue; - } - - public void Resize() - { - Width = gridItemSize; - Height = gridItemSize; - hit.Width = gridItemSize; - hit.Height = gridItemSize; - background.Width = gridItemSize; - background.Height = gridItemSize; - } - - public void SetGridItem(Item item) - { - if (item == null) - { - _item = null; - LocalSerial = 0; - hit.ClearTooltip(); - Hightlight = false; - count?.Dispose(); - count = null; - ItemGridLocked = false; - } - else - { - _item = item; - ref readonly var text = ref Client.Game.Arts.GetArt((uint)(_item.DisplayedGraphic)); - texture = text.Texture; - bounds = text.UV; - - rect = Client.Game.Arts.GetRealArtBounds(_item.DisplayedGraphic); - - LocalSerial = item.Serial; - int itemAmt = (_item.ItemData.IsStackable ? _item.Amount : 1); - if (itemAmt > 1) - { - count?.Dispose(); - count = new Label(itemAmt.ToString(), true, 0x0481, align: TEXT_ALIGN_TYPE.TS_LEFT); - count.X = 1; - count.Y = Height - count.Height; - } - if (MultiItemMoveGump.MoveItems.Contains(_item)) - Hightlight = true; - hit.SetTooltip(_item); - } - } - - private void _hit_MouseDoubleClick(object sender, MouseDoubleClickEventArgs e) - { - if (e.Button != MouseButtonType.Left || TargetManager.IsTargeting || _item == null) - { - return; - } - if (!Keyboard.Ctrl && (ProfileManager.CurrentProfile.DoubleClickToLootInsideContainers && gridContainer.isCorpse) && !_item.IsDestroyed && !_item.ItemData.IsContainer && container != World.Player.FindItemByLayer(Layer.Backpack) && !_item.IsLocked && _item.IsLootable) - { - GameActions.GrabItem(_item, _item.Amount); - } - else - { - GameActions.DoubleClick(LocalSerial); - } - e.Result = true; - } - - private void _hit_MouseUp(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtonType.Left) - { - if (Client.Game.GameCursor.ItemHold.Enabled) - { - if (_item != null && _item.ItemData.IsContainer) - { - Rectangle containerBounds = ContainerManager.Get(_item.Graphic).Bounds; - GameActions.DropItem(Client.Game.GameCursor.ItemHold.Serial, 0xFFFF, 0xFFFF, 0, _item.Serial); - Mouse.CancelDoubleClick = true; - } - else if (_item != null && _item.ItemData.IsStackable && _item.Graphic == Client.Game.GameCursor.ItemHold.Graphic) - { - GameActions.DropItem(Client.Game.GameCursor.ItemHold.Serial, _item.X, _item.Y, 0, _item.Serial); - Mouse.CancelDoubleClick = true; - } - else - { - Rectangle containerBounds = ContainerManager.Get(container.Graphic).Bounds; - gridContainer.gridSlotManager.AddLockedItemSlot(Client.Game.GameCursor.ItemHold.Serial, slot); - GameActions.DropItem(Client.Game.GameCursor.ItemHold.Serial, containerBounds.Width / 2, containerBounds.Height / 2, 0, container.Serial); - Mouse.CancelDoubleClick = true; - } - } - else if (TargetManager.IsTargeting) - { - if (_item != null) - { - TargetManager.Target(_item); - if (TargetManager.TargetingState == CursorTarget.SetTargetClientSide) - { - UIManager.Add(new InspectorGump(_item)); - } - } - else - TargetManager.Target(container); - Mouse.CancelDoubleClick = true; - } - else if (Keyboard.Ctrl) - { - gridContainer.gridSlotManager.SetLockedSlot(slot, !ItemGridLocked); - Mouse.CancelDoubleClick = true; - } - else if (Keyboard.Alt && _item != null) - { - if (!MultiItemMoveGump.MoveItems.Contains(_item)) - MultiItemMoveGump.MoveItems.Enqueue(_item); - MultiItemMoveGump.AddMultiItemMoveGumpToUI(gridContainer.X - 200, gridContainer.Y); - SelectHighlight = true; - Mouse.CancelDoubleClick = true; - } - else if (Keyboard.Shift && _item != null && ProfileManager.CurrentProfile.EnableAutoLoot && !ProfileManager.CurrentProfile.HoldShiftForContext && !ProfileManager.CurrentProfile.HoldShiftToSplitStack) - { - AutoLootManager.Instance.AddLootItem(_item.Graphic, _item.Hue, _item.Name); - GameActions.Print($"Added this item to auto loot."); - } - else if (_item != null) - { - Point offset = Mouse.LDragOffset; - if (Math.Abs(offset.X) < Constants.MIN_PICKUP_DRAG_DISTANCE_PIXELS && Math.Abs(offset.Y) < Constants.MIN_PICKUP_DRAG_DISTANCE_PIXELS) - { - if ((gridContainer.isCorpse && ProfileManager.CurrentProfile.CorpseSingleClickLoot) || gridContainer.quickLootThisContainer) - { - GameActions.GrabItem(_item.Serial, _item.Amount); - Mouse.CancelDoubleClick = true; - } - else - { - if (World.ClientFeatures.TooltipsEnabled) - DelayedObjectClickManager.Set(_item.Serial, gridContainer.X, gridContainer.Y - 80, Time.Ticks + Mouse.MOUSE_DELAY_DOUBLE_CLICK); - else - { - GameActions.SingleClick(_item.Serial); - } - } - } - } - } - } - - private void _hit_MouseExit(object sender, MouseEventArgs e) - { - if (Mouse.LButtonPressed && !mousePressedWhenEntered) - { - Point offset = Mouse.LDragOffset; - if (Math.Abs(offset.X) >= Constants.MIN_PICKUP_DRAG_DISTANCE_PIXELS || Math.Abs(offset.Y) >= Constants.MIN_PICKUP_DRAG_DISTANCE_PIXELS) - { - if (_item != null) - { - if (!Keyboard.Alt) - GameActions.PickUp(_item, e.X, e.Y); - } - else - { - if (ProfileManager.CurrentProfile.HoldAltToMoveGumps) - { - if (Keyboard.Alt) - UIManager.AttemptDragControl(gridContainer); - } - else - UIManager.AttemptDragControl(gridContainer); - } - } - } - - if (Keyboard.Alt && Mouse.LButtonPressed && _item != null) - { - if (!MultiItemMoveGump.MoveItems.Contains(_item)) - MultiItemMoveGump.MoveItems.Enqueue(_item); - MultiItemMoveGump.AddMultiItemMoveGumpToUI(gridContainer.X - 200, gridContainer.Y); - SelectHighlight = true; - } - - - GridContainerPreview g; - while ((g = UIManager.GetGump()) != null) - { - g.Dispose(); - } - } - - private void _hit_MouseEnter(object sender, MouseEventArgs e) - { - SelectedObject.Object = World.Get(LocalSerial); - if (Mouse.LButtonPressed) - mousePressedWhenEntered = true; - else - mousePressedWhenEntered = false; - if (_item != null) - { - if (_item.ItemData.IsContainer && _item.Items != null && ProfileManager.CurrentProfile.GridEnableContPreview && !spellbooks.Contains(_item.Graphic)) - { - preview = new GridContainerPreview(_item, Mouse.Position.X, Mouse.Position.Y); - UIManager.Add(preview); - } - - if (Keyboard.Alt && Mouse.LButtonPressed && _item != null) - { - if (!MultiItemMoveGump.MoveItems.Contains(_item)) - MultiItemMoveGump.MoveItems.Enqueue(_item); - MultiItemMoveGump.AddMultiItemMoveGumpToUI(gridContainer.X - 200, gridContainer.Y); - SelectHighlight = true; - } - - if (!hit.HasTooltip) - hit.SetTooltip(_item); - } - } - - private Texture2D texture; - private Rectangle rect; - private Rectangle bounds; - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (_item != null && _item.ItemData.Layer > 0 && hit.MouseIsOver && Keyboard.Ctrl && (toolTipThis == null || toolTipThis.IsDisposed) && (toolTipitem1 == null || toolTipitem1.IsDisposed) && (toolTipitem2 == null || toolTipitem2.IsDisposed)) - { - Item compItem = World.Player.FindItemByLayer((Layer)_item.ItemData.Layer); - if (compItem != null && (Layer)_item.ItemData.Layer != Layer.Backpack) - { - hit.ClearTooltip(); - List toolTipList = new List(); - toolTipThis = new CustomToolTip(_item, Mouse.Position.X + 5, Mouse.Position.Y + 5, hit, compareTo: compItem); - toolTipList.Add(toolTipThis); - toolTipitem1 = new CustomToolTip(compItem, toolTipThis.X + toolTipThis.Width + 10, toolTipThis.Y, hit, "Equipped Item
"); - toolTipList.Add(toolTipitem1); - - if (CUOEnviroment.Debug) - { - ItemPropertiesData i1 = new ItemPropertiesData(_item); - ItemPropertiesData i2 = new ItemPropertiesData(compItem); - - if (i1.GenerateComparisonTooltip(i2, out string compileToolTip)) - GameActions.Print(compileToolTip); - } - - if ((Layer)_item.ItemData.Layer == Layer.OneHanded) - { - Item compItem2 = World.Player.FindItemByLayer(Layer.TwoHanded); - if (compItem2 != null) - { - toolTipitem2 = new CustomToolTip(compItem2, toolTipitem1.X + toolTipitem1.Width + 10, toolTipitem1.Y, hit, "Equipped Item
"); - //UIManager.Add(toolTipitem2); - toolTipList.Add(toolTipitem2); - } - } - else if ((Layer)_item.ItemData.Layer == Layer.TwoHanded) - { - Item compItem2 = World.Player.FindItemByLayer(Layer.OneHanded); - if (compItem2 != null) - { - toolTipitem2 = new CustomToolTip(compItem2, toolTipitem1.X + toolTipitem1.Width + 10, toolTipitem1.Y, hit, "Equipped Item
"); - //UIManager.Add(toolTipitem2); - toolTipList.Add(toolTipitem2); - } - } - - MultipleToolTipGump multipleToolTipGump = new MultipleToolTipGump(Mouse.Position.X + 10, Mouse.Position.Y + 10, toolTipList.ToArray(), hit); - UIManager.Add(multipleToolTipGump); - } - } - - if (SelectHighlight) - if (!MultiItemMoveGump.MoveItems.Contains(_item)) - SelectHighlight = false; - - base.Draw(batcher, x, y); - - Vector3 hueVector; - - hueVector = ShaderHueTranslator.GetHueVector(ProfileManager.CurrentProfile.GridBorderHue, false, (float)ProfileManager.CurrentProfile.GridBorderAlpha / 100); - - if (ItemGridLocked) - hueVector = ShaderHueTranslator.GetHueVector(0x2, false, (float)ProfileManager.CurrentProfile.GridBorderAlpha / 100); - if (Hightlight || SelectHighlight) - { - hueVector = ShaderHueTranslator.GetHueVector(0x34, false, 1); - } - - batcher.DrawRectangle - ( - SolidColorTextureCache.GetTexture(Color.White), - x, - y, - Width, - Height, - hueVector - ); - - if (borderHighlight) - { - int bx = x + 6; - int by = y + 6; - int bsize = ProfileManager.CurrentProfile.GridHightlightSize; - - - Texture2D borderTexture = SolidColorTextureCache.GetTexture(Color.White); - Vector3 borderHueVec = ShaderHueTranslator.GetHueVector(borderHighlightHue, false, 0.8f); - - batcher.Draw( //Top bar - borderTexture, - new Rectangle(bx, by, Width - 12, bsize), - borderHueVec - ); - - batcher.Draw( //Left Bar - borderTexture, - new Rectangle(bx, by + bsize, bsize, Height - 12 - (bsize * 2)), - borderHueVec - ); - - batcher.Draw( //Right Bar - borderTexture, - new Rectangle(bx + Width - 12 - bsize, by + bsize, bsize, Height - 12 - (bsize * 2)), - borderHueVec - ); - - batcher.Draw( //Bottom bar - borderTexture, - new Rectangle(bx, by + Height - 12 - bsize, Width - 12, bsize), - borderHueVec - ); - } - - if (hit.MouseIsOver && _item != null) - { - hueVector.Z = 0.3f; - - batcher.Draw - ( - SolidColorTextureCache.GetTexture(Color.White), - new Rectangle - ( - x + 1, - y, - Width - 1, - Height - ), - hueVector - ); - } - - if (_item != null && texture != null & rect != null) - { - hueVector = ShaderHueTranslator.GetHueVector(_item.Hue, _item.ItemData.IsPartialHue, 1f); - - Point originalSize = new Point(hit.Width, hit.Height); - Point point = new Point(); - var scale = (ProfileManager.CurrentProfile.GridContainersScale / 100f); - - if (rect.Width < hit.Width) - { - if (ProfileManager.CurrentProfile.GridContainerScaleItems) - originalSize.X = (ushort)(rect.Width * scale); - else - originalSize.X = rect.Width; - - point.X = (hit.Width >> 1) - (originalSize.X >> 1); - } - else if (rect.Width > hit.Width) - { - if (ProfileManager.CurrentProfile.GridContainerScaleItems) - originalSize.X = (ushort)(hit.Width * scale); - else - originalSize.X = hit.Width; - point.X = (hit.Width >> 1) - (originalSize.X >> 1); - } - - if (rect.Height < hit.Height) - { - if (ProfileManager.CurrentProfile.GridContainerScaleItems) - originalSize.Y = (ushort)(rect.Height * scale); - else - originalSize.Y = rect.Height; - - point.Y = (hit.Height >> 1) - (originalSize.Y >> 1); - } - else if (rect.Height > hit.Height) - { - if (ProfileManager.CurrentProfile.GridContainerScaleItems) - originalSize.Y = (ushort)(hit.Height * scale); - else - originalSize.Y = hit.Height; - - point.Y = (hit.Height >> 1) - (originalSize.Y >> 1); - } - - batcher.Draw - ( - texture, - new Rectangle - ( - x + point.X, - y + point.Y + hit.Y, - originalSize.X, - originalSize.Y - ), - new Rectangle - ( - bounds.X + rect.X, - bounds.Y + rect.Y, - rect.Width, - rect.Height - ), - hueVector - ); - count?.Draw(batcher, x + count.X, y + count.Y); - } - return true; - } - } - - private class GridSlotManager - { - private Dictionary gridSlots = new Dictionary(); - private Item container; - private List containerContents; - private int amount = 125; - private Control area; - private Dictionary itemPositions = new Dictionary(); - private List itemLocks = new List(); - - public Dictionary GridSlots { get { return gridSlots; } } - public List ContainerContents { get { return containerContents; } } - public Dictionary ItemPositions { get { return itemPositions; } } - - - public GridSlotManager(uint thisContainer, GridContainer gridContainer, Control controlArea) - { - #region VARS - area = controlArea; - foreach (GridSaveSystem.GridItemSlotSaveData item in GridSaveSystem.Instance.GetItemSlots(thisContainer)) - { - ItemPositions.Add(item.Slot, item.Serial); - if (item.IsLocked) - itemLocks.Add(item.Serial); - - } - container = World.Items.Get(thisContainer); - UpdateItems(); - if (containerContents.Count > 125) - amount = containerContents.Count; - #endregion - - for (int i = 0; i < amount; i++) - { - GridItem GI = new GridItem(0, gridItemSize, container, gridContainer, i); - gridSlots.Add(i, GI); - area.Add(GI); - } - } - - public void AddLockedItemSlot(uint serial, int specificSlot) - { - if (ItemPositions.Values.Contains(serial)) //Is this item already locked? Lets remove it from lock status for now - { - int removeSlot = ItemPositions.First((x) => x.Value == serial).Key; - ItemPositions.Remove(removeSlot); - } - - if (ItemPositions.ContainsKey(specificSlot)) //Is the slot they wanted this item in already taken? Lets remove that item - ItemPositions.Remove(specificSlot); - ItemPositions.Add(specificSlot, serial); //Now we add this item at the desired slot - } - - public GridItem FindItem(uint serial) - { - foreach (var slot in gridSlots) - if (slot.Value.LocalSerial == serial) - return slot.Value; - return null; - } - - public void RebuildContainer(List filteredItems, string searchText = "", bool overrideSort = false) - { - foreach (var slot in gridSlots) - { - slot.Value.SetGridItem(null); - } - - foreach (var spot in itemPositions) - { - Item i = World.Items.Get(spot.Value); - if (i != null) - if (filteredItems.Contains(i) && (!overrideSort || itemLocks.Contains(spot.Value))) - { - if (spot.Key < gridSlots.Count) - { - gridSlots[spot.Key].SetGridItem(i); - - if (itemLocks.Contains(spot.Value)) - gridSlots[spot.Key].ItemGridLocked = true; - - filteredItems.Remove(i); - } - } - } - - foreach (Item i in filteredItems) - { - foreach (var slot in gridSlots) - { - if (slot.Value.SlotItem != null) - continue; - slot.Value.SetGridItem(i); - AddLockedItemSlot(i, slot.Key); - break; - } - } - - foreach (var slot in gridSlots) - { - slot.Value.IsVisible = !(!string.IsNullOrWhiteSpace(searchText) && ProfileManager.CurrentProfile.GridContainerSearchMode == 0); - if (slot.Value.SlotItem != null && !string.IsNullOrWhiteSpace(searchText)) - { - if (SearchItemNameAndProps(searchText, slot.Value.SlotItem)) - { - slot.Value.Hightlight = ProfileManager.CurrentProfile.GridContainerSearchMode == 1; - slot.Value.IsVisible = true; - } - } - } - SetGridPositions(); - ApplyHighlightProperties(); - } - - public void SetLockedSlot(int slot, bool locked) - { - if (gridSlots[slot].SlotItem == null) - return; - gridSlots[slot].ItemGridLocked = locked; - if (!locked) - itemLocks.Remove(gridSlots[slot].SlotItem); - else - itemLocks.Add(gridSlots[slot].SlotItem); - } - - private void SetGridPositions() - { - int x = X_SPACING, y = 0; - foreach (var slot in gridSlots) - { - if (!slot.Value.IsVisible) - { - continue; - } - if (x + gridItemSize >= area.Width - 14) //14 is the scroll bar width - { - x = X_SPACING; - y += gridItemSize + Y_SPACING; - } - slot.Value.X = x; - slot.Value.Y = y; - slot.Value.Resize(); - x += gridItemSize + X_SPACING; - } - } - - /// - /// - /// - /// - /// List of items matching the search result, or all items if search is blank/profile does has hide search mode disabled - public List SearchResults(string search) - { - UpdateItems(); //Why is this here? Because the server sends the container before it sends the data with it so sometimes we get empty containers without reloading the contents - if (search != "") - { - if (ProfileManager.CurrentProfile.GridContainerSearchMode == 0) //Hide search mode - { - List filteredContents = new List(); - foreach (Item i in containerContents) - { - if (SearchItemNameAndProps(search, i)) - filteredContents.Add(i); - } - return filteredContents; - } - } - return containerContents; - } - - private bool SearchItemNameAndProps(string search, Item item) - { - if (item == null) - return false; - - if (World.OPL.TryGetNameAndData(item.Serial, out string name, out string data)) - { - if (name != null && name.ToLower().Contains(search.ToLower())) - return true; - if (data != null) - if (data.ToLower().Contains(search.ToLower())) - return true; - } - else - { - if (item.Name != null && item.Name.ToLower().Contains(search.ToLower())) - return true; - - if (item.ItemData.Name.ToLower().Contains(search.ToLower())) - return true; - } - - return false; - } - - public void UpdateItems() - { - containerContents = GetItemsInContainer(container); - } - - public static List GetItemsInContainer(Item _container) - { - List contents = new List(); - for (LinkedObject i = _container.Items; i != null; i = i.Next) - { - Item item = (Item)i; - var layer = (Layer)item.ItemData.Layer; - - if (_container.IsCorpse && item.Layer > 0 && !Constants.BAD_CONTAINER_LAYERS[(int)layer]) - { - continue; - } - if (item.ItemData.IsWearable && (layer == Layer.Face || layer == Layer.Beard || layer == Layer.Hair)) - { - continue; - } - - contents.Add(item); - } - return contents.OrderBy((x) => x.Graphic).ThenBy((x) => x.Hue).ToList(); - } - - public int hcount = 0; - - public void ApplyHighlightProperties() - { - if (ProfileManager.CurrentProfile.GridHighlight_CorpseOnly && !container.IsCorpse) - return; - hcount++; - Task.Factory.StartNew(() => - { - var tcount = hcount; - System.Threading.Thread.Sleep(1000); - - if (tcount != hcount) { return; } //Another call has already been made - List highlightConfigs = new List(); - for (int propIndex = 0; propIndex < ProfileManager.CurrentProfile.GridHighlight_PropNames.Count; propIndex++) - { - highlightConfigs.Add(GridHighlightData.GetGridHighlightData(propIndex)); - } - - foreach (var item in gridSlots) //For each grid slot - { - item.Value.SetHighLightBorder(0); - if (item.Value.SlotItem != null) - { - ItemPropertiesData itemData = new ItemPropertiesData(item.Value.SlotItem); - - if (itemData.HasData) - foreach (GridHighlightData configData in highlightConfigs) //For each highlight configuration - { - bool fullMatch = true; - for (int i = 0; i < configData.Properties.Count; i++) //For each property in a single grid highlight config - { - if (!fullMatch) break; - bool hasProp = false; - foreach (var singleProperty in itemData.singlePropertyData) //For each property on the item - { - if (singleProperty.Name.ToLower().Contains(configData.Properties[i].ToLower()) || singleProperty.OriginalString.ToLower().Contains(configData.Properties[i].ToLower())) //This property has a match for this highlight search text - { - hasProp = true; - if (singleProperty.FirstValue >= configData.PropMinVal[i]) //This property matches the highlight property - fullMatch = true; - else if (configData.PropMinVal[i] == -1) - fullMatch = true; - else - fullMatch = false; - } - } - if (!hasProp) fullMatch = false; - } - if (fullMatch) item.Value.SetHighLightBorder(configData.Hue); - } - } - } - }); - } - - } - - private class GridScrollArea : Control - { - private readonly ScrollBarBase _scrollBar; - private int _lastWidth; - private int _lastHeight; - - public GridScrollArea - ( - int x, - int y, - int w, - int h, - int scroll_max_height = -1 - ) - { - X = x; - Y = y; - Width = w; - Height = h; - _lastWidth = w; - _lastHeight = h; - - _scrollBar = new ScrollBar(Width - 14, 0, Height); - - - ScrollMaxHeight = scroll_max_height; - - _scrollBar.MinValue = 0; - _scrollBar.MaxValue = scroll_max_height >= 0 ? scroll_max_height : Height; - _scrollBar.Parent = this; - - AcceptMouseInput = true; - WantUpdateSize = false; - CanMove = true; - ScrollbarBehaviour = ScrollbarBehaviour.ShowAlways; - } - - - public int ScrollMaxHeight { get; set; } = -1; - public ScrollbarBehaviour ScrollbarBehaviour { get; set; } - public int ScrollValue => _scrollBar.Value; - public int ScrollMinValue => _scrollBar.MinValue; - public int ScrollMaxValue => _scrollBar.MaxValue; - - public Rectangle ScissorRectangle; - - public override void Update() - { - base.Update(); - - CalculateScrollBarMaxValue(); - - if (Width != _lastWidth || Height != _lastHeight) - { - _scrollBar.X = Width - 14; - _scrollBar.Height = Height; - _lastWidth = Width; - _lastHeight = Height; - } - - if (ScrollbarBehaviour == ScrollbarBehaviour.ShowAlways) - { - _scrollBar.IsVisible = true; - } - else if (ScrollbarBehaviour == ScrollbarBehaviour.ShowWhenDataExceedFromView) - { - _scrollBar.IsVisible = _scrollBar.MaxValue > _scrollBar.MinValue; - } - } - - public void Scroll(bool isup) - { - if (isup) - { - _scrollBar.Value -= _scrollBar.ScrollStep; - } - else - { - _scrollBar.Value += _scrollBar.ScrollStep; - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - _scrollBar.Draw(batcher, x + _scrollBar.X, y + _scrollBar.Y); - - if (batcher.ClipBegin(x + ScissorRectangle.X, y + ScissorRectangle.Y, Width - 14 + ScissorRectangle.Width, Height + ScissorRectangle.Height)) - { - for (int i = 1; i < Children.Count; i++) - { - Control child = Children[i]; - - if (!child.IsVisible) - { - continue; - } - - int finalY = y + child.Y - _scrollBar.Value + ScissorRectangle.Y; - - child.Draw(batcher, x + child.X, finalY); - } - - batcher.ClipEnd(); - } - - return true; - } - - protected override void OnMouseWheel(MouseEventType delta) - { - switch (delta) - { - case MouseEventType.WheelScrollUp: - _scrollBar.Value -= _scrollBar.ScrollStep; - - break; - - case MouseEventType.WheelScrollDown: - _scrollBar.Value += _scrollBar.ScrollStep; - - break; - } - } - - public override void Clear() - { - for (int i = 1; i < Children.Count; i++) - { - Children[i].Dispose(); - } - } - - private void CalculateScrollBarMaxValue() - { - _scrollBar.Height = ScrollMaxHeight >= 0 ? ScrollMaxHeight : Height; - bool maxValue = _scrollBar.Value == _scrollBar.MaxValue && _scrollBar.MaxValue != 0; - - int startX = 0, startY = 0, endX = 0, endY = 0; - - for (int i = 1; i < Children.Count; i++) - { - Control c = Children[i]; - - if (c.IsVisible && !c.IsDisposed) - { - if (c.X < startX) - { - startX = c.X; - } - - if (c.Y < startY) - { - startY = c.Y; - } - - if (c.Bounds.Right > endX) - { - endX = c.Bounds.Right; - } - - if (c.Bounds.Bottom > endY) - { - endY = c.Bounds.Bottom; - } - } - } - - int width = Math.Abs(startX) + Math.Abs(endX); - int height = Math.Abs(startY) + Math.Abs(endY) - _scrollBar.Height; - height = Math.Max(0, height - (-ScissorRectangle.Y + ScissorRectangle.Height)); - - if (height > 0) - { - _scrollBar.MaxValue = height; - - if (maxValue) - { - _scrollBar.Value = _scrollBar.MaxValue; - } - } - else - { - _scrollBar.Value = _scrollBar.MaxValue = 0; - } - - _scrollBar.UpdateOffset(0, Offset.Y); - - for (int i = 1; i < Children.Count; i++) - { - Children[i].UpdateOffset(0, -_scrollBar.Value + ScissorRectangle.Y); - } - } - } - - private class GridContainerPreview : Gump - { - private readonly AlphaBlendControl _background; - private readonly Item _container; - - private const int WIDTH = 170; - private const int HEIGHT = 150; - private const int GRIDSIZE = 50; - - public GridContainerPreview(uint serial, int x, int y) : base(serial, 0) - { - _container = World.Items.Get(serial); - if (_container == null) - { - Dispose(); - return; - } - - X = x - WIDTH - 20; - Y = y - HEIGHT - 20; - _background = new AlphaBlendControl(); - _background.Width = WIDTH; - _background.Height = HEIGHT; - - CanCloseWithRightClick = true; - Add(_background); - InvalidateContents = true; - } - - protected override void UpdateContents() - { - base.UpdateContents(); - if (InvalidateContents && !IsDisposed && IsVisible) - { - if (_container != null && _container.Items != null) - { - int currentCount = 0, lastX = 0, lastY = 0; - for (LinkedObject i = _container.Items; i != null; i = i.Next) - { - - Item item = (Item)i; - if (item == null) - continue; - - if (currentCount > 8) - break; - - StaticPic gridItem = new StaticPic(item.DisplayedGraphic, item.Hue); - gridItem.X = lastX; - if (gridItem.X + GRIDSIZE > WIDTH) - { - gridItem.X = 0; - lastX = 0; - lastY += GRIDSIZE; - - } - lastX += GRIDSIZE; - gridItem.Y = lastY; - //gridItem.Width = GRIDSIZE; - //gridItem.Height = GRIDSIZE; - Add(gridItem); - - currentCount++; - - - } - } - } - } - - public override void Update() - { - if (IsDisposed) - { - return; - } - - if (_container == null || _container.IsDestroyed || _container.OnGround && _container.Distance > 3) - { - Dispose(); - - return; - } - - base.Update(); - } - } - - private class GridSaveSystem - { - /// - /// Time cutoff in seconds - /// 60*60 = 1 hour - /// * 24 = 1 day - /// * 60 = ~2 month - /// - private const long TIME_CUTOFF = ((60 * 60) * 24) * 60; - private string gridSavePath = Path.Combine(ProfileManager.ProfilePath, "GridContainers.xml"); - private XDocument saveDocument; - private XElement rootElement; - private bool enabled = false; - - private static GridSaveSystem instance; - public static GridSaveSystem Instance - { - get - { - if (instance == null) - instance = new GridSaveSystem(); - return instance; - } - } - - private GridSaveSystem() - { - if (!SaveFileCheck()) - { - enabled = false; - return; - } - - try - { - saveDocument = XDocument.Load(gridSavePath); - } - catch - { - saveDocument = new XDocument(); - } - - rootElement = saveDocument.Element("grid_gumps"); - if (rootElement == null) - { - saveDocument.Add(new XElement("grid_gumps")); - rootElement = saveDocument.Root; - } - enabled = true; - } - - public bool SaveContainer(uint serial, Dictionary gridSlots, int width, int height, int lastX = 100, int lastY = 100, bool? useOriginalContainer = false, bool autoSort = false) - { - if (!enabled) - return false; - - if (useOriginalContainer == null) - useOriginalContainer = false; - - XElement thisContainer = rootElement.Element("container_" + serial.ToString()); - if (thisContainer == null) - { - thisContainer = new XElement("container_" + serial.ToString()); - rootElement.Add(thisContainer); - } - else - thisContainer.RemoveNodes(); - - thisContainer.SetAttributeValue("last_opened", DateTimeOffset.Now.ToUnixTimeSeconds().ToString()); - thisContainer.SetAttributeValue("width", width.ToString()); - thisContainer.SetAttributeValue("height", height.ToString()); - thisContainer.SetAttributeValue("lastX", lastX.ToString()); - thisContainer.SetAttributeValue("lastY", lastY.ToString()); - thisContainer.SetAttributeValue("useOriginalContainer", useOriginalContainer.ToString()); - thisContainer.SetAttributeValue("autoSort", autoSort.ToString()); - - foreach (var slot in gridSlots) - { - if (slot.Value.SlotItem == null) - continue; - XElement item_slot = new XElement("item"); - item_slot.SetAttributeValue("serial", slot.Value.SlotItem.Serial.ToString()); - item_slot.SetAttributeValue("locked", slot.Value.ItemGridLocked.ToString()); - item_slot.SetAttributeValue("slot", slot.Key.ToString()); - thisContainer.Add(item_slot); - } - RemoveOldContainers(); - - saveDocument.Save(gridSavePath); - - return true; - } - - public List GetItemSlots(uint container) - { - List items = new List(); - - XElement thisContainer = rootElement.Element("container_" + container.ToString()); - if (thisContainer != null) - { - foreach (XElement itemSlot in thisContainer.Elements("item")) - { - XAttribute slot, serial, isLockedAttribute; - slot = itemSlot.Attribute("slot"); - serial = itemSlot.Attribute("serial"); - isLockedAttribute = itemSlot.Attribute("locked"); - if (slot != null && serial != null) - { - if (int.TryParse(slot.Value, out int slotV)) - if (uint.TryParse(serial.Value, out uint serialV)) - { - if (isLockedAttribute != null && bool.TryParse(isLockedAttribute.Value, out bool isLocked)) - items.Add(new GridItemSlotSaveData(slotV, serialV, isLocked)); - else - items.Add(new GridItemSlotSaveData(slotV, serialV, false)); - } - } - } - } - - return items; - } - - public class GridItemSlotSaveData - { - public readonly int Slot; - public readonly uint Serial; - public readonly bool IsLocked; - - public GridItemSlotSaveData(int slot, uint serial, bool isLocked) - { - this.Slot = slot; - this.Serial = serial; - this.IsLocked = isLocked; - } - } - - public Point GetLastSize(uint container) - { - Point lastSize = new Point(GetWidth(), GetHeight()); - - XElement thisContainer = rootElement.Element("container_" + container.ToString()); - if (thisContainer != null) - { - XAttribute width, height; - width = thisContainer.Attribute("width"); - height = thisContainer.Attribute("height"); - if (width != null && height != null) - { - int.TryParse(width.Value, out lastSize.X); - int.TryParse(height.Value, out lastSize.Y); - } - } - - return lastSize; - } - - public Point GetLastPosition(uint container) - { - Point LastPos = new Point(GridContainer.lastX, GridContainer.lastY); - - XElement thisContainer = rootElement.Element("container_" + container.ToString()); - if (thisContainer != null) - { - XAttribute lastX, lastY; - lastX = thisContainer.Attribute("lastX"); - lastY = thisContainer.Attribute("lastY"); - if (lastX != null && lastY != null) - { - int.TryParse(lastX.Value, out LastPos.X); - int.TryParse(lastY.Value, out LastPos.Y); - } - } - - return LastPos; - } - - public bool UseOriginalContainerGump(uint container) - { - bool useOriginalContainer = false; - - XElement thisContainer = rootElement.Element("container_" + container.ToString()); - if (thisContainer != null) - { - XAttribute useOriginal; - useOriginal = thisContainer.Attribute("useOriginalContainer"); - if (useOriginal != null) - { - bool.TryParse(useOriginal.Value, out useOriginalContainer); - } - } - - return useOriginalContainer; - } - - public bool AutoSortContainer(uint container) - { - bool autoSort = false; - - XElement thisContainer = rootElement.Element("container_" + container.ToString()); - if (thisContainer != null) - { - XAttribute attribute = thisContainer.Attribute("autoSort"); - if (attribute != null) - { - bool.TryParse(attribute.Value, out autoSort); - } - } - - return autoSort; - } - - private void RemoveOldContainers() - { - long cutOffTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds() - TIME_CUTOFF; - List removeMe = new List(); - foreach (XElement container in rootElement.Elements()) - { - XAttribute lastOpened = container.Attribute("last_opened"); - if (lastOpened != null) - { - long lo = cutOffTime; - long.TryParse(lastOpened.Value, out lo); - - if (lo < cutOffTime) - removeMe.Add(container); - } - } - foreach (XElement container in removeMe) - container.Remove(); - } - - private bool SaveFileCheck() - { - try - { - if (!File.Exists(gridSavePath)) - File.Create(gridSavePath).Dispose(); - } - catch (Exception e) - { - Console.WriteLine("Could not create file: " + gridSavePath); - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - sb.AppendLine("######################## [START LOG] ########################"); - - sb.AppendLine($"TazUO - {CUOEnviroment.Version} - {DateTime.Now}"); - - sb.AppendLine - ($"OS: {Environment.OSVersion.Platform} {(Environment.Is64BitOperatingSystem ? "x64" : "x86")}"); - - sb.AppendLine(); - - if (Settings.GlobalSettings != null) - { - sb.AppendLine($"Shard: {Settings.GlobalSettings.IP}"); - sb.AppendLine($"ClientVersion: {Settings.GlobalSettings.ClientVersion}"); - sb.AppendLine(); - } - - sb.AppendFormat("Exception:\n{0}\n", e); - sb.AppendLine("######################## [END LOG] ########################"); - sb.AppendLine(); - sb.AppendLine(); - - Log.Panic(e.ToString()); - string path = Path.Combine(CUOEnviroment.ExecutablePath, "Logs"); - - if (!Directory.Exists(path)) - Directory.CreateDirectory(path); - - using (LogFile crashfile = new LogFile(path, "crash.txt")) - { - crashfile.WriteAsync(sb.ToString()).RunSynchronously(); - } - return false; - } - return true; - } - - public void Clear() - { - instance = null; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/GridHightlightMenu.cs b/src/ClassicUO.Client/Game/UI/Gumps/GridHightlightMenu.cs deleted file mode 100644 index 9f15383a7..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/GridHightlightMenu.cs +++ /dev/null @@ -1,492 +0,0 @@ -using ClassicUO.Configuration; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using static ClassicUO.Game.UI.Gumps.OptionsGump; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class GridHightlightMenu : Gump - { - private const int WIDTH = 350, HEIGHT = 500; - private AlphaBlendControl background; - private SettingsSection highlightSection; - private ScrollArea highlightSectionScroll; - - public GridHightlightMenu(int x = 100, int y = 100) : base(0, 0) - { - #region SET VARS - Width = WIDTH; - Height = HEIGHT; - CanMove = true; - AcceptMouseInput = true; - CanCloseWithRightClick = true; - X = x; - Y = y; - #endregion - - BuildGump(); - } - - private void BuildGump() - { - { - background = new AlphaBlendControl(0.85f); - background.Width = WIDTH; - background.Height = HEIGHT; - Add(background); - }//Background - int y = 0; - { - SettingsSection section = new SettingsSection("Grid highlighting settings", WIDTH); - section.Add(new Label("You can add object properties that you would like the grid to be highlighted for here.", true, 0xffff, WIDTH)); - - NiceButton _; - section.Add(_ = new NiceButton(0, 0, 40, 20, ButtonAction.Activate, "Add +") { IsSelectable = false }); - _.MouseUp += (s, e) => - { - if (e.Button == Input.MouseButtonType.Left) - { - highlightSectionScroll?.Add(NewAreaSection(ProfileManager.CurrentProfile.GridHighlight_Name.Count, y)); - y += 21; - } - }; - - section.AddRight(_ = new NiceButton(0, 0, 60, 20, ButtonAction.Activate, "Export") { IsSelectable = false }); - _.MouseUp += (s, e) => - { - if (e.Button == Input.MouseButtonType.Left) - { - ExportGridHightlightSettings(); - } - }; - - section.AddRight(_ = new NiceButton(0, 0, 60, 20, ButtonAction.Activate, "Import") { IsSelectable = false }); - _.MouseUp += (s, e) => - { - if (e.Button == Input.MouseButtonType.Left) - { - ImportGridHighlightSettings(); - } - }; - - Add(section); - y = section.Y + section.Height; - }//Top section - - highlightSection = new SettingsSection("", WIDTH) { Y = y }; - highlightSection.Add(highlightSectionScroll = new ScrollArea(0, 0, WIDTH - 20, Height - y - 10, true) { ScrollbarBehaviour = ScrollbarBehaviour.ShowAlways }); ; - - y = 0; - for (int i = 0; i < ProfileManager.CurrentProfile.GridHighlight_Name.Count; i++) - { - highlightSectionScroll.Add(NewAreaSection(i, y)); - y += 21; - } - - Add(highlightSection); - } - - private Area NewAreaSection(int keyLoc, int y) - { - GridHighlightData data = GridHighlightData.GetGridHighlightData(keyLoc); - Area area = new Area() { Y = y }; - area.Width = WIDTH - 40; - area.Height = 150; - y = 0; - - NiceButton _button, _del; - area.Add(_button = new NiceButton(WIDTH - 170, y, 130, 20, ButtonAction.Activate, "Open property menu") { IsSelectable = false }); - _button.MouseUp += (s, e) => - { - if (e.Button == Input.MouseButtonType.Left) - { - UIManager.GetGump()?.Dispose(); - UIManager.Add(new GridHightlightProperties(keyLoc, 100, 100)); - } - }; - - ModernColorPicker.HueDisplay hueDisplay; - area.Add(hueDisplay = new ModernColorPicker.HueDisplay(data.Hue, null, true) { X = 150, Y = y }); - hueDisplay.SetTooltip("Select grid highlight hue"); - hueDisplay.HueChanged += (s, e) => - { - data.Hue = hueDisplay.Hue; - data.Save(); - area.Add(new FadingLabel(10, "Saved", true, 0xff) { X = hueDisplay.X - 40, Y = hueDisplay.Y }); - }; - - InputField _name; - area.Add(_name = new InputField(0x0BB8, 0xFF, 0xFFFF, true, 120, 20) { X = 25, Y = y, AcceptKeyboardInput = true }); - _name.SetText(data.Name); - - _name.TextChanged += (s, e) => - { - Task.Factory.StartNew(() => - { - var tVal = _name.Text; - System.Threading.Thread.Sleep(2500); - if (_name.Text == tVal) - { - data.Name = _name.Text; - data.Save(); - area.Add(new FadingLabel(10, "Saved", true, 0xff) { X = _name.X, Y = _name.Y - 20 }); - } - }); - }; - - area.Add(_del = new NiceButton(0, y, 20, 20, ButtonAction.Activate, "X") { IsSelectable = false }); - _del.SetTooltip("Delete this highlight configuration"); - _del.MouseUp += (s, e) => - { - if (e.Button == Input.MouseButtonType.Left) - { - data.Delete(); - Dispose(); - UIManager.Add(new GridHightlightMenu(X, Y)); - } - }; - - y += 20; - - return area; - } - - public static GridHighlightData[] GetAllGridHighlightData() - { - List data = new List(); - for (int i = 0; i < ProfileManager.CurrentProfile.GridHighlight_Name.Count; i++) - { - data.Add(GridHighlightData.GetGridHighlightData(i)); - } - return data.ToArray(); - } - - public static void ExportGridHightlightSettings() - { - GridHighlightData[] allData = GetAllGridHighlightData(); - - if (!CUOEnviroment.IsUnix) - { - Thread t = new Thread(() => - { - System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog(); - saveFileDialog1.Filter = "Json|*.json"; - saveFileDialog1.Title = "Save grid highlight settings"; - saveFileDialog1.ShowDialog(); - - string result = JsonSerializer.Serialize(allData); - - // If the file name is not an empty string open it for saving. - if (saveFileDialog1.FileName != "") - { - System.IO.FileStream fs = - (System.IO.FileStream)saveFileDialog1.OpenFile(); - // NOTE that the FilterIndex property is one-based. - switch (saveFileDialog1.FilterIndex) - { - default: - byte[] data = Encoding.UTF8.GetBytes(result); - fs.Write(data, 0, data.Length); - break; - } - - fs.Close(); - } - }); - t.SetApartmentState(ApartmentState.STA); - t.Start(); - } - } - - public static void ImportGridHighlightSettings() - { - if (!CUOEnviroment.IsUnix) - { - Thread t = new Thread(() => - { - System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog(); - openFileDialog.Filter = "Json|*.json"; - openFileDialog.Title = "Import grid highlight settings"; - openFileDialog.ShowDialog(); - - // If the file name is not an empty string open it for saving. - if (openFileDialog.FileName != "") - { - // NOTE that the FilterIndex property is one-based. - switch (openFileDialog.FilterIndex) - { - default: - try - { - string result = File.ReadAllText(openFileDialog.FileName); - - GridHighlightData[] imported = JsonSerializer.Deserialize(result); - - foreach (GridHighlightData importedData in imported) - importedData.Save(); - - UIManager.GetGump()?.Dispose(); - UIManager.Add(new GridHightlightMenu()); - - } - catch (System.Exception e) - { - GameActions.Print("It looks like there was an error trying to import your grid highlight settings.", 32); - Console.WriteLine(e.ToString()); - } - break; - } - } - }); - t.SetApartmentState(ApartmentState.STA); - t.Start(); - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - batcher.DrawRectangle( - SolidColorTextureCache.GetTexture(Color.LightGray), - x - 1, y - 1, - WIDTH + 1, HEIGHT + 1, - new Vector3(0, 0, 1) - ); - - return true; - } - - public class GridHighlightData - { - private int keyLoc = -1; - - public string Name { get; set; } = "Name"; - public ushort Hue { get; set; } = 1; - public List Properties { get; set; } = new List(); - public List PropMinVal { get; set; } = new List(); - - public GridHighlightData() - { - - } - - private GridHighlightData(int keyLoc) - { - this.keyLoc = keyLoc; - if (ProfileManager.CurrentProfile.GridHighlight_Name.Count > keyLoc) //Key exists? - { - Name = ProfileManager.CurrentProfile.GridHighlight_Name[keyLoc]; - Hue = ProfileManager.CurrentProfile.GridHighlight_Hue[keyLoc]; - Properties = ProfileManager.CurrentProfile.GridHighlight_PropNames[keyLoc]; - PropMinVal = ProfileManager.CurrentProfile.GridHighlight_PropMinVal[keyLoc]; - } - else - { - ProfileManager.CurrentProfile.GridHighlight_Name.Add(Name); - ProfileManager.CurrentProfile.GridHighlight_Hue.Add(Hue); - Properties = new List(); - ProfileManager.CurrentProfile.GridHighlight_PropNames.Add(Properties); - PropMinVal = new List(); - ProfileManager.CurrentProfile.GridHighlight_PropMinVal.Add(PropMinVal); - } - - this.keyLoc = keyLoc; - } - - public void Save() - { - if (keyLoc == -1) - SaveAsNew(); - else - { - SaveName(); - SaveHue(); - SaveProps(); - SaveMinVals(); - } - } - - private void SaveName() - { - ProfileManager.CurrentProfile.GridHighlight_Name[keyLoc] = Name; - } - - private void SaveHue() - { - ProfileManager.CurrentProfile.GridHighlight_Hue[keyLoc] = Hue; - } - - private void SaveProps() - { - ProfileManager.CurrentProfile.GridHighlight_PropNames[keyLoc] = Properties; - } - - private void SaveMinVals() - { - ProfileManager.CurrentProfile.GridHighlight_PropMinVal[keyLoc] = PropMinVal; - } - - private void SaveAsNew() - { - ProfileManager.CurrentProfile.GridHighlight_Name.Add(Name); - ProfileManager.CurrentProfile.GridHighlight_Hue.Add(Hue); - ProfileManager.CurrentProfile.GridHighlight_PropNames.Add(Properties); - ProfileManager.CurrentProfile.GridHighlight_PropMinVal.Add(PropMinVal); - keyLoc = ProfileManager.CurrentProfile.GridHighlight_Name.Count; - } - - public void Delete() - { - ProfileManager.CurrentProfile.GridHighlight_Name.RemoveAt(keyLoc); - ProfileManager.CurrentProfile.GridHighlight_Hue.RemoveAt(keyLoc); - ProfileManager.CurrentProfile.GridHighlight_PropNames.RemoveAt(keyLoc); - ProfileManager.CurrentProfile.GridHighlight_PropMinVal.RemoveAt(keyLoc); - } - - public static GridHighlightData GetGridHighlightData(int keyLoc) - { - return new GridHighlightData(keyLoc); - } - } - - private class GridHightlightProperties : Gump - { - private int lastYitem = 0; - private ScrollArea scrollArea; - GridHighlightData data; - private readonly int keyLoc; - - public GridHightlightProperties(int keyLoc, int x, int y) : base(0, 0) - { - data = GridHighlightData.GetGridHighlightData(keyLoc); - X = x; - Y = y; - Width = WIDTH; - Height = HEIGHT; - CanMove = true; - AcceptMouseInput = true; - CanCloseWithRightClick = true; - - Add(new AlphaBlendControl(0.85f) { Width = WIDTH, Height = HEIGHT }); - - NiceButton _addPropertyButton; - Add(_addPropertyButton = new NiceButton(0, 0, 120, 20, ButtonAction.Activate, "Add property") { IsSelectable = false }); - _addPropertyButton.MouseUp += (s, e) => - { - if (e.Button == Input.MouseButtonType.Left) - { - AddProperty(data.Properties.Count); - - lastYitem += 20; - } - }; - - Add(scrollArea = new ScrollArea(0, 20, WIDTH, HEIGHT - 20, true) { ScrollbarBehaviour = ScrollbarBehaviour.ShowAlways }); - - scrollArea.Add(new Label("Property name", true, 0xffff, 120) { X = 0, Y = lastYitem }); - scrollArea.Add(new Label("Min value", true, 0xffff, 120) { X = 180, Y = lastYitem }); - - lastYitem += 20; - - for (int i = 0; i < data.Properties.Count; i++) - { - AddProperty(i); - lastYitem += 20; - } - - this.keyLoc = keyLoc; - } - - private void AddProperty(int subKeyLoc) - { - while (data.Properties.Count <= subKeyLoc) - { - data.Properties.Add(""); - data.PropMinVal.Add(-1); - - } - data.Save(); - InputField propInput, valInput; - scrollArea.Add(propInput = new InputField(0x0BB8, 0xFF, 0xFFFF, true, 150, 20) { Y = lastYitem }); - propInput.SetText(data.Properties[subKeyLoc]); - propInput.TextChanged += (s, e) => - { - Task.Factory.StartNew(() => - { - var tVal = propInput.Text; - System.Threading.Thread.Sleep(2500); - if (propInput.Text == tVal) - { - data.Properties[subKeyLoc] = propInput.Text; - data.Save(); - propInput.Add(new FadingLabel(10, "Saved", true, 0xff) { X = 0, Y = -20 }); - } - }); - }; - - scrollArea.Add(valInput = new InputField(0x0BB8, 0xFF, 0xFFFF, true, 100, 20) { X = 180, Y = lastYitem, NumbersOnly = true }); - valInput.SetText(data.PropMinVal[subKeyLoc].ToString()); - valInput.TextChanged += (s, e) => - { - Task.Factory.StartNew(() => - { - var tVal = valInput.Text; - System.Threading.Thread.Sleep(2500); - if (valInput.Text == tVal) - { - if (int.TryParse(valInput.Text, out int val)) - { - data.PropMinVal[subKeyLoc] = val; - data.Save(); - valInput.Add(new FadingLabel(10, "Saved", true, 0xff) { X = 0, Y = -20 }); - } - else - { - valInput.Add(new FadingLabel(20, "Couldn't parse number", true, 0xff) { X = 0, Y = -20 }); - } - } - }); - }; - - NiceButton _del; - scrollArea.Add(_del = new NiceButton(285, lastYitem, 20, 20, ButtonAction.Activate, "X") { IsSelectable = false }); - _del.SetTooltip("Delete this property"); - _del.MouseUp += (s, e) => - { - if (e.Button == Input.MouseButtonType.Left) - { - Dispose(); - data.Properties.RemoveAt(subKeyLoc); - data.PropMinVal.RemoveAt(subKeyLoc); - data.Save(); - UIManager.Add(new GridHightlightProperties(keyLoc, X, Y)); - } - }; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - batcher.DrawRectangle( - SolidColorTextureCache.GetTexture(Color.LightGray), - x - 1, y - 1, - WIDTH + 2, HEIGHT + 2, - new Vector3(0, 0, 1) - ); - - return true; - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/GridLootGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/GridLootGump.cs deleted file mode 100644 index b11152f22..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/GridLootGump.cs +++ /dev/null @@ -1,592 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Linq; -using ClassicUO.Configuration; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class GridLootGump : Gump - { - private const int MAX_WIDTH = 300; - private const int MAX_HEIGHT = 420; - - private static int _lastX = ProfileManager.CurrentProfile.GridLootType == 2 ? 200 : 100; - private static int _lastY = 100; - private readonly AlphaBlendControl _background; - private readonly NiceButton _buttonPrev, - _buttonNext, - _setlootbag; - private readonly Item _corpse; - - private int _currentPage = 1; - private readonly Label _currentPageLabel; - private readonly Label _corpseNameLabel; - private readonly bool _hideIfEmpty; - private int _pagesCount; - private bool firstItemsLoaded = false; - - public GridLootGump(uint local) : base(local, 0) - { - _corpse = World.Items.Get(local); - - if (_corpse == null) - { - Dispose(); - - return; - } - - if (World.Player.ManualOpenedCorpses.Contains(LocalSerial)) - { - World.Player.ManualOpenedCorpses.Remove(LocalSerial); - } - else if ( - World.Player.AutoOpenedCorpses.Contains(LocalSerial) - && ProfileManager.CurrentProfile != null - && ProfileManager.CurrentProfile.SkipEmptyCorpse - ) - { - IsVisible = false; - _hideIfEmpty = true; - } - - X = _lastX; - Y = _lastY; - - CanMove = true; - AcceptMouseInput = true; - WantUpdateSize = true; - CanCloseWithRightClick = true; - _background = new AlphaBlendControl(); - //_background.Width = MAX_WIDTH; - //_background.Height = MAX_HEIGHT; - Add(_background); - - Width = _background.Width; - Height = _background.Height; - - _setlootbag = new NiceButton( - 3, - Height - 23, - 100, - 20, - ButtonAction.Activate, - ResGumps.SetLootBag - ) - { - ButtonParameter = 2, - IsSelectable = false - }; - - Add(_setlootbag); - - _buttonPrev = new NiceButton( - Width - 80, - Height - 20, - 40, - 20, - ButtonAction.Activate, - ResGumps.Prev - ) - { - ButtonParameter = 0, - IsSelectable = false - }; - - _buttonNext = new NiceButton( - Width - 40, - Height - 20, - 40, - 20, - ButtonAction.Activate, - ResGumps.Next - ) - { - ButtonParameter = 1, - IsSelectable = false - }; - - _buttonNext.IsVisible = _buttonPrev.IsVisible = false; - - Add(_buttonPrev); - Add(_buttonNext); - - Add( - _currentPageLabel = new Label("1", true, 999, align: TEXT_ALIGN_TYPE.TS_CENTER) - { - X = Width / 2 - 5, - Y = Height - 20 - } - ); - - Add( - _corpseNameLabel = new Label( - GetCorpseName(), - true, - 0x0481, - align: TEXT_ALIGN_TYPE.TS_CENTER, - maxwidth: 300 - ) - { - Width = 300, - X = 0, - Y = 0 - } - ); - } - - public override void OnButtonClick(int buttonID) - { - if (buttonID == 0) - { - _currentPage--; - - if (_currentPage <= 1) - { - _currentPage = 1; - _buttonPrev.IsVisible = false; - } - - _buttonNext.IsVisible = true; - ChangePage(_currentPage); - - _currentPageLabel.Text = ActivePage.ToString(); - _currentPageLabel.X = Width / 2 - _currentPageLabel.Width / 2; - } - else if (buttonID == 1) - { - _currentPage++; - - if (_currentPage >= _pagesCount) - { - _currentPage = _pagesCount; - _buttonNext.IsVisible = false; - } - - _buttonPrev.IsVisible = true; - - ChangePage(_currentPage); - - _currentPageLabel.Text = ActivePage.ToString(); - _currentPageLabel.X = Width / 2 - _currentPageLabel.Width / 2; - } - else if (buttonID == 2) - { - GameActions.Print(ResGumps.TargetContainerToGrabItemsInto); - TargetManager.SetTargeting(CursorTarget.SetGrabBag, 0, TargetType.Neutral); - } - else - { - base.OnButtonClick(buttonID); - } - } - - protected override void UpdateContents() - { - const int GRID_ITEM_SIZE = 50; - - int x = 20; - int y = 20; - - foreach (GridLootItem gridLootItem in Children.OfType()) - { - gridLootItem.Dispose(); - } - - int count = 0; - _pagesCount = 1; - - _background.Width = x; - _background.Height = y; - - int line = 1; - int row = 0; - - for (int displayGroup = 0; displayGroup < 2; displayGroup++) - { - for (LinkedObject i = _corpse.Items; i != null; i = i.Next) - { - Item it = (Item)i; - - if (!ItemBelongsToGroup(it, displayGroup) || !it.IsLootable) - { - continue; - } - - GridLootItem gridItem = new GridLootItem(it, GRID_ITEM_SIZE); - - if (x >= MAX_WIDTH - 20) - { - x = 20; - ++line; - - y += gridItem.Height + 20; - - if (y >= MAX_HEIGHT - 60) - { - _pagesCount++; - y = 20; - //line = 1; - } - } - - gridItem.X = x; - gridItem.Y = y + 20; - Add(gridItem, _pagesCount); - - x += gridItem.Width + 20; - ++row; - ++count; - } - } - - _background.Width = (GRID_ITEM_SIZE + 20) * row + 20; - _background.Height = 20 + 40 + (GRID_ITEM_SIZE + 20) * line + 40; - - if (_background.Height >= MAX_HEIGHT - 40) - { - _background.Height = MAX_HEIGHT; - } - - _background.Width = MAX_WIDTH; - - if (ActivePage <= 1) - { - ActivePage = 1; - _buttonNext.IsVisible = _pagesCount > 1; - _buttonPrev.IsVisible = false; - } - else if (ActivePage >= _pagesCount) - { - ActivePage = _pagesCount; - _buttonNext.IsVisible = false; - _buttonPrev.IsVisible = _pagesCount > 1; - } - else if (ActivePage > 1 && ActivePage < _pagesCount) - { - _buttonNext.IsVisible = true; - _buttonPrev.IsVisible = true; - } - - if (count == 0) - { - GameActions.Print(ResGumps.CorpseIsEmpty); - Dispose(); - } - else if (_hideIfEmpty && !IsVisible) - { - IsVisible = true; - } - - if(!firstItemsLoaded) - { - firstItemsLoaded = true; - AutoLootManager.Instance.HandleCorpse(_corpse); - } - } - - private bool ItemBelongsToGroup(Item it, int group) - { - // Note: items must be assigned to groups in a mutually-exclusive manner, so that each item occurs only once in the grid - if (it.ItemData.IsStackable) - return group > 0; - else - return group == 0; - } - - public override void Dispose() - { - if (_corpse != null) - { - if (_corpse == SelectedObject.CorpseObject) - { - SelectedObject.CorpseObject = null; - } - } - - _lastX = X; - _lastY = Y; - - base.Dispose(); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (!IsVisible || IsDisposed) - { - return false; - } - - base.Draw(batcher, x, y); - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - batcher.DrawRectangle( - SolidColorTextureCache.GetTexture(Color.Gray), - x, - y, - Width, - Height, - hueVector - ); - - return true; - } - - public override void Update() - { - if (_corpse == null || _corpse.IsDestroyed || _corpse.OnGround && _corpse.Distance > 3) - { - Dispose(); - - return; - } - - base.Update(); - - if (IsDisposed) - { - return; - } - - if (_background.Width < 100) - { - _background.Width = 100; - } - - if (_background.Height < 120) - { - _background.Height = 120; - } - - Width = _background.Width; - Height = _background.Height; - - _buttonPrev.X = Width - 80; - _buttonPrev.Y = Height - 23; - _buttonNext.X = Width - 40; - _buttonNext.Y = Height - 20; - _setlootbag.X = 3; - _setlootbag.Y = Height - 23; - _currentPageLabel.X = Width / 2 - 5; - _currentPageLabel.Y = Height - 20; - - _corpseNameLabel.Text = GetCorpseName(); - - WantUpdateSize = true; - - if ( - _corpse != null - && !_corpse.IsDestroyed - && UIManager.MouseOverControl != null - && ( - UIManager.MouseOverControl == this - || UIManager.MouseOverControl.RootParent == this - ) - ) - { - SelectedObject.Object = _corpse; - SelectedObject.CorpseObject = _corpse; - } - } - - protected override void OnMouseExit(int x, int y) - { - if (_corpse != null && !_corpse.IsDestroyed) - { - SelectedObject.CorpseObject = null; - } - } - - private string GetCorpseName() - { - return _corpse.Name?.Length > 0 ? _corpse.Name : "a corpse"; - } - - private class GridLootItem : Control - { - private readonly HitBox _hit; - - public GridLootItem(uint serial, int size) - { - LocalSerial = serial; - - Item item = World.Items.Get(serial); - - if (item == null) - { - Dispose(); - - return; - } - - CanMove = false; - - HSliderBar amount = new HSliderBar( - 0, - 0, - size, - 1, - // OSI has an odd behaviour. It uses the Amount field to store unknown data for non stackable items. - item.ItemData.IsStackable - ? item.Amount - : 1, - item.ItemData.IsStackable ? item.Amount : 1, - HSliderBarStyle.MetalWidgetRecessedBar, - true, - color: 0xFFFF, - drawUp: true - ); - - Add(amount); - - amount.IsVisible = amount.IsEnabled = amount.MaxValue > 1; - - AlphaBlendControl background = new AlphaBlendControl(); - background.Y = 15; - background.Width = size; - background.Height = size; - Add(background); - - _hit = new HitBox(0, 15, size, size, null, 0f); - Add(_hit); - - if (World.ClientFeatures.TooltipsEnabled) - { - _hit.SetTooltip(item); - } - - _hit.MouseUp += (sender, e) => - { - if (e.Button == MouseButtonType.Left) - { - GameActions.GrabItem(item, (ushort)amount.Value); - } - }; - - Width = background.Width; - Height = background.Height + 15; - - WantUpdateSize = false; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - Item item = World.Items.Get(LocalSerial); - - Vector3 hueVector; - - if (item != null) - { - ref readonly var artInfo = ref Client.Game.Arts.GetArt(item.DisplayedGraphic); - - var rect = Client.Game.Arts.GetRealArtBounds(item.DisplayedGraphic); - - hueVector = ShaderHueTranslator.GetHueVector( - item.Hue, - item.ItemData.IsPartialHue, - 1f - ); - - Point originalSize = new Point(_hit.Width, _hit.Height); - Point point = new Point(); - - if (rect.Width < _hit.Width) - { - originalSize.X = rect.Width; - point.X = (_hit.Width >> 1) - (originalSize.X >> 1); - } - - if (rect.Height < _hit.Height) - { - originalSize.Y = rect.Height; - point.Y = (_hit.Height >> 1) - (originalSize.Y >> 1); - } - - batcher.Draw( - artInfo.Texture, - new Rectangle( - x + point.X, - y + point.Y + _hit.Y, - originalSize.X, - originalSize.Y - ), - new Rectangle( - artInfo.UV.X + rect.X, - artInfo.UV.Y + rect.Y, - rect.Width, - rect.Height - ), - hueVector - ); - } - - hueVector = ShaderHueTranslator.GetHueVector(0); - - batcher.DrawRectangle( - SolidColorTextureCache.GetTexture(Color.Gray), - x, - y + 15, - Width, - Height - 15, - hueVector - ); - - if (_hit.MouseIsOver) - { - hueVector.Z = 0.7f; - - batcher.Draw( - SolidColorTextureCache.GetTexture(Color.Yellow), - new Rectangle(x + 1, y + 15, Width - 1, Height - 15), - hueVector - ); - - hueVector.Z = 1; - } - - return true; - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/Gump.cs b/src/ClassicUO.Client/Game/UI/Gumps/Gump.cs deleted file mode 100644 index 261f3f512..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/Gump.cs +++ /dev/null @@ -1,302 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Xml; -using ClassicUO.Configuration; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - public class Gump : Control - { - private bool isLocked = false; - - public Gump(uint local, uint server) - { - LocalSerial = local; - ServerSerial = server; - AcceptMouseInput = false; - AcceptKeyboardInput = false; - } - - public bool CanBeSaved => GumpType != Gumps.GumpType.None || ServerSerial != 0; - - public virtual GumpType GumpType { get; } - - public bool InvalidateContents { get; set; } - - public uint MasterGumpSerial { get; set; } - - public float AlphaOffset = 0; - - protected override void OnMouseWheel(MouseEventType delta) - { - base.OnMouseWheel(delta); - - if (Keyboard.Alt && ProfileManager.CurrentProfile.EnableAlphaScrollingOnGumps) - { - if (delta == MouseEventType.WheelScrollUp && Alpha < 0.99) - { - AlphaOffset += 0.02f; - Alpha += 0.02f; - foreach (Control c in Children) - { - c.Alpha += 0.02f; - if (c.Alpha > 1) c.Alpha = 1; - } - } - else if(Alpha > 0.1) - { - AlphaOffset -= 0.02f; - Alpha -= 0.02f; - foreach (Control c in Children) - c.Alpha -= 0.02f; - } - } - } - - public virtual bool IsLocked - { - get { return isLocked; } - set - { - isLocked = value; - if (isLocked) - { - CanMove = false; - CanCloseWithRightClick = false; - } - else - { - CanMove = true; - CanCloseWithRightClick = true; - } - } - } - - public bool CanBeLocked { get; set; } = true; - - public override void Update() - { - if (InvalidateContents) - { - UpdateContents(); - InvalidateContents = false; - } - - if (ActivePage == 0) - { - ActivePage = 1; - } - - base.Update(); - } - - public override void Dispose() - { - Item it = World.Items.Get(LocalSerial); - - if (it != null && it.Opened) - { - it.Opened = false; - } - - base.Dispose(); - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - base.OnMouseUp(x, y, button); - if (CanBeLocked && Keyboard.Ctrl && Keyboard.Alt && UIManager.MouseOverControl != null && (UIManager.MouseOverControl == this || UIManager.MouseOverControl.RootParent == this)) - { - IsLocked ^= true; - } - } - - public virtual void Save(XmlTextWriter writer) - { - writer.WriteAttributeString("type", ((int)GumpType).ToString()); - writer.WriteAttributeString("x", X.ToString()); - writer.WriteAttributeString("y", Y.ToString()); - writer.WriteAttributeString("serial", LocalSerial.ToString()); - writer.WriteAttributeString("serverSerial", ServerSerial.ToString()); - writer.WriteAttributeString("isLocked", isLocked.ToString()); - writer.WriteAttributeString("alphaOffset", AlphaOffset.ToString()); - } - - public void SetInScreen() - { - Rectangle windowBounds = Client.Game.Window.ClientBounds; - Rectangle bounds = Bounds; - bounds.X += windowBounds.X; - bounds.Y += windowBounds.Y; - - if (windowBounds.Intersects(bounds)) - { - return; - } - - X = 0; - Y = 0; - } - - public virtual void Restore(XmlElement xml) - { - if (bool.TryParse(xml.GetAttribute("isLocked"), out bool lockedStatus)) - IsLocked = lockedStatus; - if (float.TryParse(xml.GetAttribute("alphaOffset"), out float alpha)) - { - AlphaOffset = alpha; - Alpha += alpha; - foreach (Control c in Children) - c.Alpha += alpha; - } - } - - public void RequestUpdateContents() - { - InvalidateContents = true; - } - - protected virtual void UpdateContents() - { - } - - protected override void OnDragEnd(int x, int y) - { - Point position = Location; - int halfWidth = Width - (Width >> 2); - int halfHeight = Height - (Height >> 2); - - if (X < -halfWidth) - { - position.X = -halfWidth; - } - - if (Y < -halfHeight) - { - position.Y = -halfHeight; - } - - if (X > Client.Game.Window.ClientBounds.Width - (Width - halfWidth)) - { - position.X = Client.Game.Window.ClientBounds.Width - (Width - halfWidth); - } - - if (Y > Client.Game.Window.ClientBounds.Height - (Height - halfHeight)) - { - position.Y = Client.Game.Window.ClientBounds.Height - (Height - halfHeight); - } - - Location = position; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - return IsVisible && base.Draw(batcher, x, y); - } - - public override void OnButtonClick(int buttonID) - { - if (!IsDisposed && LocalSerial != 0) - { - List switches = new List(); - List> entries = new List>(); - - foreach (Control control in Children) - { - switch (control) - { - case Checkbox checkbox when checkbox.IsChecked: - switches.Add(control.LocalSerial); - - break; - - case StbTextBox textBox: - entries.Add(new Tuple((ushort)textBox.LocalSerial, textBox.Text)); - - break; - } - } - - GameActions.ReplyGump - ( - LocalSerial, - // Seems like MasterGump serial does not work as expected. - /*MasterGumpSerial != 0 ? MasterGumpSerial :*/ ServerSerial, - buttonID, - switches.ToArray(), - entries.ToArray() - ); - - if (CanMove) - { - UIManager.SavePosition(ServerSerial, Location); - } - else - { - UIManager.RemovePosition(ServerSerial); - } - - Dispose(); - } - } - - protected override void CloseWithRightClick() - { - if (!CanCloseWithRightClick) - { - return; - } - - if (ServerSerial != 0) - { - OnButtonClick(0); - } - - base.CloseWithRightClick(); - } - - public override void ChangePage(int pageIndex) - { - // For a gump, Page is the page that is drawing. - ActivePage = pageIndex; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/GumpType.cs b/src/ClassicUO.Client/Game/UI/Gumps/GumpType.cs deleted file mode 100644 index aa9135e3a..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/GumpType.cs +++ /dev/null @@ -1,66 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -namespace ClassicUO.Game.UI.Gumps -{ - public enum GumpType - { - None, - - Buff, - Container, - CounterBar, - HealthBar, - InfoBar, - Journal, - MacroButton, - MiniMap, - PaperDoll, - SkillMenu, - SpellBook, - StatusGump, - TipNotice, - AbilityButton, - SpellButton, - SkillButton, - RacialButton, - WorldMap, - - Debug, - NetStats, - - NameOverHeadHandler, - MacroButtonEditor = 6464, - DurabilityGump = 6465, - GridContainer = 8787 - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/HealthBarGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/HealthBarGump.cs deleted file mode 100644 index ad477f3ee..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/HealthBarGump.cs +++ /dev/null @@ -1,2169 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Xml; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using SDL2; -using System.Text.Json.Serialization; - -namespace ClassicUO.Game.UI.Gumps -{ - internal abstract class BaseHealthBarGump : AnchorableGump - { - private bool _targetBroke; - - public bool IsLastAttackBar { get; set; } = false; - public static BaseHealthBarGump LastAttackBar { get; set; } - - protected BaseHealthBarGump(Entity entity) : this(0, 0) - { - if (entity == null || entity.IsDestroyed) - { - Dispose(); - - return; - } - - GameActions.RequestMobileStatus(entity.Serial, true); - LocalSerial = entity.Serial; - CanCloseWithRightClick = true; - _name = entity.Name; - _isDead = entity is Mobile mm && mm.IsDead; - - BuildGump(); - } - - public virtual void SetNewMobile(uint serial) - { - if (World.Mobiles.TryGetValue(serial, out Mobile m)) - { - LocalSerial = serial; - _name = m.Name; - _isDead = m.IsDead; - - Children.Clear(); - BuildGump(); - } - } - - protected BaseHealthBarGump(uint serial) : this(World.Get(serial)) - { - } - - protected BaseHealthBarGump(uint local, uint server) : base(local, server) - { - CanMove = true; - AnchorType = ANCHOR_TYPE.HEALTHBAR; - } - - public override int GroupMatrixWidth - { - get => Width; - protected set { } - } - - public override int GroupMatrixHeight - { - get => Height; - protected set { } - } - - public override GumpType GumpType => GumpType.HealthBar; - internal bool IsInactive => (_isDead || _outOfRange) && !_canChangeName; - protected bool _canChangeName; - protected bool _isDead; - protected string _name; - protected bool _outOfRange; - protected StbTextBox _textBox; - - public bool IsLastTarget { get; set; } = false; - - private bool _locked = false; - private bool IsLocked - { - get { return _locked; } - set - { - _locked = value; - if (_locked) - { - CanMove = false; - CanCloseWithRightClick = false; - } - else - { - CanMove = true; - CanCloseWithRightClick = true; - } - } - } - - protected abstract void BuildGump(); - - - public override void Dispose() - { - /*if (TargetManager.LastAttack != LocalSerial) - { - GameActions.SendCloseStatus(LocalSerial); - }*/ - - if (IsLastTarget && ProfileManager.CurrentProfile != null) - ProfileManager.CurrentProfile.LastTargetHealthBarPos = Location; - - _textBox?.Dispose(); - _textBox = null; - base.Dispose(); - } - - public override void Save(XmlTextWriter writer) - { - base.Save(writer); - - if (ProfileManager.CurrentProfile.SaveHealthbars) - { - writer.WriteAttributeString("name", _name); - writer.WriteAttributeString("locked", IsLocked.ToString()); - writer.WriteAttributeString("lastAttackSingle", IsLastAttackBar.ToString()); - } - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - - if (LocalSerial == World.Player) - { - _name = World.Player.Name; - BuildGump(); - } - else if (ProfileManager.CurrentProfile.SaveHealthbars) - { - _name = xml.GetAttribute("name"); - if (bool.TryParse(xml.GetAttribute("locked"), out bool locked)) - { - IsLocked = locked; - } - - if (bool.TryParse(xml.GetAttribute("lastAttackSingle"), out bool lastAttack)) - { - if (lastAttack) - { - LastAttackBar = this; - IsLastAttackBar = lastAttack; - } - } - - _outOfRange = true; - BuildGump(); - } - else - { - Dispose(); - } - } - - protected void TextBoxOnMouseUp(object sender, MouseEventArgs e) - { - if (e.Button != MouseButtonType.Left) - { - return; - } - - if (World.Get(LocalSerial) == null) - { - return; - } - - Point p = Mouse.LDragOffset; - - if (Math.Max(Math.Abs(p.X), Math.Abs(p.Y)) >= 1) - { - return; - } - - if (TargetManager.IsTargeting) - { - TargetManager.Target(LocalSerial); - Mouse.LastLeftButtonClickTime = 0; - } - else if (_canChangeName && !_targetBroke) - { - _textBox.IsEditable = true; - _textBox.SetKeyboardFocus(); - } - - _targetBroke = false; - } - - protected static int CalculatePercents(int max, int current, int maxValue) - { - if (max > 0) - { - max = current * 100 / max; - - if (max > 100) - { - max = 100; - } - - if (max > 1) - { - max = maxValue * max / 100; - } - } - - return max; - } - - protected override void OnDragEnd(int x, int y) - { - // when dragging an healthbar with target on, we have to reset the dclick timer - if (TargetManager.IsTargeting) - { - Mouse.LastLeftButtonClickTime = 0; - Mouse.CancelDoubleClick = true; - } - - base.OnDragEnd(x, y); - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - base.OnMouseUp(x, y, button); - - if (button == MouseButtonType.Left && Keyboard.Alt) - { - if (UIManager.MouseOverControl != null && (UIManager.MouseOverControl == this || UIManager.MouseOverControl.RootParent == this)) - { - ref readonly var texture = ref Client.Game.Gumps.GetGump(0x82C); - if (texture.Texture != null) - { - if (x >= 0 && x < texture.UV.Width && y >= 0 && y <= texture.UV.Height) - { - IsLocked = !IsLocked; - return; - } - } - } - - MessageManager.HandleMessage - ( - World.Player, - ResGeneral.NowFollowing, - string.Empty, - 0, - MessageType.Regular, - 3, - TextType.CLIENT - ); - ProfileManager.CurrentProfile.FollowingMode = true; - ProfileManager.CurrentProfile.FollowingTarget = LocalSerial; - } - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - if (button != MouseButtonType.Left) - { - return; - } - - if (TargetManager.IsTargeting) - { - _targetBroke = true; - TargetManager.Target(LocalSerial); - Mouse.LastLeftButtonClickTime = 0; - } - else if (_canChangeName) - { - if (_textBox != null) - { - _textBox.IsEditable = false; - } - - UIManager.KeyboardFocusControl = null; - UIManager.SystemChat?.SetFocus(); - } - - base.OnMouseDown(x, y, button); - } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if (button != MouseButtonType.Left) - { - return false; - } - - if (_canChangeName) - { - if (_textBox != null) - { - _textBox.IsEditable = false; - } - - UIManager.KeyboardFocusControl = null; - UIManager.SystemChat?.SetFocus(); - } - - Entity entity = World.Get(LocalSerial); - - if (entity != null) - { - if (entity != World.Player) - { - if (World.Player.InWarMode) - { - GameActions.Attack(entity); - } - else if (!GameActions.OpenCorpse(entity)) - { - GameActions.DoubleClick(entity); - } - } - else - { - if (StatusGumpBase.GetStatusGump() == null) - UIManager.Add(StatusGumpBase.AddStatusGump(ProfileManager.CurrentProfile.StatusGumpPosition.X, ProfileManager.CurrentProfile.StatusGumpPosition.Y)); - } - } - - return true; - } - - protected override void OnKeyDown(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - Entity entity = World.Get(LocalSerial); - - if (entity == null || SerialHelper.IsItem(entity.Serial)) - { - return; - } - - if ((key == SDL.SDL_Keycode.SDLK_RETURN || key == SDL.SDL_Keycode.SDLK_KP_ENTER) && _textBox != null && _textBox.IsEditable) - { - GameActions.Rename(entity, _textBox.Text); - UIManager.KeyboardFocusControl = null; - UIManager.SystemChat?.SetFocus(); - _textBox.IsEditable = false; - } - } - - protected override void OnMouseOver(int x, int y) - { - Entity entity = World.Get(LocalSerial); - - if (entity != null) - { - SelectedObject.HealthbarObject = entity; - SelectedObject.Object = entity; - } - - base.OnMouseOver(x, y); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - if (Keyboard.Alt && UIManager.MouseOverControl != null && (UIManager.MouseOverControl == this || UIManager.MouseOverControl.RootParent == this)) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - ref readonly var texture = ref Client.Game.Gumps.GetGump(0x82C); - - if (texture.Texture != null) - { - if (IsLocked) - { - hueVector.X = 34; - hueVector.Y = 1; - } - batcher.Draw - ( - texture.Texture, - new Vector2(x, y), - texture.UV, - hueVector - ); - } - } - - return true; - } - - protected bool CheckIfAnchoredElseDispose() - { - if (IsLocked || IsLastAttackBar) - { - return false; - } - if ((UIManager.AnchorManager[this] == null || ProfileManager.CurrentProfile.CloseHealthBarIfAnchored) && LocalSerial != World.Player) - { - Dispose(); - - return true; - } - - return false; - } - } - - internal class HealthBarGumpCustom : BaseHealthBarGump - { - private static Settings _settings; - private static Settings settings - { - get - { - if (_settings == null) - { - _settings = (Settings)Settings.Load(typeof(HealthBarGumpCustom).ToString()); - if (_settings == null) - { - _settings = new Settings(); - Settings.Save(typeof(HealthBarGumpCustom).ToString(), _settings); - } - return _settings; - } - else - { - return _settings; - } - } - } - - internal static int HPB_WIDTH = settings.Width; - internal static int HPB_HEIGHT_MULTILINE = settings.Height_Multiline; - internal static int HPB_HEIGHT_SINGLELINE = settings.Height_Singleline; - private static int HPB_BORDERSIZE = settings.BorderSize; - private static int HPB_OUTLINESIZE = settings.OutlineSize; - - - internal static int HPB_BAR_WIDTH = settings.HP_Bar_Width; - private static int HPB_BAR_HEIGHT = settings.HP_Bar_Height; - private static int HPB_BAR_SPACELEFT = (HPB_WIDTH - HPB_BAR_WIDTH) / 2; - - - private static Color HPB_COLOR_DRAW_RED = settings.Hue_HP_Lines_Red; - private static Color HPB_COLOR_DRAW_BLUE = settings.Hue_HP_Lines_Blue; - private static Color HPB_COLOR_DRAW_BLACK = settings.Hue_HP_Lines_Black; - - private static readonly Texture2D HPB_COLOR_BLUE = SolidColorTextureCache.GetTexture(settings.Hue_HP_Blue); - private static readonly Texture2D HPB_COLOR_GRAY = SolidColorTextureCache.GetTexture(settings.Hue_HP_Gray); - private static readonly Texture2D HPB_COLOR_RED = SolidColorTextureCache.GetTexture(settings.Hue_HP_Red); - private static readonly Texture2D HPB_COLOR_YELLOW = SolidColorTextureCache.GetTexture(settings.Hue_HP_Yellow); - private static readonly Texture2D HPB_COLOR_POISON = SolidColorTextureCache.GetTexture(settings.Hue_HP_Poison); - private static readonly Texture2D HPB_COLOR_BLACK = SolidColorTextureCache.GetTexture(settings.Hue_HP_Black); - - private readonly LineCHB[] _bars = new LineCHB[3]; - private readonly LineCHB[] _border = new LineCHB[4]; - - private LineCHB _hpLineRed, _manaLineRed, _stamLineRed, _outline; - - - private bool _oldWarMode, _normalHits, _poisoned, _yellowHits; - - public HealthBarGumpCustom(Entity entity) : base(entity) - { - } - - public HealthBarGumpCustom(uint serial) : base(serial) - { - } - - public HealthBarGumpCustom() : base(0, 0) - { - } - - protected AlphaBlendControl _background; - - protected override void UpdateContents() - { - Clear(); - Children.Clear(); - - _background = null; - _hpLineRed = _manaLineRed = _stamLineRed = null; - - if (_textBox != null) - { - _textBox.MouseUp -= TextBoxOnMouseUp; - } - - _textBox = null; - - BuildGump(); - } - - public override void Update() - { - base.Update(); - - if (IsDisposed) - { - return; - } - - bool inparty = World.Party.Contains(LocalSerial); - - - ushort textColor = 0x0386; - - Entity entity = World.Get(LocalSerial); - - if (entity is Item it && it.Layer == 0 && it.Container == World.Player) - { - entity = null; - } - - if (entity == null || entity.IsDestroyed) - { - bool hasCorpse = World.CorpseManager.Exists(0, LocalSerial | 0x8000_0000); - if (LocalSerial != World.Player && (ProfileManager.CurrentProfile.CloseHealthBarType == 1 || ProfileManager.CurrentProfile.CloseHealthBarType == 3) || ((ProfileManager.CurrentProfile.CloseHealthBarType == 2 || ProfileManager.CurrentProfile.CloseHealthBarType == 3) && hasCorpse)) - { - //### KEEPS PARTY BAR ACTIVE WHEN PARTY MEMBER DIES & MOBILEBAR CLOSE SELECTED ###// - if (!inparty && CheckIfAnchoredElseDispose()) - { - return; - } - - //### KEEPS PARTY BAR ACTIVE WHEN PARTY MEMBER DIES & MOBILEBAR CLOSE SELECTED ###// - } - - if (_isDead) - { - _isDead = false; - } - - if (!_outOfRange) - { - _outOfRange = true; - textColor = 912; - - if (TargetManager.LastAttack != LocalSerial) - { - GameActions.SendCloseStatus(LocalSerial); - } - - if (inparty) - { - if (_textBox != null && _textBox.Hue != textColor) - { - _textBox.Hue = textColor; - } - - if (_bars.Length >= 2 && _bars[1] != null) - { - _bars[1].IsVisible = false; - - _bars[2].IsVisible = false; - } - } - else - { - if (_textBox != null) - { - if (_textBox.Hue != textColor) - { - _textBox.Hue = textColor; - } - - _textBox.IsEditable = false; - } - } - - if (_background.Hue != 912) - { - _background.Hue = 912; - } - - if (_hpLineRed.LineColor != HPB_COLOR_GRAY) - { - _hpLineRed.LineColor = HPB_COLOR_GRAY; - - _border[0].LineColor = _border[1].LineColor = _border[2].LineColor = _border[3].LineColor = HPB_COLOR_BLACK; - - if (_manaLineRed != null && _stamLineRed != null) - { - _manaLineRed.LineColor = _stamLineRed.LineColor = HPB_COLOR_GRAY; - } - } - - _bars[0].IsVisible = false; - } - } - - if (entity != null && !entity.IsDestroyed) - { - _hpLineRed.IsVisible = entity.HitsMax > 0; - - Mobile mobile = entity as Mobile; - - if (!_isDead && entity != World.Player && mobile != null && mobile.IsDead && (ProfileManager.CurrentProfile.CloseHealthBarType == 2 || ProfileManager.CurrentProfile.CloseHealthBarType == 3)) // is dead - { - if (!inparty && CheckIfAnchoredElseDispose()) - { - return; - } - } - - if (entity is Mobile mm && _canChangeName != mm.IsRenamable) - { - _canChangeName = mm.IsRenamable; - - if (_textBox != null) - { - _textBox.AcceptMouseInput = _canChangeName; - _textBox.AcceptKeyboardInput = _canChangeName; - - if (!_canChangeName) - { - _textBox.IsEditable = false; - } - } - } - - if (!(mobile != null && mobile.IsDead) && _isDead) - { - _isDead = false; - } - - if (!string.IsNullOrEmpty(entity.Name) && _name != entity.Name) - { - _name = entity.Name; - - if (_textBox != null) - { - _textBox.SetText(_name); - } - } - - if (_outOfRange) - { - if (entity.HitsMax == 0) - { - GameActions.RequestMobileStatus(entity); - } - - _outOfRange = false; - - - _canChangeName = mobile != null && mobile.IsRenamable; - - if (_canChangeName) - { - textColor = 0x000E; - } - - if (inparty && _bars.Length >= 2 && _bars[1] != null) - { - _bars[1].IsVisible = true; - - _bars[2].IsVisible = true; - } - - if (_hpLineRed.LineColor != HPB_COLOR_RED) - { - _hpLineRed.LineColor = HPB_COLOR_RED; - - _border[0].LineColor = _border[1].LineColor = _border[2].LineColor = _border[3].LineColor = HPB_COLOR_BLACK; - - if (_manaLineRed != null && _stamLineRed != null) - { - _manaLineRed.LineColor = _stamLineRed.LineColor = HPB_COLOR_RED; - } - } - - _bars[0].IsVisible = true; - } - - if (mobile != null && mobile != World.Player) - if (TargetManager.LastTargetInfo.Serial != World.Player && !_outOfRange) - { - int tDistance = mobile.Distance; - if (mobile == TargetManager.LastTargetInfo.Serial) - { - _border[0].LineColor = HPB_COLOR_RED; - _border[0].Hue = 0; - if (tDistance < 15 && mobile != World.Player) - { - _border[0].LineColor = HPB_COLOR_YELLOW; - _border[0].Hue = 42; - if (tDistance < 10) - { - _border[0].Hue = 52; - if (tDistance < 5) - { - _border[0].Hue = 67; - } - } - } - - if (_border.Length >= 3) - { - _border[1].LineColor = _border[2].LineColor = _border[3].LineColor = HPB_COLOR_RED; - } - } - else if (mobile != TargetManager.LastTargetInfo.Serial) - { - _border[0].LineColor = HPB_COLOR_BLACK; - _border[0].Hue = 0; - if (tDistance < 15 && mobile != World.Player) - { - _border[0].LineColor = HPB_COLOR_YELLOW; - _border[0].Hue = 42; - if (tDistance < 10) - { - _border[0].Hue = 52; - if (tDistance < 5) - { - _border[0].Hue = 67; - } - } - } - - if (_border.Length >= 3) - { - _border[1].LineColor = _border[2].LineColor = _border[3].LineColor = HPB_COLOR_BLACK; - } - } - } - - if (mobile != null) - { - textColor = Notoriety.GetHue(mobile.NotorietyFlag); - } - - if (_textBox != null && _textBox.Hue != textColor) - { - _textBox.Hue = textColor; - } - - ushort barColor = mobile != null ? Notoriety.GetHue(mobile.NotorietyFlag) : (ushort)912; - - if (_background.Hue != barColor) - { - if (mobile != null && mobile.IsDead) - { - _background.Hue = 912; - } - else if (!ProfileManager.CurrentProfile.CBBlackBGToggled) - { - _background.Hue = barColor; - } - } - - if (mobile != null && mobile.IsDead || ProfileManager.CurrentProfile.CBBlackBGToggled) - { - if (_background.Hue != 912) - { - _background.Hue = 912; - } - } - - - if (mobile != null) - { - if (mobile.IsPoisoned && !_poisoned) - { - _bars[0].LineColor = HPB_COLOR_POISON; - - _poisoned = true; - _normalHits = false; - } - else if (mobile.IsYellowHits && !_yellowHits) - { - _bars[0].LineColor = HPB_COLOR_YELLOW; - - _yellowHits = true; - _normalHits = false; - } - else if (!_normalHits && !mobile.IsPoisoned && !mobile.IsYellowHits && (_poisoned || _yellowHits)) - { - _bars[0].LineColor = HPB_COLOR_BLUE; - - _poisoned = false; - _yellowHits = false; - _normalHits = true; - } - } - - - int hits = CalculatePercents(entity.HitsMax, entity.Hits, HPB_BAR_WIDTH); - - if (hits != _bars[0].LineWidth) - { - _bars[0].LineWidth = hits; - } - - if ((inparty || LocalSerial == World.Player) && mobile != null && _bars != null) - { - int mana = CalculatePercents(mobile.ManaMax, mobile.Mana, HPB_BAR_WIDTH); - int stam = CalculatePercents(mobile.StaminaMax, mobile.Stamina, HPB_BAR_WIDTH); - - if (_bars.Length >= 2 && _bars[1] != null && mana != _bars[1].LineWidth) - { - _bars[1].LineWidth = mana; - } - - if (_bars.Length >= 2 && _bars[2] != null && stam != _bars[2].LineWidth) - { - _bars[2].LineWidth = stam; - } - } - - if (UIManager.MouseOverControl != null && UIManager.MouseOverControl.RootParent == this) - { - SelectedObject.HealthbarObject = entity; - SelectedObject.Object = entity; - } - } - - if (LocalSerial == World.Player) - { - if (World.Player.InWarMode != _oldWarMode) - { - _oldWarMode = !_oldWarMode; - - if (World.Player.InWarMode) - { - _border[0].LineColor = HPB_COLOR_RED; - - if (_border.Length >= 3) - { - _border[1].LineColor = _border[2].LineColor = _border[3].LineColor = HPB_COLOR_RED; - } - } - else - { - _border[0].LineColor = HPB_COLOR_BLACK; - - if (_border.Length >= 3) - { - _border[1].LineColor = _border[2].LineColor = _border[3].LineColor = HPB_COLOR_BLACK; - } - } - } - } - } - - protected override void BuildGump() - { - WantUpdateSize = false; - - Entity entity = World.Get(LocalSerial); - - - if (World.Party.Contains(LocalSerial)) - { - Height = HPB_HEIGHT_MULTILINE; - Width = HPB_WIDTH; - - Add(_background = new AlphaBlendControl(0.7f) { Width = Width, Height = Height, AcceptMouseInput = true, CanMove = true }); - - - if (LocalSerial == World.Player) - { - Add - ( - _textBox = new StbTextBox - ( - 1, - 32, - HPB_WIDTH, - true, - FontStyle.Cropped | FontStyle.BlackBorder, - Notoriety.GetHue(World.Player.NotorietyFlag), - TEXT_ALIGN_TYPE.TS_CENTER - ) - { - X = 0, - Y = 3, - Width = HPB_BAR_WIDTH, - IsEditable = false, - CanMove = true - } - ); - } - else - { - Add - ( - _textBox = new StbTextBox - ( - 1, - 32, - HPB_WIDTH, - true, - FontStyle.Cropped | FontStyle.BlackBorder, - Notoriety.GetHue((entity as Mobile)?.NotorietyFlag ?? NotorietyFlag.Gray), - TEXT_ALIGN_TYPE.TS_CENTER - ) - { - X = 0, - Y = 3, - Width = HPB_BAR_WIDTH, - IsEditable = false, - CanMove = true - } - ); - } - - Add - ( - _outline = new LineCHB - ( - HPB_BAR_SPACELEFT - HPB_OUTLINESIZE, - 27 - HPB_OUTLINESIZE, - HPB_BAR_WIDTH + HPB_OUTLINESIZE * 2, - HPB_BAR_HEIGHT * 3 + 2 + HPB_OUTLINESIZE * 2, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - - Add - ( - _hpLineRed = new LineCHB - ( - HPB_BAR_SPACELEFT, - 27, - HPB_BAR_WIDTH, - HPB_BAR_HEIGHT, - HPB_COLOR_DRAW_RED.PackedValue - ) - ); - - Add - ( - _manaLineRed = new LineCHB - ( - HPB_BAR_SPACELEFT, - 36, - HPB_BAR_WIDTH, - HPB_BAR_HEIGHT, - HPB_COLOR_DRAW_RED.PackedValue - ) - ); - - Add - ( - _stamLineRed = new LineCHB - ( - HPB_BAR_SPACELEFT, - 45, - HPB_BAR_WIDTH, - HPB_BAR_HEIGHT, - HPB_COLOR_DRAW_RED.PackedValue - ) - ); - - Add - ( - _bars[0] = new LineCHB - ( - HPB_BAR_SPACELEFT, - 27, - HPB_BAR_WIDTH, - HPB_BAR_HEIGHT, - HPB_COLOR_DRAW_BLUE.PackedValue - ) - { LineWidth = 0 } - ); - - Add - ( - _bars[1] = new LineCHB - ( - HPB_BAR_SPACELEFT, - 36, - HPB_BAR_WIDTH, - HPB_BAR_HEIGHT, - HPB_COLOR_DRAW_BLUE.PackedValue - ) - { LineWidth = 0 } - ); - - Add - ( - _bars[2] = new LineCHB - ( - HPB_BAR_SPACELEFT, - 45, - HPB_BAR_WIDTH, - HPB_BAR_HEIGHT, - HPB_COLOR_DRAW_BLUE.PackedValue - ) - { LineWidth = 0 } - ); - - Add - ( - _border[0] = new LineCHB - ( - 0, - 0, - HPB_WIDTH, - HPB_BORDERSIZE, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - - Add - ( - _border[1] = new LineCHB - ( - 0, - HPB_HEIGHT_MULTILINE - HPB_BORDERSIZE, - HPB_WIDTH, - HPB_BORDERSIZE, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - - Add - ( - _border[2] = new LineCHB - ( - 0, - 0, - HPB_BORDERSIZE, - HPB_HEIGHT_MULTILINE, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - - Add - ( - _border[3] = new LineCHB - ( - HPB_WIDTH - HPB_BORDERSIZE, - 0, - HPB_BORDERSIZE, - HPB_HEIGHT_MULTILINE, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - } - else - { - if (LocalSerial == World.Player) - { - _oldWarMode = World.Player.InWarMode; - Height = HPB_HEIGHT_MULTILINE; - Width = HPB_WIDTH; - - Add(_background = new AlphaBlendControl(0.7f) { Width = Width, Height = Height, AcceptMouseInput = true, CanMove = true }); - - Add - ( - _textBox = new StbTextBox - ( - 1, - 32, - isunicode: true, - style: FontStyle.Cropped | FontStyle.BlackBorder, - hue: Notoriety.GetHue((entity as Mobile)?.NotorietyFlag ?? NotorietyFlag.Gray), - maxWidth: Width, - align: TEXT_ALIGN_TYPE.TS_CENTER - ) - { - X = 0, - Y = 3, - Width = HPB_BAR_WIDTH, - IsEditable = false, - CanMove = true - } - ); - - Add - ( - _outline = new LineCHB - ( - HPB_BAR_SPACELEFT - HPB_OUTLINESIZE, - _textBox.Height - HPB_OUTLINESIZE, - HPB_BAR_WIDTH + HPB_OUTLINESIZE * 2, - HPB_BAR_HEIGHT * 3 + 2 + HPB_OUTLINESIZE * 3, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - - Add - ( - _hpLineRed = new LineCHB - ( - HPB_BAR_SPACELEFT, - _outline.Y + HPB_OUTLINESIZE, - HPB_BAR_WIDTH, - HPB_BAR_HEIGHT, - HPB_COLOR_DRAW_RED.PackedValue - ) - ); - Control m, s; - Add - (m = - new LineCHB - ( - HPB_BAR_SPACELEFT, - _hpLineRed.Height + _hpLineRed.Y + HPB_OUTLINESIZE, - HPB_BAR_WIDTH, - HPB_BAR_HEIGHT, - HPB_COLOR_DRAW_RED.PackedValue - ) - ); - - Add - (s = - new LineCHB - ( - HPB_BAR_SPACELEFT, - m.Height + m.Y + HPB_OUTLINESIZE, - HPB_BAR_WIDTH, - HPB_BAR_HEIGHT, - HPB_COLOR_DRAW_RED.PackedValue - ) - ); - - Add - ( - _bars[0] = new LineCHB - ( - HPB_BAR_SPACELEFT, - _hpLineRed.Y, - HPB_BAR_WIDTH, - HPB_BAR_HEIGHT, - HPB_COLOR_DRAW_BLUE.PackedValue - ) - { LineWidth = 0 } - ); - - Add - ( - _bars[1] = new LineCHB - ( - HPB_BAR_SPACELEFT, - m.Y, - HPB_BAR_WIDTH, - HPB_BAR_HEIGHT, - HPB_COLOR_DRAW_BLUE.PackedValue - ) - { LineWidth = 0 } - ); - - Add - ( - _bars[2] = new LineCHB - ( - HPB_BAR_SPACELEFT, - s.Y, - HPB_BAR_WIDTH, - HPB_BAR_HEIGHT, - HPB_COLOR_DRAW_BLUE.PackedValue - ) - { LineWidth = 0 } - ); - - Add - ( - _border[0] = new LineCHB - ( - 0, - 0, - HPB_WIDTH, - HPB_BORDERSIZE, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - - Add - ( - _border[1] = new LineCHB - ( - 0, - HPB_HEIGHT_MULTILINE - HPB_BORDERSIZE, - HPB_WIDTH, - HPB_BORDERSIZE, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - - Add - ( - _border[2] = new LineCHB - ( - 0, - 0, - HPB_BORDERSIZE, - HPB_HEIGHT_MULTILINE, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - - Add - ( - _border[3] = new LineCHB - ( - HPB_WIDTH - HPB_BORDERSIZE, - 0, - HPB_BORDERSIZE, - HPB_HEIGHT_MULTILINE, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - - _border[0].LineColor = _border[1].LineColor = _border[2].LineColor = _border[3].LineColor = _oldWarMode ? HPB_COLOR_RED : HPB_COLOR_BLACK; - } - else - { - Mobile mobile = entity as Mobile; - - if (entity != null) - { - _canChangeName = mobile != null && mobile.IsRenamable; - } - - Height = HPB_HEIGHT_SINGLELINE; - Width = HPB_WIDTH; - - Add(_background = new AlphaBlendControl(0.7f) { Width = Width, Height = Height, AcceptMouseInput = true, CanMove = true }); - - Add - ( - _outline = new LineCHB - ( - HPB_BAR_SPACELEFT - HPB_OUTLINESIZE, - 21 - HPB_OUTLINESIZE, - HPB_BAR_WIDTH + HPB_OUTLINESIZE * 2, - HPB_BAR_HEIGHT + HPB_OUTLINESIZE * 2, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - - Add - ( - _hpLineRed = new LineCHB - ( - HPB_BAR_SPACELEFT, - 21, - HPB_BAR_WIDTH, - HPB_BAR_HEIGHT, - HPB_COLOR_DRAW_RED.PackedValue - ) - ); - - Add - ( - _bars[0] = new LineCHB - ( - HPB_BAR_SPACELEFT, - 21, - HPB_BAR_WIDTH, - HPB_BAR_HEIGHT, - HPB_COLOR_DRAW_BLUE.PackedValue - ) - { LineWidth = 0 } - ); - - Add - ( - _border[0] = new LineCHB - ( - 0, - 0, - HPB_WIDTH, - HPB_BORDERSIZE, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - - Add - ( - _border[1] = new LineCHB - ( - 0, - HPB_HEIGHT_SINGLELINE - HPB_BORDERSIZE, - HPB_WIDTH, - HPB_BORDERSIZE, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - - Add - ( - _border[2] = new LineCHB - ( - 0, - 0, - HPB_BORDERSIZE, - HPB_HEIGHT_SINGLELINE, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - - Add - ( - _border[3] = new LineCHB - ( - HPB_WIDTH - HPB_BORDERSIZE, - 0, - HPB_BORDERSIZE, - HPB_HEIGHT_SINGLELINE, - HPB_COLOR_DRAW_BLACK.PackedValue - ) - ); - - - Add - ( - _textBox = new StbTextBox - ( - 1, - 32, - HPB_WIDTH, - true, - hue: Notoriety.GetHue((entity as Mobile)?.NotorietyFlag ?? NotorietyFlag.Gray), - style: FontStyle.Cropped | FontStyle.BlackBorder, - align: TEXT_ALIGN_TYPE.TS_CENTER - ) - { - X = 0, - Y = 0, - Width = HPB_WIDTH, - Height = 15, - IsEditable = false, - AcceptMouseInput = _canChangeName, - AcceptKeyboardInput = _canChangeName, - WantUpdateSize = false, - CanMove = true - } - ); - } - } - - _textBox.MouseUp += TextBoxOnMouseUp; - _textBox.SetText(_name); - - if (entity == null) - { - _textBox.Hue = _background.Hue = 912; - - if (_hpLineRed.LineColor != HPB_COLOR_GRAY) - { - _hpLineRed.LineColor = HPB_COLOR_GRAY; - - _border[0].LineColor = _border[1].LineColor = _border[2].LineColor = _border[3].LineColor = HPB_COLOR_BLACK; - - if (_manaLineRed != null && _stamLineRed != null) - { - _manaLineRed.LineColor = _stamLineRed.LineColor = HPB_COLOR_GRAY; - } - } - } - } - - public override bool Contains(int x, int y) - { - return true; - } - - private class LineCHB : Line - { - public int Hue = 0; - public LineCHB(int x, int y, int w, int h, uint color) : base - ( - x, - y, - w, - h, - color - ) - { - LineWidth = w; - - LineColor = SolidColorTextureCache.GetTexture(new Color { PackedValue = color }); - - CanMove = true; - } - - public int LineWidth { get; set; } - public Texture2D LineColor { get; set; } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(Hue, false, Alpha); - - batcher.Draw - ( - LineColor, - new Rectangle - ( - x, - y, - LineWidth, - Height - ), - hueVector - ); - - return true; - } - } - - #region Health Bar Gump Custom - - // Health Bar Gump Custom v.1c by Syrupz(Alan) - // - // The goal of this was to simply modernize the Health Bar Gumps while still giving people - // an option to continue using the classic Health Bar Gumps. The option to overide bar types - // be it (straight line(custom) or graphic(classic) is directly included in this version - // with no need to change art files in UO directory. - // - // Please report any problems with this to Alan#0084 on Discord and I will promptly work on fixing said issues. - // - // Lastly, I want to give a special thanks to Gaechti for helping me stress test this - // and helping me work and organizing this in a timely fashion to get this released. - // I would like to also thank KaRaShO, Roxya, Stalli, and Link for their input, tips, - // and advice to approach certain challenges that arose throughout development. - // in different manners to get these Health Bars to function per my own vision; gratitude. - // - // Health Bar Gump Custom v.1c by Syrupz(Alan) - - #endregion - - private class Settings : UISettings - { - [JsonConverter(typeof(ColorJsonConverter))] - public Color Hue_HP_Blue { get; set; } = Color.DodgerBlue; - [JsonConverter(typeof(ColorJsonConverter))] - public Color Hue_HP_Gray { get; set; } = Color.Gray; - [JsonConverter(typeof(ColorJsonConverter))] - public Color Hue_HP_Red { get; set; } = Color.Red; - [JsonConverter(typeof(ColorJsonConverter))] - public Color Hue_HP_Yellow { get; set; } = Color.Orange; - [JsonConverter(typeof(ColorJsonConverter))] - public Color Hue_HP_Poison { get; set; } = Color.LimeGreen; - [JsonConverter(typeof(ColorJsonConverter))] - public Color Hue_HP_Black { get; set; } = Color.Black; - - [JsonConverter(typeof(ColorJsonConverter))] - public Color Hue_HP_Lines_Red { get; set; } = Color.Red; - [JsonConverter(typeof(ColorJsonConverter))] - public Color Hue_HP_Lines_Blue { get; set; } = Color.DodgerBlue; - [JsonConverter(typeof(ColorJsonConverter))] - public Color Hue_HP_Lines_Black { get; set; } = Color.Black; - - public int Width { get; set; } = 120; - public int Height_Multiline { get; set; } = 60; - public int Height_Singleline { get; set; } = 36; - public int BorderSize { get; set; } = 1; - public int OutlineSize { get; set; } = 1; - public int HP_Bar_Width { get; set; } = 100; - public int HP_Bar_Height { get; set; } = 8; - } - } - - internal class HealthBarGump : BaseHealthBarGump - { - private static Settings _settings; - private static Settings settings - { - get - { - if (_settings == null) - { - _settings = (Settings)Settings.Load(typeof(HealthBarGump).ToString()); - if (_settings == null) - { - _settings = new Settings(); - Settings.Save(typeof(HealthBarGump).ToString(), _settings); - } - return _settings; - } - else - { - return _settings; - } - } - } - - private GumpPic _background, _hpLineRed, _manaLineRed, _stamLineRed; - - private readonly GumpPicWithWidth[] _bars = new GumpPicWithWidth[3]; - - private Button _buttonHeal1, _buttonHeal2; - private int _oldHits, _oldStam, _oldMana; - - private bool _oldWarMode, _normalHits, _poisoned, _yellowHits; - - - public HealthBarGump(Entity entity) : base(entity) - { - } - - public HealthBarGump(uint serial) : base(serial) - { - } - - public HealthBarGump() : base(0, 0) - { - } - - public override int GroupMatrixWidth - { - get => Width; - protected set { } - } - - public override int GroupMatrixHeight - { - get => Height; - protected set { } - } - - protected override void UpdateContents() - { - Clear(); - Children.Clear(); - - _background = _hpLineRed = _manaLineRed = _stamLineRed = null; - _buttonHeal1 = _buttonHeal2 = null; - - if (_textBox != null) - { - _textBox.MouseUp -= TextBoxOnMouseUp; - } - - _textBox = null; - - BuildGump(); - } - - protected override void BuildGump() - { - WantUpdateSize = false; - - Entity entity = World.Get(LocalSerial); - - if (World.Party.Contains(LocalSerial)) - { - Add - ( - _background = new GumpPic(0, 0, settings.Background_Normal, settings.Hue_Background) - { - ContainsByBounds = true, - Alpha = 0 - } - ); - - Width = 115; - Height = 55; - - if (LocalSerial == World.Player) - { - Add - ( - _textBox = new StbTextBox - ( - 3, - 32, - 120, - false, - FontStyle.Fixed, - Notoriety.GetHue(World.Player.NotorietyFlag) - ) - { - X = 0, - Y = -2, - Width = 120, - Height = 50, - IsEditable = false, - CanMove = true - } - ); - - _name = ResGumps.Self; - } - else - { - Add - ( - _textBox = new StbTextBox - ( - 3, - 32, - 109, - false, - FontStyle.Fixed | FontStyle.BlackBorder, - Notoriety.GetHue((entity as Mobile)?.NotorietyFlag ?? NotorietyFlag.Gray) - ) - { - X = 0, - Y = -2, - Width = 109, - Height = 50, - IsEditable = false, - CanMove = true - } - ); - } - - Add(_buttonHeal1 = new Button((int)ButtonParty.Heal1, 0x0938, 0x093A, 0x0938) { ButtonAction = ButtonAction.Activate, X = 0, Y = 20 }); - - Add(_buttonHeal2 = new Button((int)ButtonParty.Heal2, 0x0939, 0x093A, 0x0939) { ButtonAction = ButtonAction.Activate, X = 0, Y = 33 }); - - Add(_hpLineRed = new GumpPic(18, 20, settings.Line_Red_Party, 0)); - Add(_manaLineRed = new GumpPic(18, 33, settings.Line_Red_Party, 0)); - Add(_stamLineRed = new GumpPic(18, 45, settings.Line_Red_Party, 0)); - - Add - ( - _bars[0] = new GumpPicWithWidth - ( - 18, - 20, - settings.Line_Blue_Party, - settings.Hue_Bar_HP_Foreground_Normal, - 96 - ) - ); - - Add - ( - _bars[1] = new GumpPicWithWidth - ( - 18, - 33, - settings.Line_Blue_Party, - settings.Hue_Bar_Mana_Foreground_Normal, - 96 - ) - ); - - Add - ( - _bars[2] = new GumpPicWithWidth - ( - 18, - 45, - settings.Line_Blue_Party, - settings.Hue_Bar_Stam_Foreground_Normal, - 96 - ) - ); - } - else - { - if (LocalSerial == World.Player) - { - _oldWarMode = World.Player.InWarMode; - - Add(_background = new GumpPic(0, 0, _oldWarMode ? settings.Background_War : settings.Background_Normal, 0) { ContainsByBounds = true }); - - Width = _background.Width; - Height = _background.Height; - - // add backgrounds - Add(_hpLineRed = new GumpPic(34, 12, settings.Line_Red, 0)); - Add(new GumpPic(34, 25, settings.Line_Red, 0)); - Add(new GumpPic(34, 38, settings.Line_Red, 0)); - - // add over - Add - ( - _bars[0] = new GumpPicWithWidth - ( - 34, - 12, - settings.Line_Blue, - settings.Hue_Bar_HP_Foreground_Normal, - 0 - ) - ); - - Add - ( - _bars[1] = new GumpPicWithWidth - ( - 34, - 25, - settings.Line_Blue, - settings.Hue_Bar_Mana_Foreground_Normal, - 0 - ) - ); - - Add - ( - _bars[2] = new GumpPicWithWidth - ( - 34, - 38, - settings.Line_Blue, - settings.Hue_Bar_Stam_Foreground_Normal, - 0 - ) - ); - } - else - { - ushort textColor = 0x0386; - ushort hitsColor = 0x0386; - - Mobile mobile = entity as Mobile; - - if (entity != null) - { - hitsColor = 0; - _canChangeName = mobile != null && mobile.IsRenamable; - - if (_canChangeName) - { - textColor = 0x000E; - } - } - - ushort barColor = entity == null || entity == World.Player || mobile == null || mobile.NotorietyFlag == NotorietyFlag.Criminal || mobile.NotorietyFlag == NotorietyFlag.Gray ? (ushort)0 : Notoriety.GetHue(mobile.NotorietyFlag); - - Add(_background = new GumpPic(0, 0, 0x0804, barColor) { ContainsByBounds = true }); - Add(_hpLineRed = new GumpPic(34, 38, settings.Line_Red, hitsColor)); - - Add - ( - _bars[0] = new GumpPicWithWidth - ( - 34, - 38, - settings.Line_Blue, - 0, - 0 - ) - ); - - Width = _background.Width; - Height = _background.Height; - - Add - ( - _textBox = new StbTextBox - ( - 1, - 32, - 120, - false, - hue: textColor, - style: FontStyle.Fixed - ) - { - X = 16, - Y = 14, - Width = 120, - Height = 15, - IsEditable = false, - AcceptMouseInput = _canChangeName, - AcceptKeyboardInput = _canChangeName, - WantUpdateSize = false, - CanMove = true - } - ); - } - } - - - if (_textBox != null) - { - _textBox.MouseUp += TextBoxOnMouseUp; - _textBox.SetText(_name); - } - } - - public override void Update() - { - base.Update(); - - if (IsDisposed /* || (_textBox != null && _textBox.IsDisposed)*/) - { - return; - } - - bool inparty = World.Party.Contains(LocalSerial); - - - ushort textColor = settings.Hue_Text; - ushort hitsColor = settings.Hue_HitsBar_Background; - ushort backgroundHue = settings.Background_Normal; - ushort hpForegroundHue = settings.Hue_Bar_HP_Foreground_Normal; - - Entity entity = World.Get(LocalSerial); - - if (entity is Item it && it.Layer == 0 && it.Container == World.Player) - { - entity = null; - } - - if (entity == null || entity.IsDestroyed) - { - bool hasCorpse = World.CorpseManager.Exists(0, LocalSerial | 0x8000_0000); - if (LocalSerial != World.Player && (ProfileManager.CurrentProfile.CloseHealthBarType == 1 || ProfileManager.CurrentProfile.CloseHealthBarType == 3) || ((ProfileManager.CurrentProfile.CloseHealthBarType == 2 || ProfileManager.CurrentProfile.CloseHealthBarType == 3) && hasCorpse)) - { - if (CheckIfAnchoredElseDispose()) - { - return; - } - } - - if (_isDead) - { - _isDead = false; - } - - if (!_outOfRange) - { - _outOfRange = true; - - if (TargetManager.LastAttack != LocalSerial) - { - GameActions.SendCloseStatus(LocalSerial); - } - - if (inparty) - { - hitsColor = settings.Hue_HitsBarInParty; - textColor = settings.Hue_TextInParty; - - if (_textBox != null && _textBox.Hue != textColor) - { - _textBox.Hue = textColor; - } - - _buttonHeal1.IsVisible = _buttonHeal2.IsVisible = false; - - if (_bars.Length >= 2 && _bars[1] != null) - { - _bars[1].IsVisible = false; - - _bars[2].IsVisible = false; - } - } - else - { - if (_textBox != null) - { - if (_textBox.Hue != textColor) - { - _textBox.Hue = textColor; - } - - _textBox.IsEditable = false; - } - } - - _bars[0].IsVisible = false; - } - } - - if (entity != null && !entity.IsDestroyed) - { - _hpLineRed.IsVisible = entity.HitsMax > 0; - - Mobile mobile = entity as Mobile; - - if (!_isDead && entity != World.Player && mobile != null && mobile.IsDead && !inparty && (ProfileManager.CurrentProfile.CloseHealthBarType == 2 || ProfileManager.CurrentProfile.CloseHealthBarType == 3)) // is dead - { - if (CheckIfAnchoredElseDispose()) - { - return; - } - } - - if (entity is Mobile mm && _canChangeName != mm.IsRenamable) - { - _canChangeName = mm.IsRenamable; - - if (_textBox != null) - { - _textBox.AcceptMouseInput = _canChangeName; - _textBox.AcceptKeyboardInput = _canChangeName; - - if (!_canChangeName) - { - _textBox.IsEditable = false; - } - } - } - - if (!(mobile != null && mobile.IsDead) && _isDead) - { - _isDead = false; - } - - if (!string.IsNullOrEmpty(entity.Name) && !(inparty && LocalSerial == World.Player.Serial) && _name != entity.Name) - { - _name = entity.Name; - - if (_textBox != null) - { - _textBox.SetText(_name); - } - } - - if (_outOfRange) - { - if (entity.HitsMax == 0) - { - GameActions.RequestMobileStatus(entity); - } - - _outOfRange = false; - - _canChangeName = !inparty && mobile != null && mobile.IsRenamable; - - hitsColor = settings.Hue_HitsBar_OutOfRange; - - if (inparty) - { - _buttonHeal1.IsVisible = _buttonHeal2.IsVisible = true; - - if (_bars.Length >= 2 && _bars[1] != null) - { - _bars[1].IsVisible = true; - - _bars[2].IsVisible = true; - } - } - _bars[0].IsVisible = true; - } - - if (inparty && mobile != null) - { - textColor = Notoriety.GetHue(mobile.NotorietyFlag); - } - else - { - if (_canChangeName) - { - textColor = settings.Hue_Text_Renamable; - } - } - - backgroundHue = entity == World.Player || mobile == null || mobile.NotorietyFlag == NotorietyFlag.Criminal || mobile.NotorietyFlag == NotorietyFlag.Gray ? (ushort)settings.Hue_Background : Notoriety.GetHue(mobile.NotorietyFlag); - - if (mobile != null && mobile.IsPoisoned && !_poisoned) - { - if (inparty) - { - hpForegroundHue = settings.Hue_Bar_Poisoned_InParty; - } - else - { - hpForegroundHue = settings.Hue_Bar_Poisoned; - _bars[0].Graphic = settings.Line_Poisoned; - } - - _poisoned = true; - _normalHits = false; - } - else if (mobile != null && mobile.IsYellowHits && !_yellowHits) - { - if (inparty) - { - hpForegroundHue = settings.Hue_Bar_Yellow_InParty; - } - else - { - hpForegroundHue = settings.Hue_Bar_Yellow; - _bars[0].Graphic = settings.Line_Yellowhits; - } - - _yellowHits = true; - _normalHits = false; - } - else if (!_normalHits && mobile != null && !mobile.IsPoisoned && !mobile.IsYellowHits && (_poisoned || _yellowHits)) - { - if (inparty) - { - hpForegroundHue = settings.Hue_HitsBarInParty; - } - else - { - hpForegroundHue = settings.Hue_Bar_HP_Foreground_Normal; - _bars[0].Graphic = settings.Line_Blue; - } - - _poisoned = false; - _yellowHits = false; - _normalHits = true; - } - - int barW = inparty ? 96 : 109; - - int hits = CalculatePercents(entity.HitsMax, entity.Hits, barW); - - - if (hits != _oldHits) - { - _bars[0].Percent = hits; - - _oldHits = hits; - } - - - if ((inparty || LocalSerial == World.Player) && mobile != null) - { - int mana = CalculatePercents(mobile.ManaMax, mobile.Mana, barW); - int stam = CalculatePercents(mobile.StaminaMax, mobile.Stamina, barW); - - if (mana != _oldMana && _bars.Length >= 2 && _bars[1] != null) - { - _bars[1].Percent = mana; - - _oldMana = mana; - } - - if (stam != _oldStam && _bars.Length >= 2 && _bars[2] != null) - { - _bars[2].Percent = stam; - - _oldStam = stam; - } - } - - if (UIManager.MouseOverControl != null && UIManager.MouseOverControl.RootParent == this) - { - SelectedObject.HealthbarObject = entity; - SelectedObject.Object = entity; - } - } - - if (LocalSerial == World.Player) - { - if (World.Player.InWarMode != _oldWarMode) - { - _oldWarMode = !_oldWarMode; - - _background.Graphic = World.Player.InWarMode ? settings.Background_War : settings.Background_Normal; - } - } - - - if (_bars.Length > 0 && _bars[0].Hue != hpForegroundHue) //HP Foreground - { - _bars[0].Hue = hpForegroundHue; - } - if (_textBox != null && _textBox.Hue != textColor) - { - _textBox.Hue = textColor; - } - if (_background.Hue != backgroundHue) - { - _background.Hue = backgroundHue; - } - if (_hpLineRed.Hue != hitsColor) - { - _hpLineRed.Hue = hitsColor; - - if (_manaLineRed != null && _stamLineRed != null) - { - _manaLineRed.Hue = _stamLineRed.Hue = hitsColor; - } - } - } - - public override void OnButtonClick(int buttonID) - { - switch ((ButtonParty)buttonID) - { - case ButtonParty.Heal1: - GameActions.CastSpell(29); - World.Party.PartyHealTimer = Time.Ticks + 50; - World.Party.PartyHealTarget = LocalSerial; - - break; - - case ButtonParty.Heal2: - GameActions.CastSpell(11); - World.Party.PartyHealTimer = Time.Ticks + 50; - World.Party.PartyHealTarget = LocalSerial; - - break; - } - - Mouse.CancelDoubleClick = true; - Mouse.LastLeftButtonClickTime = 0; - } - - private enum ButtonParty - { - Heal1, - Heal2 - } - - private class Settings : UISettings - { - public ushort Background_Normal { get; set; } = 0x0803; - public ushort Background_War { get; set; } = 0x0807; - public ushort Line_Red { get; set; } = 0x0805; - public ushort Line_Blue { get; set; } = 0x0806; - public ushort Line_Poisoned { get; set; } = 0x0808; - public ushort Line_Yellowhits { get; set; } = 0x0809; - public ushort Line_Red_Party { get; set; } = 0x0028; - public ushort Line_Blue_Party { get; set; } = 0x0029; - - public ushort Hue_Text { get; set; } = 0x0386; - public ushort Hue_Text_Renamable { get; set; } = 0x000E; - public ushort Hue_HitsBar_Background { get; set; } = 0; - public ushort Hue_TextInParty { get; set; } = 912; - public ushort Hue_HitsBarInParty { get; set; } = 912; - public ushort Hue_HitsBar_OutOfRange { get; set; } = 0; - public ushort Hue_Background { get; set; } = 0; - public ushort Hue_Bar_Poisoned_InParty { get; set; } = 63; - public ushort Hue_Bar_Poisoned { get; set; } = 63; - public ushort Hue_Bar_Yellow_InParty { get; set; } = 353; - public ushort Hue_Bar_Yellow { get; set; } = 353; - public ushort Hue_Bar_HP_Foreground_Normal { get; set; } = 0; - public ushort Hue_Bar_Mana_Foreground_Normal { get; set; } = 0; - public ushort Hue_Bar_Stam_Foreground_Normal { get; set; } = 0; - } - - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/HouseCustomizationGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/HouseCustomizationGump.cs deleted file mode 100644 index e2c0c0bec..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/HouseCustomizationGump.cs +++ /dev/null @@ -1,2148 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Assets; -using ClassicUO.Network; -using ClassicUO.Resources; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class HouseCustomizationGump : Gump - { - private readonly HouseCustomizationManager _customHouseManager; - private readonly DataBox _dataBox; - private readonly DataBox _dataBoxGUI; - private readonly GumpPic _gumpPic; - private readonly Label _textComponents; - private readonly Label _textCost; - private readonly Label _textFixtures; - - public HouseCustomizationGump(uint serial, int x, int y) : base(serial, 0) - { - X = x; - Y = y; - CanMove = true; - AcceptMouseInput = false; - CanCloseWithRightClick = true; - _customHouseManager = new HouseCustomizationManager(serial); - World.CustomHouseManager = _customHouseManager; - - Add(new GumpPicTiled(121, 36, 397, 120, 0x0E14)); - - _dataBox = new DataBox(0, 0, 0, 0) - { - WantUpdateSize = true, - CanMove = false, - AcceptMouseInput = false - }; - - Add(_dataBox); - - Add(new GumpPic(0, 17, 0x55F0, 0)); - - _gumpPic = new GumpPic( - 486, - 17, - (ushort)(_customHouseManager.FloorCount == 4 ? 0x55F2 : 0x55F9), - 0 - ); - Add(_gumpPic); - - Add(new GumpPicTiled(153, 17, 333, 154, 0x55F1)); - - Button button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_WALL, - 0x5654, - 0x5656, - 0x5655 - ) - { - X = 9, - Y = 41, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.Walls); - Add(button); - - button = new Button((int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_DOOR, 0x5657, 0x5659, 0x5658) - { - X = 39, - Y = 40, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.Doors); - Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_FLOOR, - 0x565A, - 0x565C, - 0x565B - ) - { - X = 70, - Y = 40, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.Floors); - Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_STAIR, - 0x565D, - 0x565F, - 0x565E - ) - { - X = 9, - Y = 72, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.Stairs); - Add(button); - - button = new Button((int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_ROOF, 0x5788, 0x578A, 0x5789) - { - X = 39, - Y = 72, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.Roofs); - Add(button); - - button = new Button((int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_MISC, 0x5663, 0x5665, 0x5664) - { - X = 69, - Y = 72, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.Miscellaneous); - Add(button); - - button = new Button((int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_MENU, 0x566C, 0x566E, 0x566D) - { - X = 69, - Y = 100, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.SystemMenu); - Add(button); - - _textComponents = new Label(string.Empty, false, 0x0481, font: 9) - { - X = 82, - Y = 142, - AcceptMouseInput = true - }; - - Add(_textComponents); - - Label text = new Label(":", false, 0x0481, font: 9) { X = 84, Y = 142 }; - - Add(text); - - _textFixtures = new Label(string.Empty, false, 0x0481, font: 9) - { - X = 94, - Y = 142, - AcceptMouseInput = true - }; - - Add(_textFixtures); - - _textCost = new Label(string.Empty, false, 0x0481, font: 9) - { - X = 524, - Y = 142, - AcceptMouseInput = true - }; - - _textCost.SetTooltip(ResGumps.Cost); - Add(_textCost); - - //HitBox box = new HitBox(36, 137, 84, 23) - //{ - // Priority = ClickPriority.Default - //}; - //Add(box); - - //HitBox box = new HitBox(522, 137, 84, 23) - //{ - // Priority = ClickPriority.Default - //}; - //Add(box); - - _dataBoxGUI = new DataBox(0, 0, 0, 0) - { - WantUpdateSize = true, - CanMove = false, - AcceptMouseInput = false - }; - - Add(_dataBoxGUI); - - UpdateMaxPage(); - Update(); - } - - public new void Update() - { - _dataBox.Clear(); - _dataBoxGUI.Clear(); - - _gumpPic.Graphic = (ushort)(_customHouseManager.FloorCount == 4 ? 0x55F2 : 0x55F9); - - Button button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_ERASE, - (ushort)(0x5666 + (_customHouseManager.Erasing ? 1 : 0)), - 0x5668, - 0x5667 - ) - { - X = 9, - Y = 100, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.Erase); - _dataBoxGUI.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_EYEDROPPER, - (ushort)(0x5669 + (_customHouseManager.SeekTile ? 1 : 0)), - 0x566B, - 0x566A - ) - { - X = 39, - Y = 100, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.EyedropperTool); - Add(button); - - ushort[] floorVisionGraphic1 = { 0x572E, 0x5734, 0x5731 }; - ushort[] floorVisionGraphic2 = { 0x5725, 0x5728, 0x572B }; - ushort[] floorVisionGraphic3 = { 0x571C, 0x571F, 0x5722 }; - - int[] associateGraphicTable = { 0, 1, 2, 1, 2, 1, 2 }; - - ushort floorVisionGraphic = floorVisionGraphic1[ - associateGraphicTable[_customHouseManager.FloorVisionState[0]] - ]; - - int graphicOffset = _customHouseManager.CurrentFloor == 1 ? 3 : 0; - int graphicOffset2 = _customHouseManager.CurrentFloor == 1 ? 4 : 0; - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_VISIBILITY_STORY_1, - floorVisionGraphic, - (ushort)(floorVisionGraphic + 2), - (ushort)(floorVisionGraphic + 1) - ) - { - X = 533, - Y = 108, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.Store0Visibility, 1)); - _dataBoxGUI.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_FLOOR_1, - (ushort)(0x56CD + graphicOffset2), - 0x56D1, - (ushort)(0x56CD + graphicOffset2) - ) - { - X = 583, - Y = 96, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.GoToStory0, 1)); - _dataBoxGUI.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_FLOOR_1, - (ushort)(0x56F6 + graphicOffset), - (ushort)(0x56F8 + graphicOffset), - (ushort)(0x56F7 + graphicOffset) - ) - { - X = 623, - Y = 103, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.GoToStory0, 1)); - _dataBoxGUI.Add(button); - - floorVisionGraphic = floorVisionGraphic2[ - associateGraphicTable[_customHouseManager.FloorVisionState[1]] - ]; - graphicOffset = _customHouseManager.CurrentFloor == 2 ? 3 : 0; - graphicOffset2 = _customHouseManager.CurrentFloor == 2 ? 4 : 0; - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_VISIBILITY_STORY_2, - floorVisionGraphic, - (ushort)(floorVisionGraphic + 2), - (ushort)(floorVisionGraphic + 1) - ) - { - X = 533, - Y = 86, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.Store0Visibility, 2)); - _dataBoxGUI.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_FLOOR_2, - (ushort)(0x56CE + graphicOffset2), - 0x56D2, - (ushort)(0x56CE + graphicOffset2) - ) - { - X = 583, - Y = 73, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.GoToStory0, 2)); - _dataBoxGUI.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_FLOOR_2, - (ushort)(0x56F0 + graphicOffset), - (ushort)(0x56F2 + graphicOffset), - (ushort)(0x56F1 + graphicOffset) - ) - { - X = 623, - Y = 86, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.GoToStory0, 2)); - _dataBoxGUI.Add(button); - - graphicOffset = _customHouseManager.CurrentFloor == 3 ? 3 : 0; - graphicOffset2 = _customHouseManager.CurrentFloor == 3 ? 4 : 0; - - if (_customHouseManager.FloorCount == 4) - { - floorVisionGraphic = floorVisionGraphic2[ - associateGraphicTable[_customHouseManager.FloorVisionState[2]] - ]; - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_VISIBILITY_STORY_3, - floorVisionGraphic, - (ushort)(floorVisionGraphic + 2), - (ushort)(floorVisionGraphic + 1) - ) - { - X = 533, - Y = 64, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.Store0Visibility, 3)); - _dataBoxGUI.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_FLOOR_3, - (ushort)(0x56CE + graphicOffset2), - 0x56D2, - (ushort)(0x56CE + graphicOffset2) - ) - { - X = 582, - Y = 56, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.GoToStory0, 3)); - _dataBoxGUI.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_FLOOR_3, - (ushort)(0x56F0 + graphicOffset), - (ushort)(0x56F2 + graphicOffset), - (ushort)(0x56F1 + graphicOffset) - ) - { - X = 623, - Y = 69, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.GoToStory0, 3)); - _dataBoxGUI.Add(button); - - floorVisionGraphic = floorVisionGraphic2[ - associateGraphicTable[_customHouseManager.FloorVisionState[3]] - ]; - - graphicOffset = _customHouseManager.CurrentFloor == 4 ? 3 : 0; - graphicOffset2 = _customHouseManager.CurrentFloor == 4 ? 4 : 0; - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_VISIBILITY_STORY_4, - floorVisionGraphic, - (ushort)(floorVisionGraphic + 2), - (ushort)(floorVisionGraphic + 1) - ) - { - X = 533, - Y = 42, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.Store0Visibility, 4)); - _dataBoxGUI.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_FLOOR_4, - (ushort)(0x56D0 + graphicOffset2), - 0x56D4, - (ushort)(0x56D0 + graphicOffset2) - ) - { - X = 583, - Y = 42, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.GoToStory0, 4)); - _dataBoxGUI.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_FLOOR_4, - (ushort)(0x56EA + graphicOffset), - (ushort)(0x56EC + graphicOffset), - (ushort)(0x56EB + graphicOffset) - ) - { - X = 623, - Y = 50, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.GoToStory0, 4)); - _dataBoxGUI.Add(button); - } - else - { - floorVisionGraphic = floorVisionGraphic2[ - associateGraphicTable[_customHouseManager.FloorVisionState[2]] - ]; - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_VISIBILITY_STORY_3, - floorVisionGraphic, - (ushort)(floorVisionGraphic + 2), - (ushort)(floorVisionGraphic + 1) - ) - { - X = 533, - Y = 64, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.Store0Visibility, 3)); - _dataBoxGUI.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_FLOOR_3, - (ushort)(0x56D0 + graphicOffset2), - 0x56D4, - (ushort)(0x56D0 + graphicOffset2) - ) - { - X = 582, - Y = 56, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.GoToStory0, 3)); - _dataBoxGUI.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_FLOOR_3, - (ushort)(0x56EA + graphicOffset), - (ushort)(0x56EC + graphicOffset), - (ushort)(0x56EB + graphicOffset) - ) - { - X = 623, - Y = 69, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(string.Format(ResGumps.GoToStory0, 3)); - _dataBoxGUI.Add(button); - } - - switch (_customHouseManager.State) - { - case CUSTOM_HOUSE_GUMP_STATE.CHGS_WALL: - AddWall(); - - break; - - case CUSTOM_HOUSE_GUMP_STATE.CHGS_DOOR: - AddDoor(); - - break; - - case CUSTOM_HOUSE_GUMP_STATE.CHGS_FLOOR: - AddFloor(); - - break; - - case CUSTOM_HOUSE_GUMP_STATE.CHGS_STAIR: - AddStair(); - - break; - - case CUSTOM_HOUSE_GUMP_STATE.CHGS_ROOF: - AddRoof(); - - break; - - case CUSTOM_HOUSE_GUMP_STATE.CHGS_MISC: - AddMisc(); - - break; - - case CUSTOM_HOUSE_GUMP_STATE.CHGS_MENU: - AddMenu(); - - break; - } - - if (_customHouseManager.MaxPage > 1) - { - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_LIST_LEFT, - 0x5625, - 0x5627, - 0x5626 - ) - { - X = 110, - Y = 63, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.PreviousPage); - _dataBoxGUI.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_LIST_RIGHT, - 0x5628, - 0x562A, - 0x5629 - ) - { - X = 510, - Y = 63, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.NextPage); - _dataBoxGUI.Add(button); - } - - _customHouseManager.Components = 0; - _customHouseManager.Fixtures = 0; - - Item foundationItem = World.Items.Get(LocalSerial); - - if (foundationItem != null) - { - if (World.HouseManager.TryGetHouse(LocalSerial, out House house)) - { - foreach (Multi item in house.Components) - { - if ( - item.IsCustom - && (item.State & CUSTOM_HOUSE_MULTI_OBJECT_FLAGS.CHMOF_GENERIC_INTERNAL) - == 0 - ) - { - CUSTOM_HOUSE_GUMP_STATE state = 0; - - (int res1, int res2) = _customHouseManager.ExistsInList( - ref state, - item.Graphic - ); - - if (res1 != -1 && res2 != -1) - { - if ( - state == CUSTOM_HOUSE_GUMP_STATE.CHGS_DOOR - || state == CUSTOM_HOUSE_GUMP_STATE.CHGS_FIXTURE - ) - { - _customHouseManager.Fixtures++; - } - else - { - _customHouseManager.Components++; - } - } - } - } - } - } - - _textComponents.Hue = (ushort)( - _customHouseManager.Components >= _customHouseManager.MaxComponets ? 0x0026 : 0x0481 - ); - - _textComponents.Text = _customHouseManager.Components.ToString(); - _textComponents.X = 82 - _textComponents.Width; - - _textFixtures.Hue = (ushort)( - _customHouseManager.Fixtures >= _customHouseManager.MaxFixtures ? 0x0026 : 0x0481 - ); - - _textFixtures.Text = _customHouseManager.Fixtures.ToString(); - - string tooltip = ClilocLoader.Instance.Translate( - 1061039, - $"{_customHouseManager.MaxComponets}\t{_customHouseManager.MaxFixtures}", - true - ); - - _textComponents.SetTooltip(tooltip); - _textFixtures.SetTooltip(tooltip); - - _textCost.Text = ( - (_customHouseManager.Components + _customHouseManager.Fixtures) * 500 - ).ToString(); - } - - public void UpdateMaxPage() - { - _customHouseManager.MaxPage = 1; - - switch (_customHouseManager.State) - { - case CUSTOM_HOUSE_GUMP_STATE.CHGS_WALL: - if (_customHouseManager.Category == -1) - { - _customHouseManager.MaxPage = (int) - Math.Ceiling(HouseCustomizationManager.Walls.Count / 16.0f); - } - else - { - foreach (CustomHouseWallCategory c in HouseCustomizationManager.Walls) - { - if (c.Index == _customHouseManager.Category) - { - _customHouseManager.MaxPage = c.Items.Count; - - break; - } - } - } - - break; - - case CUSTOM_HOUSE_GUMP_STATE.CHGS_DOOR: - _customHouseManager.MaxPage = HouseCustomizationManager.Doors.Count; - - break; - - case CUSTOM_HOUSE_GUMP_STATE.CHGS_FLOOR: - _customHouseManager.MaxPage = HouseCustomizationManager.Floors.Count; - - break; - - case CUSTOM_HOUSE_GUMP_STATE.CHGS_STAIR: - _customHouseManager.MaxPage = HouseCustomizationManager.Stairs.Count; - - break; - - case CUSTOM_HOUSE_GUMP_STATE.CHGS_ROOF: - if (_customHouseManager.Category == -1) - { - _customHouseManager.MaxPage = (int) - Math.Ceiling(HouseCustomizationManager.Roofs.Count / 16.0f); - } - else - { - foreach (CustomHouseRoofCategory c in HouseCustomizationManager.Roofs) - { - if (c.Index == _customHouseManager.Category) - { - _customHouseManager.MaxPage = c.Items.Count; - - break; - } - } - } - - break; - - case CUSTOM_HOUSE_GUMP_STATE.CHGS_MISC: - if (_customHouseManager.Category == -1) - { - _customHouseManager.MaxPage = (int) - Math.Ceiling(HouseCustomizationManager.Miscs.Count / 16.0f); - } - else - { - foreach (CustomHouseMiscCategory c in HouseCustomizationManager.Miscs) - { - if (c.Index == _customHouseManager.Category) - { - _customHouseManager.MaxPage = c.Items.Count; - - break; - } - } - } - - break; - } - } - - private void AddWall() - { - int x = 0, - y = 0; - - if (_customHouseManager.Category == -1) - { - int startCategory = Page * 16; - int endCategory = startCategory + 16; - - if (endCategory > HouseCustomizationManager.Walls.Count) - { - endCategory = HouseCustomizationManager.Walls.Count; - } - - _dataBox.Add(new ScissorControl(true, 121, 36, 384, 60)); - - for (int i = startCategory; i < endCategory; i++) - { - List vec = HouseCustomizationManager.Walls[i].Items; - - if (vec.Count == 0) - { - continue; - } - - ref readonly var artInfo = ref Client.Game.Arts.GetArt((uint)vec[0].East1); - - int offsetX = x + 121 + (48 - artInfo.UV.Width) / 2; - int offsetY = y + 36; - - StaticPic pic = new StaticPic((ushort)vec[0].East1, 0) - { - X = offsetX, - Y = offsetY, - CanMove = false, - LocalSerial = (uint)(ID_GUMP_CUSTOM_HOUSE.ID_GCH_ITEM_IN_LIST + i), - Height = 60 - }; - - pic.MouseUp += (sender, e) => - { - OnButtonClick((int)pic.LocalSerial); - }; - _dataBox.Add(pic); - - x += 48; - - if (x >= 384) - { - x = 0; - y += 60; - - _dataBox.Add(new ScissorControl(false)); - - _dataBox.Add(new ScissorControl(true, 121, 96, 384, 60)); - } - } - - // disable scissor - _dataBox.Add(new ScissorControl(false)); - } - else if ( - _customHouseManager.Category >= 0 - && _customHouseManager.Category < HouseCustomizationManager.Walls.Count - ) - { - List vec = HouseCustomizationManager.Walls[ - _customHouseManager.Category - ].Items; - - if (Page >= 0 && Page < vec.Count) - { - CustomHouseWall item = vec[Page]; - - // add scissor - _dataBox.Add(new ScissorControl(true, 121, 36, 384, 120)); - - for (int i = 0; i < 8; i++) - { - ushort graphic = _customHouseManager.ShowWindow - ? item.WindowGraphics[i] - : item.Graphics[i]; - - if (graphic != 0) - { - ref readonly var artInfo = ref Client.Game.Arts.GetArt(graphic); - - int offsetX = x + 130 + (48 - artInfo.UV.Width) / 2; - int offsetY = y + 36 + (120 - artInfo.UV.Height) / 2; - - StaticPic pic = new StaticPic(graphic, 0) - { - X = offsetX, - Y = offsetY, - CanMove = false, - LocalSerial = (uint)(ID_GUMP_CUSTOM_HOUSE.ID_GCH_ITEM_IN_LIST + i), - Height = 120 - }; - - pic.MouseUp += (sender, e) => - { - OnButtonClick((int)pic.LocalSerial); - }; - _dataBox.Add(pic); - } - - x += 48; - } - - // remove scissor - _dataBox.Add(new ScissorControl(false)); - } - - _dataBoxGUI.Add(new GumpPic(152, 0, 0x55F3, 0)); - - Button button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_CATEGORY, - 0x5622, - 0x5624, - 0x5623 - ) - { - X = 167, - Y = 5, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.ToCustomHouseManagerCategory); - _dataBoxGUI.Add(button); - - _dataBoxGUI.Add(new GumpPic(218, 4, 0x55F4, 0)); - - if (_customHouseManager.ShowWindow) - { - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_WALL_SHOW_WINDOW, - 0x562E, - 0x5630, - 0x562F - ) - { - X = 228, - Y = 9, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.WindowToggle); - _dataBoxGUI.Add(button); - } - else - { - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_WALL_SHOW_WINDOW, - 0x562B, - 0x562D, - 0x562C - ) - { - X = 228, - Y = 9, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.WindowToggle); - _dataBoxGUI.Add(button); - } - } - } - - private void AddDoor() - { - if (Page >= 0 && Page < HouseCustomizationManager.Doors.Count) - { - CustomHouseDoor item = HouseCustomizationManager.Doors[Page]; - - int x = 0, - y = 0; - - // add scissor - _dataBox.Add(new ScissorControl(true, 138, 36, 384, 120)); - - for (int i = 0; i < 8; i++) - { - ushort graphic = item.Graphics[i]; - - if (graphic != 0) - { - ref readonly var artInfo = ref Client.Game.Arts.GetArt(graphic); - - int offsetX = x + 138 + (48 - artInfo.UV.Width) / 2; - - if (i > 3) - { - offsetX -= 20; - } - - int offsetY = y + 36 + (120 - artInfo.UV.Height) / 2; - - StaticPic pic = new StaticPic(graphic, 0) - { - X = offsetX, - Y = offsetY, - CanMove = false, - LocalSerial = (uint)(ID_GUMP_CUSTOM_HOUSE.ID_GCH_ITEM_IN_LIST + i), - Height = 120 - }; - - pic.MouseUp += (sender, e) => - { - OnButtonClick((int)pic.LocalSerial); - }; - _dataBox.Add(pic); - } - - x += 48; - } - - int direction = 0; - - switch (item.Category) - { - case 16: - case 17: - case 18: - direction = 1; - - break; - - case 15: - direction = 2; - - break; - - case 19: - case 20: - case 21: - case 22: - case 23: - case 26: - case 27: - case 28: - case 29: - case 31: - case 32: - case 34: - direction = 3; - - break; - - case 30: - case 33: - direction = 4; - - break; - } - - switch (direction) - { - case 0: - _dataBox.Add(new GumpPic(151, 39, 0x5780, 0)); - _dataBox.Add(new GumpPic(196, 39, 0x5781, 0)); - _dataBox.Add(new GumpPic(219, 133, 0x5782, 0)); - _dataBox.Add(new GumpPic(266, 136, 0x5783, 0)); - _dataBox.Add(new GumpPic(357, 136, 0x5784, 0)); - _dataBox.Add(new GumpPic(404, 133, 0x5785, 0)); - _dataBox.Add(new GumpPic(431, 39, 0x5786, 0)); - _dataBox.Add(new GumpPic(474, 39, 0x5787, 0)); - - break; - - case 1: - _dataBox.Add(new GumpPic(245, 39, 0x5785, 0)); - _dataBox.Add(new GumpPic(290, 39, 0x5787, 0)); - _dataBox.Add(new GumpPic(337, 39, 0x5780, 0)); - _dataBox.Add(new GumpPic(380, 39, 0x5782, 0)); - - break; - - case 2: - _dataBox.Add(new GumpPic(219, 133, 0x5782, 0)); - _dataBox.Add(new GumpPic(404, 133, 0x5785, 0)); - - break; - - case 3: - _dataBox.Add(new GumpPic(245, 39, 0x5780, 0)); - _dataBox.Add(new GumpPic(290, 39, 0x5781, 0)); - _dataBox.Add(new GumpPic(337, 39, 0x5786, 0)); - _dataBox.Add(new GumpPic(380, 39, 0x5787, 0)); - - break; - - case 4: - _dataBox.Add(new GumpPic(151, 39, 0x5780, 0)); - _dataBox.Add(new GumpPic(196, 39, 0x5781, 0)); - _dataBox.Add(new GumpPic(245, 39, 0x5780, 0)); - _dataBox.Add(new GumpPic(290, 39, 0x5781, 0)); - _dataBox.Add(new GumpPic(337, 39, 0x5786, 0)); - _dataBox.Add(new GumpPic(380, 39, 0x5787, 0)); - _dataBox.Add(new GumpPic(431, 39, 0x5786, 0)); - _dataBox.Add(new GumpPic(474, 39, 0x5787, 0)); - - break; - } - - // remove scissor - _dataBox.Add(new ScissorControl(false)); - } - } - - private void AddFloor() - { - if (Page >= 0 && Page < HouseCustomizationManager.Floors.Count) - { - CustomHouseFloor item = HouseCustomizationManager.Floors[Page]; - - int x = 0, - y = 0; - - // add scissor - _dataBox.Add(new ScissorControl(true, 123, 36, 384, 120)); - - int index = 0; - - for (int j = 0; j < 2; j++) - { - for (int i = 0; i < 8; i++) - { - ushort graphic = item.Graphics[index]; - - if (graphic != 0) - { - ref readonly var artInfo = ref Client.Game.Arts.GetArt(graphic); - - int offsetX = x + 123 + (48 - artInfo.UV.Width) / 2; - int offsetY = y + 36 + (60 - artInfo.UV.Height) / 2; - - StaticPic pic = new StaticPic(graphic, 0) - { - X = offsetX, - Y = offsetY, - CanMove = false, - LocalSerial = (uint)( - ID_GUMP_CUSTOM_HOUSE.ID_GCH_ITEM_IN_LIST + index - ) - //Height = 120 - }; - - pic.MouseUp += (sender, e) => - { - OnButtonClick((int)pic.LocalSerial); - }; - _dataBox.Add(pic); - } - - x += 48; - index++; - } - - x = 0; - y += 60; - } - - // remove scissor - _dataBox.Add(new ScissorControl(false)); - } - } - - private void AddStair() - { - if (Page >= 0 && Page < HouseCustomizationManager.Stairs.Count) - { - CustomHouseStair item = HouseCustomizationManager.Stairs[Page]; - - for (int j = 0; j < 2; j++) - { - int x = j != 0 ? 96 : 192; - int y = j != 0 ? 60 : 0; - - // add scissor - _dataBox.Add(new ScissorControl(true, 121, 36 + y, 384, 60)); - - Label text = new Label( - ClilocLoader.Instance.GetString(1062113 + j), - true, - 0xFFFF, - 90, - 0 - ) - { - X = 137, - Y = j != 0 ? 111 : 51 - }; - - _dataBox.Add(text); - - int start = j != 0 ? 0 : 5; - int end = j != 0 ? 6 : 9; - int combinedStair = j != 0 ? 0 : 10; - - for (int i = start; i < end; i++) - { - ushort graphic = item.Graphics[i]; - - if (graphic != 0) - { - ref readonly var artInfo = ref Client.Game.Arts.GetArt(graphic); - - int offsetX = x + 123 + (48 - artInfo.UV.Width) / 2; - int offsetY = y + 36 + (60 - artInfo.UV.Height) / 2; - - StaticPic pic = new StaticPic(graphic, 0) - { - X = offsetX, - Y = offsetY, - CanMove = false, - LocalSerial = (uint)( - ID_GUMP_CUSTOM_HOUSE.ID_GCH_ITEM_IN_LIST + i + combinedStair - ), - Height = 60 - }; - - pic.MouseUp += (sender, e) => - { - OnButtonClick((int)pic.LocalSerial); - }; - _dataBox.Add(pic); - } - - x += 48; - } - - // remove scissor - _dataBox.Add(new ScissorControl(false)); - } - - _dataBox.Add(new ColorBox(384, 2, 0) { X = 123, Y = 96 }); - } - } - - private void AddRoof() - { - int x = 0, - y = 0; - - if (_customHouseManager.Category == -1) - { - int startCategory = Page * 16; - int endCategory = startCategory + 16; - - if (endCategory > HouseCustomizationManager.Roofs.Count) - { - endCategory = HouseCustomizationManager.Roofs.Count; - } - - // push scissor - _dataBox.Add(new ScissorControl(true, 121, 36, 384, 60)); - - for (int i = startCategory; i < endCategory; i++) - { - List vec = HouseCustomizationManager.Roofs[i].Items; - - if (vec.Count == 0) - { - continue; - } - - ref readonly var artInfo = ref Client.Game.Arts.GetArt((uint)vec[0].NSCrosspiece); - - int offsetX = x + 121 + (48 - artInfo.UV.Width) / 2; - int offsetY = y + 36; - - StaticPic pic = new StaticPic((ushort)vec[0].NSCrosspiece, 0) - { - X = offsetX, - Y = offsetY, - CanMove = false, - LocalSerial = (uint)(ID_GUMP_CUSTOM_HOUSE.ID_GCH_ITEM_IN_LIST + i), - Height = 60 - }; - - pic.MouseUp += (sender, e) => - { - OnButtonClick((int)pic.LocalSerial); - }; - _dataBox.Add(pic); - - x += 48; - - if (x >= 384) - { - x = 0; - y += 60; - - // pop scissor, - // push scissor - - _dataBox.Add(new ScissorControl(false)); - - _dataBox.Add(new ScissorControl(true, 121, 96, 384, 60)); - } - } - - // pop scissor - _dataBox.Add(new ScissorControl(false)); - } - else if ( - _customHouseManager.Category >= 0 - && _customHouseManager.Category < HouseCustomizationManager.Roofs.Count - ) - { - List vec = HouseCustomizationManager.Roofs[ - _customHouseManager.Category - ].Items; - - if (Page >= 0 && Page < vec.Count) - { - CustomHouseRoof item = vec[Page]; - - // push scissor - _dataBox.Add(new ScissorControl(true, 130, 44, 384, 120)); - - int index = 0; - - for (int j = 0; j < 2; j++) - { - for (int i = 0; i < 8; i++) - { - ushort graphic = item.Graphics[index]; - - if (graphic != 0) - { - ref readonly var artInfo = ref Client.Game.Arts.GetArt(graphic); - - int offsetX = x + 130 + (48 - artInfo.UV.Width) / 2; - int offsetY = y + 44 + (60 - artInfo.UV.Height) / 2; - - StaticPic pic = new StaticPic(graphic, 0) - { - X = offsetX, - Y = offsetY, - CanMove = false, - LocalSerial = (uint)( - ID_GUMP_CUSTOM_HOUSE.ID_GCH_ITEM_IN_LIST + index - ), - //Height = 120 - }; - - pic.MouseUp += (sender, e) => - { - OnButtonClick((int)pic.LocalSerial); - }; - _dataBox.Add(pic); - } - - x += 48; - index++; - } - - x = 0; - y += 60; - } - - // pop scissor - _dataBox.Add(new ScissorControl(false)); - } - - _dataBoxGUI.Add(new GumpPic(152, 0, 0x55F3, 0)); - - Button button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_CATEGORY, - 0x5622, - 0x5624, - 0x5623 - ) - { - X = 167, - Y = 5, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.ToCustomHouseManagerCategory); - _dataBoxGUI.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_ROOF_Z_DOWN, - 0x578B, - 0x578D, - 0x578C - ) - { - X = 305, - Y = 0, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.LowerRoofPlacementLevel); - _dataBoxGUI.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_ROOF_Z_UP, - 0x578E, - 0x5790, - 0x578F - ) - { - X = 349, - Y = 0, - ButtonAction = ButtonAction.Activate - }; - - button.SetTooltip(ResGumps.RaiseRoofPlacementLevel); - _dataBoxGUI.Add(button); - - _dataBoxGUI.Add(new GumpPic(583, 4, 0x55F4, 0)); - - Label text = new Label(_customHouseManager.RoofZ.ToString(), false, 0x04E9, font: 3) - { - X = 405, - Y = 15 - }; - - _dataBoxGUI.Add(text); - } - } - - private void AddMisc() - { - int x = 0, - y = 0; - - if (_customHouseManager.Category == -1) - { - int startCategory = Page * 16; - int endCategory = startCategory + 16; - - if (endCategory > HouseCustomizationManager.Miscs.Count) - { - endCategory = HouseCustomizationManager.Miscs.Count; - } - - // push scissor - _dataBox.Add(new ScissorControl(true, 121, 36, 384, 60)); - - for (int i = startCategory; i < endCategory; i++) - { - List vec = HouseCustomizationManager.Miscs[i].Items; - - if (vec.Count == 0) - { - continue; - } - - ref readonly var artInfo = ref Client.Game.Arts.GetArt((uint)vec[0].Piece5); - - int offsetX = x + 121 + (48 - artInfo.UV.Width) / 2; - int offsetY = y + 36; - - StaticPic pic = new StaticPic((ushort)vec[0].Piece5, 0) - { - X = offsetX, - Y = offsetY, - CanMove = false, - LocalSerial = (uint)(ID_GUMP_CUSTOM_HOUSE.ID_GCH_ITEM_IN_LIST + i), - Height = 60 - }; - - pic.MouseUp += (sender, e) => - { - OnButtonClick((int)pic.LocalSerial); - }; - _dataBox.Add(pic); - - x += 48; - - if (x >= 384) - { - x = 0; - y += 60; - - // pop scissor - // push scissor - _dataBox.Add(new ScissorControl(false)); - - _dataBox.Add(new ScissorControl(true, 121, 96, 384, 60)); - } - } - - // pop scissor - _dataBox.Add(new ScissorControl(false)); - } - else if ( - _customHouseManager.Category >= 0 - && _customHouseManager.Category < HouseCustomizationManager.Miscs.Count - ) - { - List vec = HouseCustomizationManager.Miscs[ - _customHouseManager.Category - ].Items; - - if (Page >= 0 && Page < vec.Count) - { - CustomHouseMisc item = vec[Page]; - - // push scissor - _dataBox.Add(new ScissorControl(true, 130, 44, 384, 120)); - - for (int i = 0; i < 8; i++) - { - ushort graphic = item.Graphics[i]; - - if (graphic != 0) - { - ref readonly var artInfo = ref Client.Game.Arts.GetArt(graphic); - - int offsetX = x + 130 + (48 - artInfo.UV.Width) / 2; - int offsetY = y + 44 + (120 - artInfo.UV.Height) / 2; - - StaticPic pic = new StaticPic(graphic, 0) - { - X = offsetX, - Y = offsetY, - CanMove = false, - LocalSerial = (uint)(ID_GUMP_CUSTOM_HOUSE.ID_GCH_ITEM_IN_LIST + i), - //Height = 120 - }; - - pic.MouseUp += (sender, e) => - { - OnButtonClick((int)pic.LocalSerial); - }; - _dataBox.Add(pic); - } - - x += 48; - } - - // pop scissor - _dataBox.Add(new ScissorControl(false)); - } - - _dataBoxGUI.Add(new GumpPic(152, 0, 0x55F3, 0)); - - _dataBoxGUI.Add( - new Button((int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_CATEGORY, 0x5622, 0x5624, 0x5623) - { - X = 167, - Y = 5, - ButtonAction = ButtonAction.Activate - } - ); - } - } - - private void AddMenu() - { - Button button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_MENU_BACKUP, - 0x098D, - 0x098D, - 0x098D, - ResGumps.Backup, - 0, - true, - 0, - 0x0036 - ) - { - X = 150, - Y = 50, - ButtonAction = ButtonAction.Activate, - FontCenter = true - }; - - button.SetTooltip(ResGumps.StoreDesignInProgress); - _dataBox.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_MENU_RESTORE, - 0x098D, - 0x098D, - 0x098D, - ResGumps.Restore, - 0, - true, - 0, - 0x0036 - ) - { - X = 150, - Y = 90, - ButtonAction = ButtonAction.Activate, - FontCenter = true - }; - - button.SetTooltip(ResGumps.RestoreYourDesign); - _dataBox.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_MENU_SYNCH, - 0x098D, - 0x098D, - 0x098D, - ResGumps.Sync, - 0, - true, - 0, - 0x0036 - ) - { - X = 270, - Y = 50, - ButtonAction = ButtonAction.Activate, - FontCenter = true - }; - - button.SetTooltip(ResGumps.SynchronizeDesignStateWithServer); - _dataBox.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_MENU_CLEAR, - 0x098D, - 0x098D, - 0x098D, - ResGumps.Clear, - 0, - true, - 0, - 0x0036 - ) - { - X = 270, - Y = 90, - ButtonAction = ButtonAction.Activate, - FontCenter = true - }; - - button.SetTooltip(ResGumps.ClearAllChanges); - _dataBox.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_MENU_COMMIT, - 0x098D, - 0x098D, - 0x098D, - ResGumps.Commit, - 0, - true, - 0, - 0x0036 - ) - { - X = 390, - Y = 50, - ButtonAction = ButtonAction.Activate, - FontCenter = true - }; - - button.SetTooltip(ResGumps.SaveExistingChanges); - _dataBox.Add(button); - - button = new Button( - (int)ID_GUMP_CUSTOM_HOUSE.ID_GCH_MENU_REVERT, - 0x098D, - 0x098D, - 0x098D, - ResGumps.Revert, - 0, - true, - 0, - 0x0036 - ) - { - X = 390, - Y = 90, - ButtonAction = ButtonAction.Activate, - FontCenter = true - }; - - button.SetTooltip(ResGumps.RevertYourDesign); - _dataBox.Add(button); - } - - public override void OnButtonClick(int buttonID) - { - ID_GUMP_CUSTOM_HOUSE idd = (ID_GUMP_CUSTOM_HOUSE)buttonID; - - if (idd >= ID_GUMP_CUSTOM_HOUSE.ID_GCH_ITEM_IN_LIST) - { - int index = idd - ID_GUMP_CUSTOM_HOUSE.ID_GCH_ITEM_IN_LIST; - - if ( - _customHouseManager.Category == -1 - && ( - _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_WALL - || _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_ROOF - || _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_MISC - ) - ) - { - int newCategory = -1; - - if ( - _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_WALL - && index >= 0 - && index < HouseCustomizationManager.Walls.Count - ) - { - newCategory = HouseCustomizationManager.Walls[index].Index; - } - else if ( - _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_ROOF - && index >= 0 - && index < HouseCustomizationManager.Roofs.Count - ) - { - newCategory = HouseCustomizationManager.Roofs[index].Index; - } - else if ( - _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_MISC - && index >= 0 - && index < HouseCustomizationManager.Miscs.Count - ) - { - newCategory = HouseCustomizationManager.Miscs[index].Index; - } - - if (newCategory != -1) - { - _customHouseManager.Category = newCategory; - Page = 0; - _customHouseManager.SelectedGraphic = 0; - _customHouseManager.Erasing = false; - _customHouseManager.SeekTile = false; - _customHouseManager.CombinedStair = false; - UpdateMaxPage(); - Update(); - } - } - else if (index >= 0 && Page >= 0) - { - bool combinedStairs = false; - ushort graphic = 0; - - if ( - _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_WALL - || _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_ROOF - || _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_MISC - ) - { - if (_customHouseManager.Category >= 0) - { - if ( - _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_WALL - && _customHouseManager.Category - < HouseCustomizationManager.Walls.Count - && index < CustomHouseWall.GRAPHICS_COUNT - ) - { - List list = HouseCustomizationManager.Walls[ - _customHouseManager.Category - ].Items; - - if (Page < list.Count) - { - graphic = _customHouseManager.ShowWindow - ? list[Page].WindowGraphics[index] - : list[Page].Graphics[index]; - } - } - else if ( - _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_ROOF - && _customHouseManager.Category - < HouseCustomizationManager.Roofs.Count - && index < CustomHouseRoof.GRAPHICS_COUNT - ) - { - List list = HouseCustomizationManager.Roofs[ - _customHouseManager.Category - ].Items; - - if (Page < list.Count) - { - graphic = list[Page].Graphics[index]; - } - } - else if ( - _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_MISC - && _customHouseManager.Category - < HouseCustomizationManager.Miscs.Count - && index < CustomHouseMisc.GRAPHICS_COUNT - ) - { - List list = HouseCustomizationManager.Miscs[ - _customHouseManager.Category - ].Items; - - if (Page < list.Count) - { - graphic = list[Page].Graphics[index]; - } - } - } - } - else - { - if ( - _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_DOOR - && Page < HouseCustomizationManager.Doors.Count - && index < CustomHouseDoor.GRAPHICS_COUNT - ) - { - graphic = HouseCustomizationManager.Doors[Page].Graphics[index]; - } - else if ( - _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_FLOOR - && Page < HouseCustomizationManager.Floors.Count - && index < CustomHouseFloor.GRAPHICS_COUNT - ) - { - graphic = HouseCustomizationManager.Floors[Page].Graphics[index]; - } - else if ( - _customHouseManager.State == CUSTOM_HOUSE_GUMP_STATE.CHGS_STAIR - && Page < HouseCustomizationManager.Stairs.Count - ) - { - if (index > 10) - { - combinedStairs = true; - index -= 10; - } - - if (index < CustomHouseStair.GRAPHICS_COUNT) - { - graphic = HouseCustomizationManager.Stairs[Page].Graphics[index]; - } - } - } - - if (graphic != 0) - { - _customHouseManager.SetTargetMulti(); - _customHouseManager.CombinedStair = combinedStairs; - _customHouseManager.SelectedGraphic = graphic; - Update(); - } - } - - return; - } - - switch (idd) - { - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_WALL: - _customHouseManager.Category = -1; - _customHouseManager.State = CUSTOM_HOUSE_GUMP_STATE.CHGS_WALL; - Page = 0; - _customHouseManager.SelectedGraphic = 0; - _customHouseManager.CombinedStair = false; - UpdateMaxPage(); - TargetManager.CancelTarget(); - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_DOOR: - _customHouseManager.Category = -1; - _customHouseManager.State = CUSTOM_HOUSE_GUMP_STATE.CHGS_DOOR; - Page = 0; - _customHouseManager.SelectedGraphic = 0; - _customHouseManager.CombinedStair = false; - UpdateMaxPage(); - TargetManager.CancelTarget(); - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_FLOOR: - _customHouseManager.Category = -1; - _customHouseManager.State = CUSTOM_HOUSE_GUMP_STATE.CHGS_FLOOR; - Page = 0; - _customHouseManager.SelectedGraphic = 0; - _customHouseManager.CombinedStair = false; - UpdateMaxPage(); - TargetManager.CancelTarget(); - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_STAIR: - _customHouseManager.Category = -1; - _customHouseManager.State = CUSTOM_HOUSE_GUMP_STATE.CHGS_STAIR; - Page = 0; - _customHouseManager.SelectedGraphic = 0; - _customHouseManager.CombinedStair = false; - UpdateMaxPage(); - TargetManager.CancelTarget(); - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_ROOF: - _customHouseManager.Category = -1; - _customHouseManager.State = CUSTOM_HOUSE_GUMP_STATE.CHGS_ROOF; - Page = 0; - _customHouseManager.SelectedGraphic = 0; - _customHouseManager.CombinedStair = false; - UpdateMaxPage(); - TargetManager.CancelTarget(); - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_MISC: - _customHouseManager.Category = -1; - _customHouseManager.State = CUSTOM_HOUSE_GUMP_STATE.CHGS_MISC; - Page = 0; - _customHouseManager.SelectedGraphic = 0; - _customHouseManager.CombinedStair = false; - UpdateMaxPage(); - TargetManager.CancelTarget(); - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_ERASE: - _customHouseManager.SetTargetMulti(); - _customHouseManager.Erasing = !_customHouseManager.Erasing; - _customHouseManager.SelectedGraphic = 0; - _customHouseManager.CombinedStair = false; - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_EYEDROPPER: - _customHouseManager.SetTargetMulti(); - _customHouseManager.SeekTile = true; - _customHouseManager.SelectedGraphic = 0; - _customHouseManager.CombinedStair = false; - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_STATE_MENU: - _customHouseManager.Category = -1; - _customHouseManager.State = CUSTOM_HOUSE_GUMP_STATE.CHGS_MENU; - Page = 0; - _customHouseManager.MaxPage = 1; - _customHouseManager.SelectedGraphic = 0; - _customHouseManager.CombinedStair = false; - TargetManager.CancelTarget(); - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_VISIBILITY_STORY_1: - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_VISIBILITY_STORY_2: - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_VISIBILITY_STORY_3: - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_VISIBILITY_STORY_4: - int selectedFloor = - (ID_GUMP_CUSTOM_HOUSE)buttonID - - ID_GUMP_CUSTOM_HOUSE.ID_GCH_VISIBILITY_STORY_1; - - _customHouseManager.FloorVisionState[selectedFloor]++; - - if ( - _customHouseManager.FloorVisionState[selectedFloor] - > (int)CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_HIDE_ALL - ) - { - _customHouseManager.FloorVisionState[selectedFloor] = (int) - CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_NORMAL; - } - - _customHouseManager.GenerateFloorPlace(); - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_FLOOR_1: - _customHouseManager.CurrentFloor = 1; - NetClient.Socket.Send_CustomHouseGoToFloor(1); - - for (int i = 0; i < _customHouseManager.FloorVisionState.Length; i++) - { - _customHouseManager.FloorVisionState[i] = (int) - CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_NORMAL; - } - - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_FLOOR_2: - _customHouseManager.CurrentFloor = 2; - NetClient.Socket.Send_CustomHouseGoToFloor(2); - - for (int i = 0; i < _customHouseManager.FloorVisionState.Length; i++) - { - _customHouseManager.FloorVisionState[i] = (int) - CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_NORMAL; - } - - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_FLOOR_3: - _customHouseManager.CurrentFloor = 3; - NetClient.Socket.Send_CustomHouseGoToFloor(3); - - for (int i = 0; i < _customHouseManager.FloorVisionState.Length; i++) - { - _customHouseManager.FloorVisionState[i] = (int) - CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_NORMAL; - } - - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_FLOOR_4: - _customHouseManager.CurrentFloor = 4; - NetClient.Socket.Send_CustomHouseGoToFloor(4); - - for (int i = 0; i < _customHouseManager.FloorVisionState.Length; i++) - { - _customHouseManager.FloorVisionState[i] = (int) - CUSTOM_HOUSE_FLOOR_VISION_STATE.CHGVS_NORMAL; - } - - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_LIST_LEFT: - Page--; - - if (Page < 0) - { - Page = _customHouseManager.MaxPage - 1; - - if (Page < 0) - { - Page = 0; - } - } - - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_LIST_RIGHT: - Page++; - - if (Page >= _customHouseManager.MaxPage) - { - Page = 0; - } - - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_MENU_BACKUP: - NetClient.Socket.Send_CustomHouseBackup(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_MENU_RESTORE: - NetClient.Socket.Send_CustomHouseRestore(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_MENU_SYNCH: - NetClient.Socket.Send_CustomHouseSync(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_MENU_CLEAR: - NetClient.Socket.Send_CustomHouseClear(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_MENU_COMMIT: - NetClient.Socket.Send_CustomHouseCommit(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_MENU_REVERT: - NetClient.Socket.Send_CustomHouseRevert(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_GO_CATEGORY: - _customHouseManager.Category = -1; - Page = 0; - _customHouseManager.SelectedGraphic = 0; - _customHouseManager.CombinedStair = false; - UpdateMaxPage(); - TargetManager.CancelTarget(); - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_WALL_SHOW_WINDOW: - _customHouseManager.ShowWindow = !_customHouseManager.ShowWindow; - Update(); - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_ROOF_Z_UP: - if (_customHouseManager.RoofZ < 6) - { - _customHouseManager.RoofZ++; - Update(); - } - - break; - - case ID_GUMP_CUSTOM_HOUSE.ID_GCH_ROOF_Z_DOWN: - if (_customHouseManager.RoofZ > 1) - { - _customHouseManager.RoofZ--; - Update(); - } - - break; - } - } - - public override void Dispose() - { - World.CustomHouseManager = null; - NetClient.Socket.Send_CustomHouseBuildingExit(); - TargetManager.CancelTarget(); - - base.Dispose(); - } - - private enum ID_GUMP_CUSTOM_HOUSE - { - ID_GCH_STATE_WALL = 1, - ID_GCH_STATE_DOOR, - ID_GCH_STATE_FLOOR, - ID_GCH_STATE_STAIR, - ID_GCH_STATE_ROOF, - ID_GCH_STATE_MISC, - ID_GCH_STATE_ERASE, - ID_GCH_STATE_EYEDROPPER, - ID_GCH_STATE_MENU, - - ID_GCH_VISIBILITY_STORY_1, - ID_GCH_VISIBILITY_STORY_2, - ID_GCH_VISIBILITY_STORY_3, - ID_GCH_VISIBILITY_STORY_4, - - ID_GCH_GO_FLOOR_1, - ID_GCH_GO_FLOOR_2, - ID_GCH_GO_FLOOR_3, - ID_GCH_GO_FLOOR_4, - - ID_GCH_LIST_LEFT, - ID_GCH_LIST_RIGHT, - - ID_GCH_MENU_BACKUP, - ID_GCH_MENU_RESTORE, - ID_GCH_MENU_SYNCH, - ID_GCH_MENU_CLEAR, - ID_GCH_MENU_COMMIT, - ID_GCH_MENU_REVERT, - - ID_GCH_GO_CATEGORY, - ID_GCH_WALL_SHOW_WINDOW, - ID_GCH_ROOF_Z_UP, - ID_GCH_ROOF_Z_DOWN, - - ID_GCH_AREA_OBJECTS_INFO, - ID_GCH_AREA_COST_INFO, - ID_GCH_AREA_ROOF_Z_INFO, - - ID_GCH_ITEM_IN_LIST - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/IgnoreManagerGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/IgnoreManagerGump.cs deleted file mode 100644 index 88105a39d..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/IgnoreManagerGump.cs +++ /dev/null @@ -1,233 +0,0 @@ -using System; -using System.Linq; -using ClassicUO.Configuration; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal sealed class IgnoreManagerGump : Gump - { - private const ushort HUE_FONT = 0xFFFF; - private const ushort BACKGROUND_COLOR = 999; - private const ushort GUMP_WIDTH = 300; - private const ushort GUMP_HEIGHT = 400; - - private readonly int _gumpPosX = Client.Game.Scene.Camera.Bounds.Width / 2 - 125; - private readonly int _gumpPosY = 100; - - private static ScrollArea _scrollArea; - - private bool _isListModified; - - private enum ButtonsId - { - ADD_NEW_IGNORE, - } - - public IgnoreManagerGump() : base(0, 0) - { - CanMove = true; - - Add - ( - new AlphaBlendControl(0.95f) - { - X = _gumpPosX, - Y = _gumpPosY, - Width = GUMP_WIDTH, - Height = GUMP_HEIGHT, - Hue = BACKGROUND_COLOR, - AcceptMouseInput = true, - CanMove = true, - CanCloseWithRightClick = true, - } - ); - - #region Boarder - Add - ( - new Line - ( - _gumpPosX, - _gumpPosY, - GUMP_WIDTH, - 1, - Color.Gray.PackedValue - ) - ); - - Add - ( - new Line - ( - _gumpPosX, - _gumpPosY, - 1, - GUMP_HEIGHT, - Color.Gray.PackedValue - ) - ); - - Add - ( - new Line - ( - _gumpPosX, - GUMP_HEIGHT + _gumpPosY, - GUMP_WIDTH, - 1, - Color.Gray.PackedValue - ) - ); - - Add - ( - new Line - ( - GUMP_WIDTH + _gumpPosX, - _gumpPosY, - 1, - GUMP_HEIGHT, - Color.Gray.PackedValue - ) - ); - #endregion - - var initY = _gumpPosY + 10; - - #region Legend - - Add(new Label(ResGumps.IgnoreListName, true, HUE_FONT, 185, 255, FontStyle.BlackBorder) { X = _gumpPosX + 10, Y = initY }); - - Add(new Label(ResGumps.Remove, true, HUE_FONT, 185, 255, FontStyle.BlackBorder) { X = _gumpPosX + 210, Y = initY }); - - Add - ( - new Line - ( - _gumpPosX, - initY + 20, - GUMP_WIDTH, - 1, - Color.Gray.PackedValue - ) - ); - - #endregion - - Add - ( - new NiceButton - ( - _gumpPosX + 20, _gumpPosY + GUMP_HEIGHT - 30, GUMP_WIDTH - 40, 25, - ButtonAction.Activate, ResGumps.IgnoreListAddButton - ) - ); - - DrawArea(); - SetInScreen(); - } - - /// - /// On Dispose save XML File - /// - public override void Dispose() - { - if (_isListModified) - IgnoreManager.SaveIgnoreList(); - - if (TargetManager.IsTargeting) - TargetManager.CancelTarget(); - - base.Dispose(); - } - - /// - /// Draw Scroll Area - /// - private void DrawArea() - { - _scrollArea = new ScrollArea - ( - _gumpPosX + 10, _gumpPosY + 40, GUMP_WIDTH - 20, GUMP_HEIGHT - 80, - true - ); - - var y = 0; - foreach (IgnoreListControl element in IgnoreManager.IgnoredCharsList.Select(m => new IgnoreListControl(m) { Y = y })) - { - element.RemoveMarkerEvent += MarkerRemoveEventHandler; - - _scrollArea.Add(element); - y += 25; - } - - Add(_scrollArea); - } - - /// - /// Handle Remove from ignored list - /// - /// - /// - private void MarkerRemoveEventHandler(object sender, EventArgs e) - { - Redraw(); - } - - /// - /// Redraw ignored list - /// - public void Redraw() - { - // If we need to redraw we assume that something changed in list - _isListModified = true; - Remove(_scrollArea); - DrawArea(); - } - - /// - /// On Button Click handler - /// - /// Button Id - public override void OnButtonClick(int buttonId) - { - switch (buttonId) - { - case (int)ButtonsId.ADD_NEW_IGNORE: - TargetManager.SetTargeting(CursorTarget.IgnorePlayerTarget, CursorType.Target, TargetType.Neutral); - break; - } - } - - private sealed class IgnoreListControl : Control - { - private readonly string _chName; - - public event EventHandler RemoveMarkerEvent; - - public IgnoreListControl(string chName) - { - CanMove = true; - AcceptMouseInput = false; - CanCloseWithRightClick = true; - _chName = chName; - - Add(new Label(chName, true, HUE_FONT, 290) { X = 10 }); - - Add(new Button(1, 0xFAB, 0xFAC) { X = 220, ButtonAction = ButtonAction.Activate }); - } - - public override void OnButtonClick(int buttonId) - { - IgnoreManager.RemoveIgnoredTarget(_chName); - RemoveMarkerEvent.Raise(); - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/ImprovedBuffGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/ImprovedBuffGump.cs deleted file mode 100644 index 0416dddc8..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/ImprovedBuffGump.cs +++ /dev/null @@ -1,229 +0,0 @@ -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Renderer; -using System; -using System.Collections.Generic; -using System.Xml; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class ImprovedBuffGump : Gump - { - public const int HEIGHT = CoolDownBar.COOL_DOWN_HEIGHT * (BuffBarManager.MAX_COOLDOWN_BARS + 2); - private GumpPic _background; - private Button _button; - private bool _direction = false; - private ushort _graphic = 2091; - private DataBox _box; - - public ImprovedBuffGump() : base(0, 0) - { - X = 100; - Y = 100; - Width = CoolDownBar.COOL_DOWN_WIDTH; - Height = HEIGHT; - CanMove = true; - CanCloseWithRightClick = true; - AcceptMouseInput = false; - - BuildGump(); - } - - public void AddBuff(BuffIcon icon) - { - CoolDownBar coolDownBar = new CoolDownBar(TimeSpan.FromMilliseconds(icon.Timer - Time.Ticks), icon.Title.Replace("
", " "), ProfileManager.CurrentProfile.ImprovedBuffBarHue, 0, 0, icon.Graphic, icon.Type, true); - coolDownBar.SetTooltip(icon.Text); - BuffBarManager.AddCoolDownBar(coolDownBar, _direction, _box); - _box.Add(coolDownBar); - } - - public void RemoveBuff(BuffIconType graphic) - { - BuffBarManager.RemoveBuffType(graphic); - BuffBarManager.UpdatePositions(_direction, _box); - } - - private void SwitchDirections() - { - _box.Height = HEIGHT; - _box.Y = 0; - if (!_direction) - { - _background.Y = HEIGHT - 11; - Y -= HEIGHT - 11; - } - else - { - _background.Y = 0; - Y += HEIGHT - 11; - } - _button.Y = _background.Y - 5; - BuffBarManager.UpdatePositions(_direction, _box); - } - - protected override void UpdateContents() - { - base.UpdateContents(); - _box.Height = HEIGHT; - _box.Y = 0; - if (!_direction) - { - _background.Y = HEIGHT - 11; - } - else - { - _background.Y = 0; - } - _button.Y = _background.Y - 5; - BuffBarManager.UpdatePositions(_direction, _box); - } - - public override void Update() - { - base.Update(); - } - - public override void OnButtonClick(int buttonID) - { - if (buttonID == 0) - { - _direction = !_direction; - SwitchDirections(); - } - } - - private void BuildGump() - { - _background = new GumpPic(0, 0, _graphic, 0); - _background.Width = CoolDownBar.COOL_DOWN_WIDTH; - - _button = new Button(0, 0x7585, 0x7589, 0x7589) - { - ButtonAction = ButtonAction.Activate - }; - - _box = new DataBox(0, 0, Width, HEIGHT); - - - - Add(_background); - Add(_button); - Add(_box); - - BuffBarManager.Clear(); - if (World.Player != null) - { - foreach (KeyValuePair k in World.Player.BuffIcons) - { - AddBuff(k.Value); - } - } - UpdateContents(); - } - - public ImprovedBuffGump(int x, int y) : this() - { - X = x; - Y = y; - } - - public override void Save(XmlTextWriter writer) - { - base.Save(writer); - writer.WriteAttributeString("graphic", _graphic.ToString()); - writer.WriteAttributeString("updown", _direction.ToString()); - writer.WriteAttributeString("lastX", X.ToString()); - writer.WriteAttributeString("lastY", Y.ToString()); - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - - _graphic = ushort.Parse(xml.GetAttribute("graphic")); - _direction = bool.Parse(xml.GetAttribute("updown")); - int.TryParse(xml.GetAttribute("lastX"), out X); - int.TryParse(xml.GetAttribute("lastY"), out Y); - RequestUpdateContents(); - } - - public override GumpType GumpType => GumpType.Buff; - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - return base.Draw(batcher, x, y); - } - - private static class BuffBarManager - { - public const int MAX_COOLDOWN_BARS = 20; - private static CoolDownBar[] coolDownBars = new CoolDownBar[MAX_COOLDOWN_BARS]; - public static void AddCoolDownBar(CoolDownBar coolDownBar, bool topDown, DataBox _boxContainer) - { - for (int i = 0; i < coolDownBars.Length; i++) - { - if (coolDownBars[i] != null && !coolDownBars[i].IsDisposed && coolDownBars[i].buffIconType == coolDownBar.buffIconType) - { - coolDownBars[i].Dispose(); - coolDownBars[i] = coolDownBar; - UpdatePositions(topDown, _boxContainer); - return; - } - if (coolDownBars[i] == null || coolDownBars[i].IsDisposed) - { - coolDownBars[i] = coolDownBar; - UpdatePositions(topDown, _boxContainer); - return; - } - } - } - - public static void UpdatePositions(bool topDown, DataBox _boxContainer) - { - int actualI = 0; - for (int i = 0; i < coolDownBars.Length; i++) - { - if (coolDownBars[i] != null && !coolDownBars[i].IsDisposed) - { - if (topDown) - { - coolDownBars[i].Y = (actualI * (CoolDownBar.COOL_DOWN_HEIGHT + 2)) + 13; - } - else - { - coolDownBars[i].Y = _boxContainer.Height - ((actualI + 1) * (CoolDownBar.COOL_DOWN_HEIGHT + 2)) - 11; - } - actualI++; - } - } - } - - public static void RemoveBuffType(BuffIconType type) - { - for (int i = 0; i < coolDownBars.Length; i++) - { - if (coolDownBars[i] != null && !coolDownBars[i].IsDisposed) - { - if (coolDownBars[i].buffIconType == type) - { - coolDownBars[i].Dispose(); - } - } - } - } - - public static void Clear() - { - for (int i = 0; i < coolDownBars.Length; i++) - { - if (coolDownBars[i] != null) - { - coolDownBars[i].Dispose(); - } - } - coolDownBars = new CoolDownBar[MAX_COOLDOWN_BARS]; - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/InfoBarGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/InfoBarGump.cs deleted file mode 100644 index d30e65f1b..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/InfoBarGump.cs +++ /dev/null @@ -1,439 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using System.Linq; -using System.Xml; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class InfoBarGump : ResizableGump - { - private readonly AlphaBlendControl _background; - - private readonly List _infobarControls = new List(); - private long _refreshTime; - - public override bool IsLocked => _isLocked; - - public InfoBarGump() : base(ProfileManager.CurrentProfile.InfoBarSize.X, ProfileManager.CurrentProfile.InfoBarSize.Y, 50, 20, 0, 0) - { - CanBeLocked = true; //For base gump locking, resizable uses a special locking procedure - CanMove = true; - _prevCanMove = true; - AcceptMouseInput = true; - AcceptKeyboardInput = false; - CanCloseWithRightClick = false; - _prevCloseWithRightClick = false; - ShowBorder = true; - _prevBorder = true; - - Insert(0, _background = new AlphaBlendControl(0.7f) { Width = Width - 8, Height = Height - 8, X = 4, Y = 4, Parent = this }); - - ResetItems(); - - } - - public override GumpType GumpType => GumpType.InfoBar; - - public void ResetItems() - { - foreach (InfoBarControl c in _infobarControls) - { - c.Dispose(); - } - - _infobarControls.Clear(); - - List infoBarItems = Client.Game.GetScene().InfoBars.GetInfoBars(); - - for (int i = 0; i < infoBarItems.Count; i++) - { - InfoBarControl info = new InfoBarControl(infoBarItems[i].label, infoBarItems[i].var, infoBarItems[i].hue); - - _infobarControls.Add(info); - Add(info); - } - } - - public void UpdateOptions() - { - ResetItems(); - } - - public static void UpdateAllOptions() - { - foreach(InfoBarGump g in UIManager.Gumps.OfType()) - { - g.UpdateOptions(); - } - } - - public override void Update() - { - if (IsDisposed) - { - return; - } - - if (_refreshTime < Time.Ticks) - { - _refreshTime = (long)Time.Ticks + 250; - - int x = 6, y = 6; - - foreach (InfoBarControl c in _infobarControls) - { - if (x + c.Width + 8 > Width) - { - y += c.Height; - x = 6; - } - - c.X = x; - c.Y = y; - - x += c.Width + 8; - } - ProfileManager.CurrentProfile.InfoBarLocked = IsLocked; - } - - base.Update(); - - _background.Width = Width - 8; - _background.Height = Height - 8; - } - - public override void OnResize() - { - base.OnResize(); - - ProfileManager.CurrentProfile.InfoBarSize = new Point(Width, Height); - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - SetLockStatus(ProfileManager.CurrentProfile.InfoBarLocked); - } - } - - - internal class InfoBarControl : Control - { - private readonly TextBox _data; - private readonly TextBox _label; - private readonly ResizableStaticPic _pic; - private ushort _warningLinesHue; - - public InfoBarControl(string label, InfoBarVars var, ushort hue) - { - AcceptMouseInput = false; - WantUpdateSize = true; - CanMove = false; - Hue = hue; - - _label = new TextBox( - label, - ProfileManager.CurrentProfile.InfoBarFont, - ProfileManager.CurrentProfile.InfoBarFontSize, - null, - hue, - strokeEffect: false - ); - if (label.StartsWith(@"\")) - { - if (ushort.TryParse(label.Substring(1), out ushort gphc)) - { - _label.IsVisible = false; - Add(_pic = new ResizableStaticPic(gphc, 20, 20) { Hue = hue }); - } - } - - Var = var; - - _data = new TextBox( - "", - ProfileManager.CurrentProfile.InfoBarFont, - ProfileManager.CurrentProfile.InfoBarFontSize, - null, - 0x0481, - strokeEffect: false - ) - { X = _label.IsVisible ? _label.Width + 3 : _pic.Width }; - - Add(_label); - Add(_data); - } - - public string Text => _label.Text; - public InfoBarVars Var { get; } - - public ushort Hue { get; } - protected long _refreshTime = (long)Time.Ticks - 1; - - public override void Update() - { - if (IsDisposed) - { - return; - } - - if (_refreshTime < Time.Ticks) - { - _refreshTime = (long)Time.Ticks + 250; - - string newData = GetVarData(Var) ?? string.Empty; - if (!newData.Equals(_data.Text)) - { - _data.UpdateText(newData); - _data.WantUpdateSize = true; - WantUpdateSize = true; - } - - if (ProfileManager.CurrentProfile.InfoBarHighlightType == 0 || Var == InfoBarVars.NameNotoriety) - { - ushort hue = GetVarHue(Var); - if (!hue.Equals((ushort)_data.Hue)) - { - _data.Hue = hue; - } - } - else - { - if ((ushort)_data.Hue != 0x0481) - { - _data.Hue = 0x0481; - } - _warningLinesHue = GetVarHue(Var); - } - } - - base.Update(); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - if (Var != InfoBarVars.NameNotoriety && ProfileManager.CurrentProfile.InfoBarHighlightType == 1 && _warningLinesHue != 0x0481) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(_warningLinesHue); - - batcher.Draw - ( - SolidColorTextureCache.GetTexture(Color.White), - new Rectangle - ( - _data.ScreenCoordinateX, - _data.ScreenCoordinateY, - _data.Width, - 2 - ), - hueVector - ); - - batcher.Draw - ( - SolidColorTextureCache.GetTexture(Color.White), - new Rectangle - ( - _data.ScreenCoordinateX, - _data.ScreenCoordinateY + Parent.Height - 2, - _data.Width, - 2 - ), - hueVector - ); - } - - return true; - } - - private string GetVarData(InfoBarVars var) - { - switch (var) - { - case InfoBarVars.HP: return $"{World.Player.Hits}/{World.Player.HitsMax}"; - - case InfoBarVars.Mana: return $"{World.Player.Mana}/{World.Player.ManaMax}"; - - case InfoBarVars.Stamina: return $"{World.Player.Stamina}/{World.Player.StaminaMax}"; - - case InfoBarVars.Weight: return $"{World.Player.Weight}/{World.Player.WeightMax}"; - - case InfoBarVars.Followers: return $"{World.Player.Followers}/{World.Player.FollowersMax}"; - - case InfoBarVars.Gold: return World.Player.Gold.ToString(); - - case InfoBarVars.Damage: return $"{World.Player.DamageMin}-{World.Player.DamageMax}"; - - case InfoBarVars.Armor: return World.Player.PhysicalResistance.ToString(); - - case InfoBarVars.Luck: return World.Player.Luck.ToString(); - - case InfoBarVars.FireResist: return World.Player.FireResistance.ToString(); - - case InfoBarVars.ColdResist: return World.Player.ColdResistance.ToString(); - - case InfoBarVars.PoisonResist: return World.Player.PoisonResistance.ToString(); - - case InfoBarVars.EnergyResist: return World.Player.EnergyResistance.ToString(); - - case InfoBarVars.LowerReagentCost: return World.Player.LowerReagentCost.ToString(); - - case InfoBarVars.SpellDamageInc: return World.Player.SpellDamageIncrease.ToString(); - - case InfoBarVars.FasterCasting: return World.Player.FasterCasting.ToString(); - - case InfoBarVars.FasterCastRecovery: return World.Player.FasterCastRecovery.ToString(); - - case InfoBarVars.HitChanceInc: return World.Player.HitChanceIncrease.ToString(); - - case InfoBarVars.DefenseChanceInc: return World.Player.DefenseChanceIncrease.ToString(); - - case InfoBarVars.LowerManaCost: return World.Player.LowerManaCost.ToString(); - - case InfoBarVars.DamageChanceInc: return World.Player.DamageIncrease.ToString(); - - case InfoBarVars.SwingSpeedInc: return World.Player.SwingSpeedIncrease.ToString(); - - case InfoBarVars.StatsCap: return World.Player.StatsCap.ToString(); - - case InfoBarVars.NameNotoriety: return World.Player.Name; - - case InfoBarVars.TithingPoints: return World.Player.TithingPoints.ToString(); - - default: return ""; - } - } - - private ushort GetVarHue(InfoBarVars var) - { - float percent; - - switch (var) - { - case InfoBarVars.HP: - percent = World.Player.Hits / (float)World.Player.HitsMax; - - if (percent <= 0.25) - { - return 0x0021; - } - else if (percent <= 0.5) - { - return 0x0030; - } - else if (percent <= 0.75) - { - return 0x0035; - } - else - { - return 0x0481; - } - - case InfoBarVars.Mana: - percent = World.Player.Mana / (float)World.Player.ManaMax; - - if (percent <= 0.25) - { - return 0x0021; - } - else if (percent <= 0.5) - { - return 0x0030; - } - else if (percent <= 0.75) - { - return 0x0035; - } - else - { - return 0x0481; - } - - case InfoBarVars.Stamina: - percent = World.Player.Stamina / (float)World.Player.StaminaMax; - - if (percent <= 0.25) - { - return 0x0021; - } - else if (percent <= 0.5) - { - return 0x0030; - } - else if (percent <= 0.75) - { - return 0x0035; - } - else - { - return 0x0481; - } - - case InfoBarVars.Weight: - percent = World.Player.Weight / (float)World.Player.WeightMax; - - if (percent >= 1) - { - return 0x0021; - } - else if (percent >= 0.75) - { - return 0x0030; - } - else if (percent >= 0.5) - { - return 0x0035; - } - else - { - return 0x0481; - } - - case InfoBarVars.NameNotoriety: return Notoriety.GetHue(World.Player.NotorietyFlag); - - default: return 0x0481; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/InputRequest.cs b/src/ClassicUO.Client/Game/UI/Gumps/InputRequest.cs deleted file mode 100644 index ccf939618..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/InputRequest.cs +++ /dev/null @@ -1,60 +0,0 @@ -using ClassicUO.Assets; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using System; -using static ClassicUO.Game.UI.Gumps.OptionsGump; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class InputRequest : Gump - { - public InputRequest(string message, string buttonText, string button2Text, Action result) : base(0, 0) - { - Width = 400; - Height = 0; - - AlphaBlendControl bg; - Add(bg = new AlphaBlendControl(0.75f)); - - Control _; - Add(_ = new TextBox(message, TrueTypeLoader.EMBEDDED_FONT, 25, Width, Microsoft.Xna.Framework.Color.White, FontStashSharp.RichText.TextHorizontalAlignment.Center, false)); - Height += _.Height; - - InputField input = new InputField - ( - 0x0BB8, - 0xFF, - 0xFFF, - true, - Width, - 30 - ) - { X = 0, Y = _.Y + _.Height + 15 }; - Height += input.Height; - Add(input); - - NiceButton button1, button2; - Add(button1 = new NiceButton(0, input.Y + input.Height + 20, Width / 2, 40, ButtonAction.Activate, buttonText) { IsSelectable = false }); - button1.MouseUp += (s, e) => - { - result.Invoke(Result.BUTTON1, input.Text); Dispose(); - }; - - Add(button2 = new NiceButton(Width / 2, input.Y + input.Height + 20, Width / 2, 40, ButtonAction.Activate, button2Text) { IsSelectable = false }); - button2.MouseUp += (s, e) => - { - result.Invoke(Result.BUTTON2, input.Text); Dispose(); - }; - Height += button1.Height + button2.Height; - - bg.Width = Width; - bg.Height = Height; - } - - public enum Result - { - BUTTON1, - BUTTON2 - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/InspectorGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/InspectorGump.cs deleted file mode 100644 index 46b37f1d3..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/InspectorGump.cs +++ /dev/null @@ -1,337 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Linq; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using Microsoft.Xna.Framework; -using SDL2; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class InspectorGump : Gump - { - private const int WIDTH = 500; - private const int HEIGHT = 400; - private readonly GameObject _obj; - - public InspectorGump(GameObject obj) : base(0, 0) - { - X = 200; - Y = 100; - _obj = obj; - CanMove = true; - AcceptMouseInput = false; - CanCloseWithRightClick = true; - - Add - ( - new BorderControl - ( - 0, - 0, - WIDTH, - HEIGHT, - 4 - ) - ); - - Add - ( - new GumpPicTiled - ( - 4, - 4, - WIDTH - 8, - HEIGHT - 8, - 0x0A40 - ) - { - Alpha = 0.5f - } - ); - - Add - ( - new GumpPicTiled - ( - 4, - 4, - WIDTH - 8, - HEIGHT - 8, - 0x0A40 - ) - { - Alpha = 0.5f - } - ); - - Add(new Label(ResGumps.ObjectInformation, true, 1153, font: 3) { X = 20, Y = 10 }); - - Add - ( - new Line - ( - 20, - 30, - WIDTH - 50, - 1, - 0xFFFFFFFF - ) - ); - - Add - ( - new NiceButton - ( - WIDTH - 115, - 5, - 100, - 25, - ButtonAction.Activate, - ResGumps.Dump - ) - { - ButtonParameter = 0 - } - ); - - ScrollArea scrollArea = new ScrollArea - ( - 20, - 35, - WIDTH - 40, - HEIGHT - 45, - true - ) - { - AcceptMouseInput = true - }; - - Add(scrollArea); - - DataBox databox = new DataBox(0, 0, 1, 1); - databox.WantUpdateSize = true; - scrollArea.Add(databox); - - Dictionary dict = GetGameObjectProperties(obj); - - if (dict != null) - { - int startX = 5; - int startY = 5; - - foreach (KeyValuePair item in dict.OrderBy(s => s.Key)) - { - Label label = new Label - ( - item.Key + ":", - true, - 33, - font: 1, - style: FontStyle.BlackBorder - ) - { - X = startX, - Y = startY - }; - - databox.Add(label); - - int height = label.Height; - - label = new Label - ( - item.Value, - true, - 1153, - font: 1, - style: FontStyle.BlackBorder, - maxwidth: WIDTH - 65 - 200 - ) - { - X = startX + 200, - Y = startY, - AcceptMouseInput = true - }; - - label.MouseUp += OnLabelClick; - - if (label.Height > 0) - { - height = label.Height; - } - - databox.Add(label); - - databox.Add - ( - new Line - ( - startX, - startY + height + 2, - WIDTH - 65, - 1, - Color.Gray.PackedValue - ) - ); - - startY += height + 4; - } - } - - //databox.ReArrangeChildren(); - } - - public override void OnButtonClick(int buttonID) - { - if (buttonID == 0) // dump - { - Dictionary dict = GetGameObjectProperties(_obj); - - if (dict != null) - { - using (LogFile writer = new LogFile(CUOEnviroment.ExecutablePath, "dump_gameobject.txt")) - { - writer.Write("###################################################"); - writer.Write($"CUO version: {CUOEnviroment.Version}"); - writer.Write($"OBJECT TYPE: {_obj.GetType()}"); - - foreach (KeyValuePair item in dict.OrderBy(s => s.Key)) - { - writer.Write($"{item.Key} = {item.Value}"); - } - - writer.Write("###################################################"); - writer.Write(""); - } - } - } - } - - private void OnLabelClick(object sender, EventArgs e) - { - Label l = (Label) sender; - - if (l != null) - { - SDL.SDL_SetClipboardText(l.Text); - } - } - - private Dictionary GetGameObjectProperties(GameObject obj) - { - Dictionary dict = new Dictionary(); - - dict["Graphics"] = $"0x{obj.Graphic:X4}"; - dict["Hue"] = $"0x{obj.Hue:X4}"; - dict["Position"] = $"X={obj.X}, Y={obj.Y}, Z={obj.Z}"; - dict["PriorityZ"] = obj.PriorityZ.ToString(); - dict["Distance"] = obj.Distance.ToString(); - dict["AllowedToDraw"] = obj.AllowedToDraw.ToString(); - dict["AlphaHue"] = obj.AlphaHue.ToString(); - - switch (obj) - { - case Mobile mob: - - dict["Serial"] = $"0x{mob.Serial:X8}"; - dict["Flags"] = mob.Flags.ToString(); - dict["Notoriety"] = mob.NotorietyFlag.ToString(); - dict["Title"] = mob.Title ?? string.Empty; - dict["Name"] = mob.Name ?? string.Empty; - dict["HP"] = $"{mob.Hits}/{mob.HitsMax}"; - dict["Mana"] = $"{mob.Mana}/{mob.ManaMax}"; - dict["Stamina"] = $"{mob.Stamina}/{mob.StaminaMax}"; - dict["SpeedMode"] = mob.SpeedMode.ToString(); - dict["Race"] = mob.Race.ToString(); - dict["IsRenamable"] = mob.IsRenamable.ToString(); - dict["Direction"] = mob.Direction.ToString(); - dict["IsDead"] = mob.IsDead.ToString(); - dict["IsDrivingABoat"] = mob.IsDrivingBoat.ToString(); - dict["IsMounted"] = mob.IsMounted.ToString(); - - break; - - case Item it: - - dict["Serial"] = $"0x{it.Serial:X8}"; - dict["Flags"] = it.Flags.ToString(); - dict["HP"] = $"{it.Hits}/{it.HitsMax}"; - dict["IsCoins"] = it.IsCoin.ToString(); - dict["Amount"] = it.Amount.ToString(); - dict["Container"] = it.Container.ToString(); - dict["Layer"] = it.Layer.ToString(); - dict["Price"] = it.Price.ToString(); - dict["Direction"] = it.Direction.ToString(); - dict["IsMulti"] = it.IsMulti.ToString(); - dict["MultiGraphic"] = $"0x{it.MultiGraphic:X4}"; - - break; - - case Static st: - - dict["IsVegetation"] = st.IsVegetation.ToString(); - - break; - - case Multi multi: - - dict["State"] = multi.State.ToString(); - dict["IsMovable"] = multi.IsMovable.ToString(); - - break; - - case Land land: - - dict["IsFlat"] = (!land.IsStretched).ToString(); - dict["NormalLeft"] = land.NormalLeft.ToString(); - dict["NormalRight"] = land.NormalRight.ToString(); - dict["NormalTop"] = land.NormalTop.ToString(); - dict["NormalBottom"] = land.NormalBottom.ToString(); - dict["MinZ"] = land.MinZ.ToString(); - dict["AvgZ"] = land.AverageZ.ToString(); - dict["YOffsets"] = land.YOffsets.ToString(); - - break; - } - - return dict; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/JournalGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/JournalGump.cs deleted file mode 100644 index 3d0e1259e..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/JournalGump.cs +++ /dev/null @@ -1,643 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.IO; -using System.Xml; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using ClassicUO.Utility.Collections; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class JournalGump : Gump - { - private const int _diffY = 22; - private readonly ExpandableScroll _background; - private readonly Checkbox[] _filters_chekboxes = new Checkbox[4]; - private readonly GumpPic _gumpPic; - private readonly HitBox _hitBox; - private bool _isMinimized; - private readonly RenderedTextList _journalEntries; - private readonly ScrollFlag _scrollBar; - - public JournalGump() : base(0, 0) - { - Height = 300; - CanMove = true; - CanCloseWithRightClick = true; - Add(_gumpPic = new GumpPic(160, 0, 0x82D, 0)); - - Add - ( - _background = new ExpandableScroll(0, _diffY, Height - _diffY, 0x1F40) - { - TitleGumpID = 0x82A - } - ); - - const ushort DARK_MODE_JOURNAL_HUE = 903; - - string str = ResGumps.DarkMode; - int width = FontsLoader.Instance.GetWidthASCII(6, str); - - Checkbox darkMode; - - Add - ( - darkMode = new Checkbox - ( - 0x00D2, - 0x00D3, - str, - 6, - 0x0288, - false - ) - { - X = _background.Width - width - 2, - Y = _diffY + 7, - IsChecked = ProfileManager.CurrentProfile.JournalDarkMode - } - ); - - Hue = (ushort) (ProfileManager.CurrentProfile.JournalDarkMode ? DARK_MODE_JOURNAL_HUE : 0); - - darkMode.ValueChanged += (sender, e) => - { - bool ok = ProfileManager.CurrentProfile.JournalDarkMode = !ProfileManager.CurrentProfile.JournalDarkMode; - Hue = (ushort) (ok ? DARK_MODE_JOURNAL_HUE : 0); - }; - - _scrollBar = new ScrollFlag(-25, _diffY + 36, Height - _diffY, true); - - Add - ( - _journalEntries = new RenderedTextList - ( - 25, - _diffY + 36, - _background.Width - (_scrollBar.Width >> 1) - 5, - 200, - _scrollBar - ) - ); - - Add(_scrollBar); - - Add(_hitBox = new HitBox(160, 0, 23, 24)); - _hitBox.MouseUp += _hitBox_MouseUp; - _gumpPic.MouseDoubleClick += _gumpPic_MouseDoubleClick; - - int cx = 43; // 63 - int dist = 75; // 85 - byte font = 6; // 1 - - _filters_chekboxes[0] = new Checkbox - ( - 0x00D2, - 0x00D3, - "System", - font, - 0x0386, - false - ) - { - X = cx, - LocalSerial = 1, - IsChecked = ProfileManager.CurrentProfile.ShowJournalSystem - }; - - _filters_chekboxes[1] = new Checkbox - ( - 0x00D2, - 0x00D3, - "Objects", - font, - 0x0386, - false - ) - { - X = cx + dist, - LocalSerial = 2, - IsChecked = ProfileManager.CurrentProfile.ShowJournalObjects - }; - - _filters_chekboxes[2] = new Checkbox - ( - 0x00D2, - 0x00D3, - "Client", - font, - 0x0386, - false - ) - { - X = cx + dist * 2, - LocalSerial = 0, - IsChecked = ProfileManager.CurrentProfile.ShowJournalClient - }; - - _filters_chekboxes[3] = new Checkbox - ( - 0x00D2, - 0x00D3, - "Guild", - font, - 0x0386, - false - ) - { - X = cx + dist * 3, - LocalSerial = 3, - IsChecked = ProfileManager.CurrentProfile.ShowJournalGuildAlly - }; - - void on_check_box(object sender, EventArgs e) - { - Checkbox c = (Checkbox) sender; - - if (c != null) - { - switch ((TextType) c.LocalSerial) - { - case TextType.CLIENT: - ProfileManager.CurrentProfile.ShowJournalClient = c.IsChecked; - - break; - - case TextType.SYSTEM: - ProfileManager.CurrentProfile.ShowJournalSystem = c.IsChecked; - - break; - - case TextType.OBJECT: - ProfileManager.CurrentProfile.ShowJournalObjects = c.IsChecked; - - break; - - case TextType.GUILD_ALLY: - ProfileManager.CurrentProfile.ShowJournalGuildAlly = c.IsChecked; - - break; - } - } - } - - for (int i = 0; i < _filters_chekboxes.Length; i++) - { - _filters_chekboxes[i].ValueChanged += on_check_box; - - Add(_filters_chekboxes[i]); - } - - InitializeJournalEntries(); - EventSink.JournalEntryAdded += AddJournalEntry; - } - - public override GumpType GumpType => GumpType.Journal; - - public ushort Hue - { - get => _background.Hue; - set => _background.Hue = value; - } - - public bool IsMinimized - { - get => _isMinimized; - set - { - if (_isMinimized != value) - { - _isMinimized = value; - - _gumpPic.Graphic = value ? (ushort) 0x830 : (ushort) 0x82D; - - if (value) - { - _gumpPic.X = 0; - } - else - { - _gumpPic.X = 160; - } - - foreach (Control c in Children) - { - c.IsVisible = !value; - } - - _gumpPic.IsVisible = true; - WantUpdateSize = true; - } - } - } - - protected override void OnMouseWheel(MouseEventType delta) - { - _scrollBar.InvokeMouseWheel(delta); - } - - - public override void Dispose() - { - EventSink.JournalEntryAdded -= AddJournalEntry; - base.Dispose(); - } - - public override void Update() - { - base.Update(); - - WantUpdateSize = true; - _journalEntries.Height = Height - (98 + _diffY); - - for (int i = 0; i < _filters_chekboxes.Length; i++) - { - _filters_chekboxes[i].Y = _background.Height - _filters_chekboxes[i].Height - _diffY + 10; - } - } - - private void AddJournalEntry(object sender, JournalEntry entry) - { - var usrSend = entry.Name != string.Empty ? $"{entry.Name}" : string.Empty; - - // Check if ignored person - if (!string.IsNullOrEmpty(usrSend) && IgnoreManager.IgnoredCharsList.Contains(usrSend)) - return; - - string text = $"{usrSend}: {entry.Text}"; - - if (string.IsNullOrEmpty(usrSend)) - { - text = entry.Text; - } - - _journalEntries.AddEntry - ( - text, - entry.Font, - entry.Hue, - entry.IsUnicode, - entry.Time, - entry.TextType - ); - } - - public override void Save(XmlTextWriter writer) - { - base.Save(writer); - writer.WriteAttributeString("height", _background.SpecialHeight.ToString()); - writer.WriteAttributeString("isminimized", IsMinimized.ToString()); - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - - _background.Height = _background.SpecialHeight = int.Parse(xml.GetAttribute("height")); - IsMinimized = bool.Parse(xml.GetAttribute("isminimized")); - } - - private void InitializeJournalEntries() - { - foreach (JournalEntry t in JournalManager.Entries) - { - AddJournalEntry(null, t); - } - - _scrollBar.MinValue = 0; - } - - private void _gumpPic_MouseDoubleClick(object sender, MouseDoubleClickEventArgs e) - { - if (e.Button == MouseButtonType.Left && IsMinimized) - { - IsMinimized = false; - e.Result = true; - } - } - - private void _hitBox_MouseUp(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtonType.Left && !IsMinimized) - { - IsMinimized = true; - } - } - - - private class RenderedTextList : Control - { - private readonly Deque _entries, _hours; - private readonly ScrollBarBase _scrollBar; - private readonly Deque _text_types; - - public RenderedTextList(int x, int y, int width, int height, ScrollBarBase scrollBarControl) - { - _scrollBar = scrollBarControl; - _scrollBar.IsVisible = false; - AcceptMouseInput = true; - CanMove = true; - X = x; - Y = y; - Width = width; - Height = height; - - _entries = new Deque(); - _hours = new Deque(); - _text_types = new Deque(); - - WantUpdateSize = false; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - int mx = x; - int my = y; - - int height = 0; - int maxheight = _scrollBar.Value + _scrollBar.Height; - - for (int i = 0; i < _entries.Count; i++) - { - RenderedText t = _entries[i]; - RenderedText hour = _hours[i]; - TextType type = _text_types[i]; - - - if (!CanBeDrawn(type)) - { - continue; - } - - - if (height + t.Height <= _scrollBar.Value) - { - // this entry is above the renderable area. - height += t.Height; - } - else if (height + t.Height <= maxheight) - { - int yy = height - _scrollBar.Value; - - if (yy < 0) - { - // this entry starts above the renderable area, but exists partially within it. - hour.Draw - ( - batcher, - hour.Width, - hour.Height, - mx, - y, - t.Width, - t.Height + yy, - 0, - -yy - ); - - t.Draw - ( - batcher, - t.Width, - t.Height, - mx + hour.Width, - y, - t.Width, - t.Height + yy, - 0, - -yy - ); - - my += t.Height + yy; - } - else - { - // this entry is completely within the renderable area. - hour.Draw(batcher, mx, my); - t.Draw(batcher, mx + hour.Width, my); - my += t.Height; - } - - height += t.Height; - } - else - { - int yyy = maxheight - height; - - hour.Draw - ( - batcher, - hour.Width, - hour.Height, - mx, - y + _scrollBar.Height - yyy, - t.Width, - yyy, - 0, - 0 - ); - - t.Draw - ( - batcher, - t.Width, - t.Height, - mx + hour.Width, - y + _scrollBar.Height - yyy, - t.Width, - yyy, - 0, - 0 - ); - - // can't fit any more entries - so we break! - break; - } - } - - return true; - } - - public override void Update() - { - base.Update(); - - if (!IsVisible) - { - return; - } - - _scrollBar.X = X + Width - (_scrollBar.Width >> 1) + 5; - _scrollBar.Height = Height; - CalculateScrollBarMaxValue(); - _scrollBar.IsVisible = _scrollBar.MaxValue > _scrollBar.MinValue; - } - - private void CalculateScrollBarMaxValue() - { - bool maxValue = _scrollBar.Value == _scrollBar.MaxValue; - int height = 0; - - for (int i = 0; i < _entries.Count; i++) - { - if (i < _text_types.Count && CanBeDrawn(_text_types[i])) - { - height += _entries[i].Height; - } - } - - height -= _scrollBar.Height; - - if (height > 0) - { - _scrollBar.MaxValue = height; - - if (maxValue) - { - _scrollBar.Value = _scrollBar.MaxValue; - } - } - else - { - _scrollBar.MaxValue = 0; - _scrollBar.Value = 0; - } - } - - public void AddEntry - ( - string text, - int font, - ushort hue, - bool isUnicode, - DateTime time, - TextType text_type - ) - { - bool maxScroll = _scrollBar.Value == _scrollBar.MaxValue; - - while (_entries.Count > 199) - { - _entries.RemoveFromFront().Destroy(); - - _hours.RemoveFromFront().Destroy(); - - _text_types.RemoveFromFront(); - } - - RenderedText h = RenderedText.Create - ( - $"{time:t} ", - 1150, - 1, - true, - FontStyle.BlackBorder - ); - - _hours.AddToBack(h); - - RenderedText rtext = RenderedText.Create - ( - text, - hue, - (byte) font, - isUnicode, - FontStyle.Indention | FontStyle.BlackBorder, - maxWidth: Width - (18 + h.Width) - ); - - _entries.AddToBack(rtext); - - _text_types.AddToBack(text_type); - - _scrollBar.MaxValue += rtext.Height; - - if (maxScroll) - { - _scrollBar.Value = _scrollBar.MaxValue; - } - } - - private static bool CanBeDrawn(TextType type) - { - if (type == TextType.CLIENT && !ProfileManager.CurrentProfile.ShowJournalClient) - { - return false; - } - - if (type == TextType.SYSTEM && !ProfileManager.CurrentProfile.ShowJournalSystem) - { - return false; - } - - if (type == TextType.OBJECT && !ProfileManager.CurrentProfile.ShowJournalObjects) - { - return false; - } - - if (type == TextType.GUILD_ALLY && !ProfileManager.CurrentProfile.ShowJournalGuildAlly) - { - return false; - } - - return true; - } - - public override void Dispose() - { - for (int i = 0; i < _entries.Count; i++) - { - _entries[i].Destroy(); - - _hours[i].Destroy(); - } - - _entries.Clear(); - _hours.Clear(); - _text_types.Clear(); - - base.Dispose(); - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/Login/CharacterSelectionGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/Login/CharacterSelectionGump.cs deleted file mode 100644 index a357400e9..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/Login/CharacterSelectionGump.cs +++ /dev/null @@ -1,384 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Linq; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Resources; -using ClassicUO.Utility; -using SDL2; - -namespace ClassicUO.Game.UI.Gumps.Login -{ - internal class CharacterSelectionGump : Gump - { - private const ushort SELECTED_COLOR = 0x0021; - private const ushort NORMAL_COLOR = 0x034F; - private uint _selectedCharacter; - - public CharacterSelectionGump() : base(0, 0) - { - CanCloseWithRightClick = false; - - int posInList = 0; - int yOffset = 150; - int yBonus = 0; - int listTitleY = 106; - - LoginScene loginScene = Client.Game.GetScene(); - - string lastCharName = LastCharacterManager.GetLastCharacter(LoginScene.Account, World.ServerName); - string lastSelected = loginScene.Characters.FirstOrDefault(o => o == lastCharName); - - LockedFeatureFlags f = World.ClientLockedFeatures.Flags; - CharacterListFlags ff = World.ClientFeatures.Flags; - - if (Client.Version >= ClientVersion.CV_6040 || Client.Version >= ClientVersion.CV_5020 && loginScene.Characters.Length > 5) - { - listTitleY = 96; - yOffset = 125; - yBonus = 45; - } - - if (!string.IsNullOrEmpty(lastSelected)) - { - _selectedCharacter = (uint) Array.IndexOf(loginScene.Characters, lastSelected); - } - else if (loginScene.Characters.Length > 0) - { - _selectedCharacter = 0; - } - - Add - ( - new ResizePic(0x0A28) - { - X = 160, Y = 70, Width = 408, Height = 343 + yBonus - }, - 1 - ); - - bool isAsianLang = string.Compare(Settings.GlobalSettings.Language, "CHT", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "KOR", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "JPN", StringComparison.InvariantCultureIgnoreCase) == 0; - - bool unicode = isAsianLang; - byte font = (byte)(isAsianLang ? 1 : 2); - ushort hue = (ushort)(isAsianLang ? 0xFFFF : 0x0386); - - Add - ( - new Label(ClilocLoader.Instance.GetString(3000050, "Character Selection"), unicode, hue, font: font) - { - X = 267, Y = listTitleY - }, - 1 - ); - - for (int i = 0, valid = 0; i < loginScene.Characters.Length; i++) - { - string character = loginScene.Characters[i]; - - if (!string.IsNullOrEmpty(character)) - { - valid++; - - if (valid > World.ClientFeatures.MaxChars) - { - break; - } - - if (World.ClientLockedFeatures.Flags != 0 && !World.ClientLockedFeatures.Flags.HasFlag(LockedFeatureFlags.SeventhCharacterSlot)) - { - if (valid == 6 && !World.ClientLockedFeatures.Flags.HasFlag(LockedFeatureFlags.SixthCharacterSlot)) - { - break; - } - } - - Add - ( - new CharacterEntryGump((uint) i, character, SelectCharacter, LoginCharacter) - { - X = 224, - Y = yOffset + posInList * 40, - Hue = i == _selectedCharacter ? SELECTED_COLOR : NORMAL_COLOR - }, - 1 - ); - - posInList++; - } - } - - if (CanCreateChar(loginScene)) - { - Add - ( - new Button((int) Buttons.New, 0x159D, 0x159F, 0x159E) - { - X = 224, Y = 350 + yBonus, ButtonAction = ButtonAction.Activate - }, - 1 - ); - } - - Add - ( - new Button((int) Buttons.Delete, 0x159A, 0x159C, 0x159B) - { - X = 442, - Y = 350 + yBonus, - ButtonAction = ButtonAction.Activate - }, - 1 - ); - - Add - ( - new Button((int) Buttons.Prev, 0x15A1, 0x15A3, 0x15A2) - { - X = 586, Y = 445, ButtonAction = ButtonAction.Activate - }, - 1 - ); - - Add - ( - new Button((int) Buttons.Next, 0x15A4, 0x15A6, 0x15A5) - { - X = 610, Y = 445, ButtonAction = ButtonAction.Activate - }, - 1 - ); - - AcceptKeyboardInput = true; - ChangePage(1); - } - - private bool CanCreateChar(LoginScene scene) - { - if (scene.Characters != null) - { - int empty = scene.Characters.Count(string.IsNullOrEmpty); - - if (empty >= 0 && scene.Characters.Length - empty < World.ClientFeatures.MaxChars) - { - return true; - } - } - - return false; - } - - protected override void OnKeyDown(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - if (key == SDL.SDL_Keycode.SDLK_RETURN || key == SDL.SDL_Keycode.SDLK_KP_ENTER) - { - LoginCharacter(_selectedCharacter); - } - } - - public override void OnButtonClick(int buttonID) - { - LoginScene loginScene = Client.Game.GetScene(); - - switch ((Buttons) buttonID) - { - case Buttons.Delete: - DeleteCharacter(loginScene); - - break; - - case Buttons.New when CanCreateChar(loginScene): - loginScene.StartCharCreation(); - - break; - - case Buttons.Next: - LoginCharacter(_selectedCharacter); - - break; - - case Buttons.Prev: - loginScene.StepBack(); - - break; - } - - base.OnButtonClick(buttonID); - } - - private void DeleteCharacter(LoginScene loginScene) - { - string charName = loginScene.Characters[_selectedCharacter]; - - if (!string.IsNullOrEmpty(charName)) - { - LoadingGump existing = Children.OfType().FirstOrDefault(); - - if (existing != null) - { - Remove(existing); - } - - Add - ( - new LoadingGump - ( - string.Format(ResGumps.PermanentlyDelete0, charName), - LoginButtons.OK | LoginButtons.Cancel, - buttonID => - { - if (buttonID == (int) LoginButtons.OK) - { - loginScene.DeleteCharacter(_selectedCharacter); - } - else - { - ChangePage(1); - } - } - ), - 2 - ); - - ChangePage(2); - } - } - - private void SelectCharacter(uint index) - { - _selectedCharacter = index; - - foreach (CharacterEntryGump characterGump in FindControls()) - { - characterGump.Hue = characterGump.CharacterIndex == index ? SELECTED_COLOR : NORMAL_COLOR; - } - } - - private void LoginCharacter(uint index) - { - LoginScene loginScene = Client.Game.GetScene(); - - if (loginScene.Characters != null && loginScene.Characters.Length > index && !string.IsNullOrEmpty(loginScene.Characters[index])) - { - loginScene.SelectCharacter(index); - } - } - - private enum Buttons - { - New, - Delete, - Next, - Prev - } - - private class CharacterEntryGump : Control - { - private readonly Label _label; - private readonly Action _loginFn; - private readonly Action _selectedFn; - - public CharacterEntryGump(uint index, string character, Action selectedFn, Action loginFn) - { - CharacterIndex = index; - _selectedFn = selectedFn; - _loginFn = loginFn; - - // Bg - Add - ( - new ResizePic(0x0BB8) - { - X = 0, Y = 0, Width = 280, Height = 30 - } - ); - - // Char Name - Add - ( - _label = new Label - ( - character, - false, - NORMAL_COLOR, - 270, - 5, - align: TEXT_ALIGN_TYPE.TS_CENTER - ) - { - X = 0 - } - ); - - AcceptMouseInput = true; - } - - public uint CharacterIndex { get; } - - public ushort Hue - { - get => _label.Hue; - set => _label.Hue = value; - } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - _loginFn(CharacterIndex); - - return true; - } - - return false; - } - - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - _selectedFn(CharacterIndex); - } - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/Login/LoadingGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/Login/LoadingGump.cs deleted file mode 100644 index 001d6b8e4..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/Login/LoadingGump.cs +++ /dev/null @@ -1,154 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Configuration; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Assets; -using SDL2; - -namespace ClassicUO.Game.UI.Gumps.Login -{ - [Flags] - internal enum LoginButtons - { - None = 1, - OK = 2, - Cancel = 4 - } - - internal class LoadingGump : Gump - { - private readonly Action _buttonClick; - private readonly Label _label; - - public LoadingGump(string labelText, LoginButtons showButtons, Action buttonClick = null) : base(0, 0) - { - _buttonClick = buttonClick; - CanCloseWithRightClick = false; - CanCloseWithEsc = false; - - bool isAsianLang = string.Compare(Settings.GlobalSettings.Language, "CHT", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "KOR", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "JPN", StringComparison.InvariantCultureIgnoreCase) == 0; - - bool unicode = isAsianLang; - byte font = (byte)(isAsianLang ? 1 : 2); - ushort hue = (ushort)(isAsianLang ? 0xFFFF : 0x0386); - - _label = new Label - ( - labelText, - unicode, - hue, - 326, - font, - align: TEXT_ALIGN_TYPE.TS_CENTER - ) - { - X = 162, - Y = 178 - }; - - Add - ( - new ResizePic(0x0A28) - { - X = 142, Y = 134, Width = 366, Height = 212 - } - ); - - Add(_label); - - if (showButtons == LoginButtons.OK) - { - Add - ( - new Button((int) LoginButtons.OK, 0x0481, 0x0483, 0x0482) - { - X = 306, Y = 304, ButtonAction = ButtonAction.Activate - } - ); - } - else if (showButtons == LoginButtons.Cancel) - { - Add - ( - new Button((int) LoginButtons.Cancel, 0x047E, 0x0480, 0x047F) - { - X = 306, - Y = 304, - ButtonAction = ButtonAction.Activate - } - ); - } - else if (showButtons == (LoginButtons.OK | LoginButtons.Cancel)) - { - Add - ( - new Button((int) LoginButtons.OK, 0x0481, 0x0483, 0x0482) - { - X = 264, Y = 304, ButtonAction = ButtonAction.Activate - } - ); - - Add - ( - new Button((int) LoginButtons.Cancel, 0x047E, 0x0480, 0x047F) - { - X = 348, Y = 304, ButtonAction = ButtonAction.Activate - } - ); - } - } - - public void SetText(string text) - { - _label.Text = text; - } - - protected override void OnKeyDown(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - if (key == SDL.SDL_Keycode.SDLK_KP_ENTER || key == SDL.SDL_Keycode.SDLK_RETURN) - { - OnButtonClick((int) LoginButtons.OK); - } - } - - - public override void OnButtonClick(int buttonID) - { - _buttonClick?.Invoke(buttonID); - base.OnButtonClick(buttonID); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/Login/LoginBackground.cs b/src/ClassicUO.Client/Game/UI/Gumps/Login/LoginBackground.cs deleted file mode 100644 index 2916ae9a3..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/Login/LoginBackground.cs +++ /dev/null @@ -1,107 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.UI.Controls; -using ClassicUO.Utility; - -namespace ClassicUO.Game.UI.Gumps.Login -{ - internal class LoginBackground : Gump - { - public LoginBackground() : base(0, 0) - { - if (Client.Version >= ClientVersion.CV_706400) - { - // Background - Add - ( - new GumpPicTiled - ( - 0, - 0, - 640, - 480, - 0x0150 - ) { AcceptKeyboardInput = false } - ); - - // UO Flag - Add(new GumpPic(0, 4, 0x0151, 0) { AcceptKeyboardInput = false }); - } - else - { - // Background - Add - ( - new GumpPicTiled - ( - 0, - 0, - 640, - 480, - 0x0E14 - ) { AcceptKeyboardInput = false } - ); - - // Border - Add(new GumpPic(0, 0, 0x157C, 0) { AcceptKeyboardInput = false }); - // UO Flag - Add(new GumpPic(0, 4, 0x15A0, 0) { AcceptKeyboardInput = false }); - - // Quit Button - Add - ( - new Button(0, 0x1589, 0x158B, 0x158A) - { - X = 555, - Y = 4, - ButtonAction = ButtonAction.Activate, - AcceptKeyboardInput = false - } - ); - } - - - CanCloseWithEsc = false; - CanCloseWithRightClick = false; - AcceptKeyboardInput = false; - - LayerOrder = UILayer.Under; - } - - - public override void OnButtonClick(int buttonID) - { - Client.Game.Exit(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/Login/LoginGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/Login/LoginGump.cs deleted file mode 100644 index fecd29c13..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/Login/LoginGump.cs +++ /dev/null @@ -1,814 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using SDL2; -using System.Collections.Generic; - -namespace ClassicUO.Game.UI.Gumps.Login -{ - internal class LoginGump : Gump - { - private readonly ushort _buttonNormal; - private readonly ushort _buttonOver; - private readonly Checkbox _checkboxAutologin; - private readonly Checkbox _checkboxSaveAccount; - private readonly Button _nextArrow0; - private readonly PasswordStbTextBox _passwordFake; - private readonly StbTextBox _textboxAccount; - - private float _time; - - public LoginGump(LoginScene scene) : base(0, 0) - { - CanCloseWithRightClick = false; - - AcceptKeyboardInput = false; - - int offsetX, offsetY, offtextY; - byte font; - ushort hue; - - if (Client.Version < ClientVersion.CV_706400) - { - _buttonNormal = 0x15A4; - _buttonOver = 0x15A5; - const ushort HUE = 0x0386; - - if (Client.Version >= ClientVersion.CV_500A) - { - Add(new GumpPic(0, 0, 0x2329, 0)); - } - - //UO Flag - Add(new GumpPic(0, 4, 0x15A0, 0) { AcceptKeyboardInput = false }); - - // Quit Button - Add - ( - new Button((int)Buttons.Quit, 0x1589, 0x158B, 0x158A) - { - X = 555, - Y = 4, - ButtonAction = ButtonAction.Activate - } - ); - - //Login Panel - Add - ( - new ResizePic(0x13BE) - { - X = 128, - Y = 288, - Width = 451, - Height = 157 - } - ); - - if (Client.Version < ClientVersion.CV_500A) - { - Add(new GumpPic(286, 45, 0x058A, 0)); - } - - // Credits - Add - ( - new Button((int)Buttons.Credits, 0x1583, 0x1585, 0x1584) - { - X = 60, - Y = 385, - ButtonAction = ButtonAction.Activate - } - ); - - Add - ( - new Label(ResGumps.LoginToUO, false, HUE, font: 2) - { - X = 253, - Y = 305 - } - ); - - Add - ( - new Label(ResGumps.Account, false, HUE, font: 2) - { - X = 183, - Y = 345 - } - ); - - Add - ( - new Label(ResGumps.Password, false, HUE, font: 2) - { - X = 183, - Y = 385 - } - ); - - // Arrow Button - Add - ( - _nextArrow0 = new Button((int)Buttons.NextArrow, 0x15A4, 0x15A6, 0x15A5) - { - X = 610, - Y = 445, - ButtonAction = ButtonAction.Activate - } - ); - - - offsetX = 328; - offsetY = 343; - offtextY = 40; - - Add - ( - new Label($"UO Version {Settings.GlobalSettings.ClientVersion}.", false, 0x034E, font: 9) - { - X = 286, - Y = 453 - } - ); - - Add - ( - new Label(string.Format("TazUO Version {0}", CUOEnviroment.Version), false, 0x034E, font: 9) - { - X = 286, - Y = 465 - } - ); - - - Add - ( - _checkboxAutologin = new Checkbox - ( - 0x00D2, - 0x00D3, - ResGumps.Autologin, - 1, - 0x0386, - false - ) - { - X = 150, - Y = 417 - } - ); - - Add - ( - _checkboxSaveAccount = new Checkbox - ( - 0x00D2, - 0x00D3, - ResGumps.SaveAccount, - 1, - 0x0386, - false - ) - { - X = _checkboxAutologin.X + _checkboxAutologin.Width + 10, - Y = 417 - } - ); - - font = 1; - hue = 0x0386; - } - else - { - _buttonNormal = 0x5CD; - _buttonOver = 0x5CB; - - Add(new GumpPic(0, 0, 0x014E, 0)); - - //// Quit Button - Add - ( - new Button((int)Buttons.Quit, 0x05CA, 0x05C9, 0x05C8) - { - X = 25, - Y = 240, - ButtonAction = ButtonAction.Activate - } - ); - - //// Credit Button - Add - ( - new Button((int)Buttons.Credits, 0x05D0, 0x05CF, 0x5CE) - { - X = 530, - Y = 125, - ButtonAction = ButtonAction.Activate - } - ); - - // Arrow Button - Add - ( - _nextArrow0 = new Button((int)Buttons.NextArrow, 0x5CD, 0x5CC, 0x5CB) - { - X = 280, - Y = 365, - ButtonAction = ButtonAction.Activate - } - ); - - offsetX = 218; - offsetY = 283; - offtextY = 50; - - - Add - ( - new Label($"UO Version {Settings.GlobalSettings.ClientVersion}.", false, 0x0481, font: 9) - { - X = 286, - Y = 453 - } - ); - - Add - ( - new Label(string.Format("TazUO Version {0}", CUOEnviroment.Version), false, 0x0481, font: 9) - { - X = 286, - Y = 465 - } - ); - - - Add - ( - _checkboxAutologin = new Checkbox - ( - 0x00D2, - 0x00D3, - ResGumps.Autologin, - 9, - 0x0481, - false - ) - { - X = 150, - Y = 417 - } - ); - - Add - ( - _checkboxSaveAccount = new Checkbox - ( - 0x00D2, - 0x00D3, - ResGumps.SaveAccount, - 9, - 0x0481, - false - ) - { - X = _checkboxAutologin.X + _checkboxAutologin.Width + 10, - Y = 417 - } - ); - - font = 9; - hue = 0x0481; - } - - - // Account Text Input Background - Add - ( - new ResizePic(0x0BB8) - { - X = offsetX, - Y = offsetY, - Width = 210, - Height = 30 - } - ); - - // Password Text Input Background - Add - ( - new ResizePic(0x0BB8) - { - X = offsetX, - Y = offsetY + offtextY, - Width = 210, - Height = 30 - } - ); - - offsetX += 7; - - // Text Inputs - Add - ( - _textboxAccount = new StbTextBox - ( - 5, - 16, - 190, - false, - hue: 0x034F - ) - { - X = offsetX, - Y = offsetY, - Width = 190, - Height = 25 - } - ); - - _textboxAccount.SetText(Settings.GlobalSettings.Username); - - Add - ( - _passwordFake = new PasswordStbTextBox - ( - 5, - 16, - 190, - false, - hue: 0x034F - ) - { - X = offsetX, - Y = offsetY + offtextY + 2, - Width = 190, - Height = 25 - } - ); - - string[] accts = SimpleAccountManager.GetAccounts(); - if (accts.Length > 0) - { - _textboxAccount.ContextMenu = new ContextMenuControl(); - foreach (string acct in accts) - { - _textboxAccount.ContextMenu.Add(new ContextMenuItemEntry(acct, () => { _textboxAccount.SetText(acct); })); - } - _textboxAccount.SetTooltip("Right click to select another account."); - _textboxAccount.MouseUp += (s, e) => { if (e.Button == MouseButtonType.Right) _textboxAccount.ContextMenu.Show(); }; - } - - _passwordFake.RealText = Crypter.Decrypt(Settings.GlobalSettings.Password); - - _checkboxSaveAccount.IsChecked = Settings.GlobalSettings.SaveAccount; - _checkboxAutologin.IsChecked = Settings.GlobalSettings.AutoLogin; - - - Add - ( - new HtmlControl - ( - 505, - 420, - 150, - 15, - false, - false, - false, - "Support ClassicUO!", - 0x32, - true, - isunicode: true, - style: FontStyle.BlackBorder - ) - ); - - - Add - ( - new HtmlControl - ( - 505, - 440, - 100, - 15, - false, - false, - false, - "Website", - 0x32, - true, - isunicode: true, - style: FontStyle.BlackBorder - ) - ); - - Add - ( - new HtmlControl - ( - 505, - 460, - 100, - 15, - false, - false, - false, - "Join Discord", - 0x32, - true, - isunicode: true, - style: FontStyle.BlackBorder - ) - ); - - TextBox _; - HitBox _hit; - Add(_ = new TextBox("TazUO Wiki", TrueTypeLoader.EMBEDDED_FONT, 15, 200, Color.Orange, strokeEffect: false) { X = 30, Y = 420, AcceptMouseInput = true }); - Add(_hit = new HitBox(_.X, _.Y, _.MeasuredSize.X, _.MeasuredSize.Y)); - _hit.MouseUp += (s, e) => - { - Utility.Platforms.PlatformHelper.LaunchBrowser("https://github.com/bittiez/ClassicUO/wiki"); - }; - - Add(_ = new TextBox("TazUO Discord", TrueTypeLoader.EMBEDDED_FONT, 15, 200, Color.Orange, strokeEffect: false) { X = 30, Y = 440, AcceptMouseInput = true }); - Add(_hit = new HitBox(_.X, _.Y, _.MeasuredSize.X, _.MeasuredSize.Y)); - _hit.MouseUp += (s, e) => - { - Utility.Platforms.PlatformHelper.LaunchBrowser("https://discord.gg/SqwtB5g95H"); - }; - - Checkbox loginmusic_checkbox = new Checkbox - ( - 0x00D2, - 0x00D3, - "Music", - font, - hue, - false - ) - { - X = _checkboxSaveAccount.X + _checkboxSaveAccount.Width + 10, - Y = 417, - IsChecked = Settings.GlobalSettings.LoginMusic - }; - - Add(loginmusic_checkbox); - - HSliderBar login_music = new HSliderBar - ( - loginmusic_checkbox.X + loginmusic_checkbox.Width + 10, - loginmusic_checkbox.Y + 4, - 80, - 0, - 100, - Settings.GlobalSettings.LoginMusicVolume, - HSliderBarStyle.MetalWidgetRecessedBar, - true, - font, - hue, - false - ); - - Add(login_music); - login_music.IsVisible = Settings.GlobalSettings.LoginMusic; - - loginmusic_checkbox.ValueChanged += (sender, e) => - { - Settings.GlobalSettings.LoginMusic = loginmusic_checkbox.IsChecked; - Client.Game.Audio.UpdateCurrentMusicVolume(true); - - login_music.IsVisible = Settings.GlobalSettings.LoginMusic; - }; - - login_music.ValueChanged += (sender, e) => - { - Settings.GlobalSettings.LoginMusicVolume = login_music.Value; - Client.Game.Audio.UpdateCurrentMusicVolume(true); - }; - - - if (!string.IsNullOrEmpty(_textboxAccount.Text)) - { - _passwordFake.SetKeyboardFocus(); - } - else - { - _textboxAccount.SetKeyboardFocus(); - } - - _ = new TextBox("A new version of TazUO is available!\n Click to open the download page.", TrueTypeLoader.EMBEDDED_FONT, 20, 300, Color.Yellow, strokeEffect: false) { X = 10, Y = 10, AcceptMouseInput = false }; - Add(_hit = new HitBox(_.X, _.Y, _.MeasuredSize.X, _.MeasuredSize.Y)); - _hit.MouseUp += (s, e) => - { - Utility.Platforms.PlatformHelper.LaunchBrowser("https://github.com/bittiez/TazUO/releases/latest"); - }; - _hit.Add(new AlphaBlendControl() { Width = _hit.Width, Height = _hit.Height }); - Add(_); - if (!UpdateManager.HasUpdate) - { - _.IsVisible = false; - _hit.IsVisible = false; - } - - if (!UpdateManager.SkipUpdateCheck) - { - UpdateManager.UpdateStatusChanged += (s, e) => - { - if (UpdateManager.HasUpdate) - { - _.IsVisible = true; - _hit.IsVisible = true; - } - }; - } - - } - - public override void OnKeyboardReturn(int textID, string text) - { - SaveCheckboxStatus(); - LoginScene ls = Client.Game.GetScene(); - - if (ls.CurrentLoginStep == LoginSteps.Main) - { - ls.Connect(_textboxAccount.Text, _passwordFake.RealText); - } - } - - private void SaveCheckboxStatus() - { - Settings.GlobalSettings.SaveAccount = _checkboxSaveAccount.IsChecked; - Settings.GlobalSettings.AutoLogin = _checkboxAutologin.IsChecked; - } - - public override void Update() - { - if (IsDisposed) - { - return; - } - - base.Update(); - - if (_time < Time.Ticks) - { - _time = (float)Time.Ticks + 1000; - - _nextArrow0.ButtonGraphicNormal = _nextArrow0.ButtonGraphicNormal == _buttonNormal ? _buttonOver : _buttonNormal; - } - - if (_passwordFake.HasKeyboardFocus) - { - if (_passwordFake.Hue != 0x0021) - { - _passwordFake.Hue = 0x0021; - } - } - else if (_passwordFake.Hue != 0) - { - _passwordFake.Hue = 0; - } - - if (_textboxAccount.HasKeyboardFocus) - { - if (_textboxAccount.Hue != 0x0021) - { - _textboxAccount.Hue = 0x0021; - } - } - else if (_textboxAccount.Hue != 0) - { - _textboxAccount.Hue = 0; - } - } - - public override void OnButtonClick(int buttonID) - { - switch ((Buttons)buttonID) - { - case Buttons.NextArrow: - SaveCheckboxStatus(); - - if (!_textboxAccount.IsDisposed) - { - Client.Game.GetScene().Connect(_textboxAccount.Text, _passwordFake.RealText); - } - - break; - - case Buttons.Quit: - Client.Game.Exit(); - - break; - - case Buttons.Credits: - UIManager.Add(new CreditsGump()); - - break; - } - } - - private class PasswordStbTextBox : StbTextBox - { - private new Point _caretScreenPosition; - private new readonly RenderedText _rendererCaret; - - private new readonly RenderedText _rendererText; - - public PasswordStbTextBox - ( - byte font, - int max_char_count = -1, - int maxWidth = 0, - bool isunicode = true, - FontStyle style = FontStyle.None, - ushort hue = 0, - TEXT_ALIGN_TYPE align = TEXT_ALIGN_TYPE.TS_LEFT - ) : base - ( - font, - max_char_count, - maxWidth, - isunicode, - style, - hue, - align - ) - { - _rendererText = RenderedText.Create - ( - string.Empty, - hue, - font, - isunicode, - style, - align, - maxWidth - ); - - _rendererCaret = RenderedText.Create - ( - "_", - hue, - font, - isunicode, - (style & FontStyle.BlackBorder) != 0 ? FontStyle.BlackBorder : FontStyle.None, - align - ); - - NoSelection = true; - } - - internal string RealText - { - get => Text; - set => SetText(value); - } - - public new ushort Hue - { - get => _rendererText.Hue; - set - { - if (_rendererText.Hue != value) - { - _rendererText.Hue = value; - _rendererCaret.Hue = value; - - _rendererText.CreateTexture(); - _rendererCaret.CreateTexture(); - } - } - } - - protected override void DrawCaret(UltimaBatcher2D batcher, int x, int y) - { - if (HasKeyboardFocus) - { - _rendererCaret.Draw(batcher, x + _caretScreenPosition.X, y + _caretScreenPosition.Y); - } - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - base.OnMouseDown(x, y, button); - - if (button == MouseButtonType.Left) - { - UpdateCaretScreenPosition(); - } - } - - protected override void OnKeyDown(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - base.OnKeyDown(key, mod); - UpdateCaretScreenPosition(); - } - - public override void Dispose() - { - _rendererText?.Destroy(); - _rendererCaret?.Destroy(); - - base.Dispose(); - } - - protected override void OnTextInput(string c) - { - base.OnTextInput(c); - } - - protected override void OnTextChanged() - { - if (Text.Length > 0) - { - _rendererText.Text = new string('*', Text.Length); - } - else - { - _rendererText.Text = string.Empty; - } - - base.OnTextChanged(); - UpdateCaretScreenPosition(); - } - - internal override void OnFocusEnter() - { - base.OnFocusEnter(); - CaretIndex = Text?.Length ?? 0; - UpdateCaretScreenPosition(); - } - - private new void UpdateCaretScreenPosition() - { - _caretScreenPosition = _rendererText.GetCaretPosition(Stb.CursorIndex); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (batcher.ClipBegin(x, y, Width, Height)) - { - DrawSelection(batcher, x, y); - - _rendererText.Draw(batcher, x, y); - - DrawCaret(batcher, x, y); - batcher.ClipEnd(); - } - - return true; - } - } - - - private enum Buttons - { - NextArrow, - Quit, - Credits - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/Login/ServerSelectionGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/Login/ServerSelectionGump.cs deleted file mode 100644 index 8d72a6ecc..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/Login/ServerSelectionGump.cs +++ /dev/null @@ -1,439 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Linq; -using System.Net; -using System.Net.NetworkInformation; -using ClassicUO.Configuration; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Resources; -using ClassicUO.Utility; -using ClassicUO.Utility.Logging; -using SDL2; - -namespace ClassicUO.Game.UI.Gumps.Login -{ - internal class ServerSelectionGump : Gump - { - private const ushort SELECTED_COLOR = 0x0021; - private const ushort NORMAL_COLOR = 0x034F; - - public ServerSelectionGump() : base(0, 0) - { - //AddChildren(new LoginBackground(true)); - - Add - ( - new Button((int) Buttons.Prev, 0x15A1, 0x15A3, 0x15A2) - { - X = 586, Y = 445, ButtonAction = ButtonAction.Activate - } - ); - - Add - ( - new Button((int) Buttons.Next, 0x15A4, 0x15A6, 0x15A5) - { - X = 610, Y = 445, ButtonAction = ButtonAction.Activate - } - ); - - if (Client.Version >= ClientVersion.CV_500A) - { - ushort textColor = 0xFFFF; - - Add - ( - new Label(ClilocLoader.Instance.GetString(1044579), true, textColor, font: 1) - { - X = 155, Y = 70 - } - ); // "Select which shard to play on:" - - if (CUOEnviroment.NoServerPing == false) - { - Add - ( - new Label(ClilocLoader.Instance.GetString(1044577), true, textColor, font: 1) - { - X = 400, Y = 70 - } - ); // "Latency:" - - Add - ( - new Label(ClilocLoader.Instance.GetString(1044578), true, textColor, font: 1) - { - X = 470, Y = 70 - } - ); // "Packet Loss:" - } - - Add - ( - new Label(ClilocLoader.Instance.GetString(1044580), true, textColor, font: 1) - { - X = 153, Y = 368 - } - ); // "Sort by:" - } - else - { - ushort textColor = 0x0481; - - Add - ( - new Label(ResGumps.SelectWhichShardToPlayOn, false, textColor, font: 9) - { - X = 155, Y = 70 - } - ); - - Add - ( - new Label(ResGumps.Latency, false, textColor, font: 9) - { - X = 400, Y = 70 - } - ); - - Add - ( - new Label(ResGumps.PacketLoss, false, textColor, font: 9) - { - X = 470, Y = 70 - } - ); - - Add - ( - new Label(ResGumps.SortBy, false, textColor, font: 9) - { - X = 153, Y = 368 - } - ); - } - - Add - ( - new Button((int) Buttons.SortTimeZone, 0x093B, 0x093C, 0x093D) - { - X = 230, Y = 366 - } - ); - - Add - ( - new Button((int) Buttons.SortFull, 0x093E, 0x093F, 0x0940) - { - X = 338, Y = 366 - } - ); - - Add - ( - new Button((int) Buttons.SortConnection, 0x0941, 0x0942, 0x0943) - { - X = 446, Y = 366 - } - ); - - // World Pic Bg - Add(new GumpPic(150, 390, 0x0589, 0)); - - // Earth - Add - ( - new Button((int) Buttons.Earth, 0x15E8, 0x15EA, 0x15E9) - { - X = 160, Y = 400, ButtonAction = ButtonAction.Activate - } - ); - - // Sever Scroll Area Bg - Add - ( - new ResizePic(0x0DAC) - { - X = 150, Y = 90, Width = 393 - 14, Height = 271 - } - ); - - // Sever Scroll Area - ScrollArea scrollArea = new ScrollArea - ( - 150, - 90, - 393, - 271, - true - ); - - DataBox databox = new DataBox(0, 0, 1, 1); - databox.WantUpdateSize = true; - LoginScene loginScene = Client.Game.GetScene(); - - scrollArea.ScissorRectangle.Y = 16; - scrollArea.ScissorRectangle.Height = -32; - - foreach (ServerListEntry server in loginScene.Servers) - { - databox.Add(new ServerEntryGump(server, 5, NORMAL_COLOR, SELECTED_COLOR)); - } - - databox.ReArrangeChildren(); - - Add(scrollArea); - scrollArea.Add(databox); - - if (loginScene.Servers.Length != 0) - { - int index = loginScene.GetServerIndexFromSettings(); - - Add - ( - new Label(loginScene.Servers[index].Name, false, 0x0481, font: 9) - { - X = 243, - Y = 420 - } - ); - } - - AcceptKeyboardInput = true; - CanCloseWithRightClick = false; - } - - public override void OnButtonClick(int buttonID) - { - LoginScene loginScene = Client.Game.GetScene(); - - if (buttonID >= (int) Buttons.Server) - { - int index = buttonID - (int) Buttons.Server; - loginScene.SelectServer((byte) index); - } - else - { - switch ((Buttons) buttonID) - { - case Buttons.Next: - case Buttons.Earth: - - if (loginScene.Servers.Length != 0) - { - int index = loginScene.GetServerIndexFromSettings(); - - loginScene.SelectServer((byte) loginScene.Servers[index].Index); - } - - break; - - case Buttons.Prev: - loginScene.StepBack(); - - break; - } - } - } - - protected override void OnKeyDown(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - if (key == SDL.SDL_Keycode.SDLK_RETURN || key == SDL.SDL_Keycode.SDLK_KP_ENTER) - { - LoginScene loginScene = Client.Game.GetScene(); - - if (loginScene.Servers?.Any(s => s != null) ?? false) - { - int index = loginScene.GetServerIndexFromSettings(); - - loginScene.SelectServer((byte) loginScene.Servers[index].Index); - } - } - } - - private enum Buttons - { - Prev, - Next, - SortTimeZone, - SortFull, - SortConnection, - Earth, - Server = 99 - } - - private class ServerEntryGump : Control - { - private readonly int _buttonId; - private readonly ServerListEntry _entry; - private readonly HoveredLabel _server_packet_loss; - private readonly HoveredLabel _server_ping; - private readonly HoveredLabel _serverName; - private uint _pingCheckTime = 0; - - public ServerEntryGump(ServerListEntry entry, byte font, ushort normal_hue, ushort selected_hue) - { - _entry = entry; - - _buttonId = entry.Index; - - Add - ( - _serverName = new HoveredLabel - ( - entry.Name, - false, - normal_hue, - selected_hue, - selected_hue, - font: font - ) - { - X = 74, - AcceptMouseInput = false - } - ); - - Add - ( - _server_ping = new HoveredLabel - ( - CUOEnviroment.NoServerPing ? string.Empty : "-", - false, - normal_hue, - selected_hue, - selected_hue, - font: font - ) - { - X = 250, - AcceptMouseInput = false - } - ); - - Add - ( - _server_packet_loss = new HoveredLabel - ( - CUOEnviroment.NoServerPing ? string.Empty : "-", - false, - normal_hue, - selected_hue, - selected_hue, - font: font - ) - { - X = 320, - AcceptMouseInput = false - } - ); - - - AcceptMouseInput = true; - Width = 370; - Height = 25; - - WantUpdateSize = false; - } - - protected override void OnMouseEnter(int x, int y) - { - base.OnMouseEnter(x, y); - - _serverName.IsSelected = true; - _server_packet_loss.IsSelected = true; - _server_ping.IsSelected = true; - } - - protected override void OnMouseExit(int x, int y) - { - base.OnMouseExit(x, y); - - _serverName.IsSelected = false; - _server_packet_loss.IsSelected = false; - _server_ping.IsSelected = false; - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - OnButtonClick((int) Buttons.Server + _buttonId); - } - } - - public override void Update() - { - base.Update(); - - if (CUOEnviroment.NoServerPing == false && _pingCheckTime < Time.Ticks) - { - _pingCheckTime = Time.Ticks + 2000; - _entry.DoPing(); - - switch (_entry.PingStatus) - { - case IPStatus.Success: - _server_ping.Text = _entry.Ping == -1 ? "-" : _entry.Ping.ToString(); - - break; - - case IPStatus.DestinationNetworkUnreachable: - case IPStatus.DestinationHostUnreachable: - case IPStatus.DestinationProtocolUnreachable: - case IPStatus.DestinationPortUnreachable: - case IPStatus.DestinationUnreachable: - _server_ping.Text = "unreach."; - - break; - - case IPStatus.TimedOut: - _server_ping.Text = "time out"; - - break; - - default: - _server_ping.Text = $"unk. [{(int) _entry.PingStatus}]"; - - break; - } - - _server_packet_loss.Text = $"{_entry.PacketLoss}%"; - } - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/MacroButtonEditorGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/MacroButtonEditorGump.cs deleted file mode 100644 index ef64df3fb..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/MacroButtonEditorGump.cs +++ /dev/null @@ -1,342 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using System; -using System.Collections.Generic; -using System.Linq; -using ClassicUO.IO.Audio; -using static ClassicUO.Renderer.UltimaBatcher2D; -using ClassicUO.Game.Scenes; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class MacroButtonEditorGump : Gump - { - private const int WIDTH = 400; - private const int HEIGHT = 400; - private ScrollArea _scrollArea; - private Area _optionsArea; - private Area _previewArea; - - public MacroButtonEditorGump() : base(0, 0) - { - CanMove = true; - AcceptMouseInput = true; - CanCloseWithRightClick = true; - _macro = Macro.CreateEmptyMacro("No Action"); - } - public MacroButtonEditorGump(Macro macro, int x, int y) : this() - { - X = x; - Y = y; - _macro = macro; - BuildGump(); - } - - public override GumpType GumpType => GumpType.MacroButtonEditor; - public Macro _macro; - - private void BuildGump() - { - Add - ( - new AlphaBlendControl(0.95f) - { - X = 2, - Y = 2, - Width = WIDTH, - Height = HEIGHT, - Hue = 999 - } - ); - Label _header; - Add(_header = new Label - ( - $"Editor for {_macro.Name}", - true, - 0xFFFF, - WIDTH, - 0xFF, - FontStyle.BlackBorder | FontStyle.Cropped, TEXT_ALIGN_TYPE.TS_CENTER - ){ Y = 5}); - - - _optionsArea = BuildOptionsArea(5, _header.Height + 5); - Add(_optionsArea); - - - _scrollArea = new ScrollArea( - 5, - _optionsArea.Y + _optionsArea.Height + 15, - WIDTH - 15, - HEIGHT - _optionsArea.Height - 125, - false - ); - _scrollArea.AcceptMouseInput = true; - _scrollArea.CanMove = true; - - - _previewArea = new Area(); - _previewArea.X = 0; - _previewArea.Y = 5; - _previewArea.Width = _scrollArea.Width - 14; - _previewArea.Height = _scrollArea.Height - 5; - _previewArea.AcceptMouseInput = true; - _previewArea.CanMove = true; - - _scrollArea.Add(_previewArea); - - - Add(_scrollArea); - - AddPreview(); - - Add - ( - new Button(1, 0x00EF, 0x00F0, 0x00EE) - { - X = 165, - Y = HEIGHT - 50, - ButtonAction = ButtonAction.Activate - } - ); - - } - private Area BuildOptionsArea(int? x, int? y) - { - var area = new Area(); - area.Width = WIDTH - 10; - area.Height = 80; - area.X = x ?? 5; - area.Y = y ?? 5; - area.AcceptMouseInput = true; - area.CanMove = true; - - - Checkbox _hideLabelCheckbox = new Checkbox - ( - 0x00D2, - 0x00D3, - "Hide Label", - 0xFF, - 0xFFFF - ) - { - X = 10, - Y = 10, - IsChecked = _macro.HideLabel - }; - - _hideLabelCheckbox.ValueChanged += (sender, e) => - { - _macro.HideLabel = _hideLabelCheckbox.IsChecked; - AddPreview(); - }; - area.Add(_hideLabelCheckbox); - - - Label _ScaleLbl = new Label - ( - "Scale", - true, - 0xFFFF, - 50, - 0xFF, - FontStyle.BlackBorder | FontStyle.Cropped, TEXT_ALIGN_TYPE.TS_LEFT - ) - { - X = _hideLabelCheckbox.X + _hideLabelCheckbox.Width + 15, - Y = _hideLabelCheckbox.Y - }; - area.Add(_ScaleLbl); - - HSliderBar _scale = new HSliderBar - ( - _ScaleLbl.X + _ScaleLbl.Width + 15, - _ScaleLbl.Y + 2, - 180, - 10, - 200, - _macro.Scale, - HSliderBarStyle.BlueWidgetNoBar, - true, - 0xFF, - 0xFFFF - ); - _scale.ValueChanged += (sender, e) => - { - _macro.Scale = (byte)_scale.Value; - AddPreview(); - }; - - _scale.Add(new AlphaBlendControl(0.3f) - { - Hue = 0x0481, - Width = _scale.Width, - Height = _scale.Height - }); - - area.Add(_scale); - - - ModernColorPicker.HueDisplay _hueDisplay = new ModernColorPicker.HueDisplay(_macro.Hue, null, true) - { - X = 10, - Y = _scale.Y + _scale.Height + 15 - }; - _hueDisplay.HueChanged += (sender, ee) => - { - _macro.Hue = _hueDisplay.Hue; - AddPreview(); - }; - area.Add(_hueDisplay); - - Label _ColorLabel; - area.Add(_ColorLabel = new Label - ( - $"Color", - true, - 0xFFFF, - 50, - 0xFF, - FontStyle.BlackBorder | FontStyle.Cropped, TEXT_ALIGN_TYPE.TS_LEFT - ) - { - X = 30, - Y = _scale.Y + _scale.Height + 15 - }); - - Label _graphicLabel; - area.Add(_graphicLabel = new Label - ( - $"Graphic", - true, - 0xFFFF, - 50, - 0xFF, - FontStyle.BlackBorder | FontStyle.Cropped, TEXT_ALIGN_TYPE.TS_RIGHT - ) - { - X = _ScaleLbl.X, - Y = _ColorLabel.Y - }); - - StbTextBox _searchBox = new StbTextBox(0xFF, -1, 65, true, FontStyle.None, 0x0481) - { - X = _scale.X, - Y = _ColorLabel.Y, - Multiline = false, - Width = 65, - Height = 20, - Text = _macro.Graphic.ToString(), - NumbersOnly = true - }; - - _searchBox.TextChanged += (sender, e) => { - if (ushort.TryParse(_searchBox.Text, out var id)){ - OnGraphicChange(id); - return; - } - OnGraphicChange(null); - }; - _searchBox.Add(new AlphaBlendControl(0.5f) - { - Hue = 0x0481, - Width = _searchBox.Width, - Height = _searchBox.Height - }); - area.Add(_searchBox); - - - area.WantUpdateSize = false; - return area; - } - private void OnGraphicChange(ushort? graphic) - { - _macro.Graphic = graphic; - AddPreview(); - } - private void AddPreview() - { - _previewArea.Clear(); - _previewArea.Children.Clear(); - var _preview = new MacroButtonGump(_macro, 0, 0) { AcceptMouseInput = false }; - - _preview.X = ((WIDTH - 10) >> 1) - (_preview.Width >> 1); - _preview.Y = ((_previewArea.Height - 10) >> 1) - (_preview.Height >> 1); - _previewArea.Add(_preview); - - _previewArea.WantUpdateSize = false; - } - - public override void OnButtonClick(int buttonID) - { - switch (buttonID) - { - case 1: - Client.Game.GetScene().Macros.Save(); - var existing = UIManager.Gumps.OfType().FirstOrDefault(s => s.TheMacro == _macro); - if (existing != null) - { - existing.TheMacro = _macro; - } - break; - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - batcher.DrawRectangle - ( - SolidColorTextureCache.GetTexture(Color.Gray), - x, - y, - Width, - Height, - hueVector - ); - - return base.Draw(batcher, x, y); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/MacroButtonGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/MacroButtonGump.cs deleted file mode 100644 index c12df9b71..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/MacroButtonGump.cs +++ /dev/null @@ -1,304 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Xml; -using ClassicUO.Configuration; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using System.Data.SqlClient; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class MacroButtonGump : AnchorableGump - { - private Texture2D backgroundTexture; - private Vector3 hueVector; - private ushort? _graphic; - private ushort _hue; - private float _scale; - private bool _hideLabel; - private Macro _macr; - private readonly int DEFAULT_WIDTH = 88; - private readonly int DEFAULT_HEIGHT = 44; - private RenderedText _gText; - - public MacroButtonGump(Macro macro, int x, int y) : this() - { - X = x; - Y = y; - Width = DEFAULT_WIDTH; - Height = DEFAULT_HEIGHT; - TheMacro = macro; - - BuildGump(); - } - - public MacroButtonGump() : base(0, 0) - { - CanMove = true; - AcceptMouseInput = true; - CanCloseWithRightClick = true; - WantUpdateSize = false; - WidthMultiplier = 2; - HeightMultiplier = 1; - GroupMatrixWidth = 44; - GroupMatrixHeight = 44; - AnchorType = ANCHOR_TYPE.SPELL; - } - - public override GumpType GumpType => GumpType.MacroButton; - - public Macro TheMacro - { - get => _macr; - set - { - _macr = value; - Scale = value.Scale; - Graphic = value.Graphic; - Hue = value.Hue; - HideLabel = value.HideLabel; - } - } - public bool IsPartialHue { get; set; } - public ushort Hue - { - get => _hue; set - { - _hue = value; - hueVector = ShaderHueTranslator.GetHueVector(value); - } - } - public bool HideLabel - { - get => _hideLabel; - set - { - _hideLabel = value; - } - } - public float Scale - { - get => _scale; - set - { - _scale = value; - - var factor = value / 100F; - - Width = (int)(Width * factor); - Height = (int)(Height * factor); - GroupMatrixHeight = Height; - GroupMatrixWidth = Width; - WidthMultiplier = 1; - } - } - public ushort? Graphic - { - get => _graphic; - set - { - _graphic = value; - var factor = Scale / 100F; - Rectangle _bounds = new Rectangle(0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT); - - if (value.HasValue) - { - ref readonly var texture = ref Client.Game.Gumps.GetGump(value.Value); - _bounds = texture.UV; - IsPartialHue = texture.Texture == null ? false : TileDataLoader.Instance.StaticData[value.Value].IsPartialHue; - } - - Width = (int)(_bounds.Width * factor); - Height = (int)(_bounds.Height * factor); - - GroupMatrixHeight = Height; - GroupMatrixWidth = Width; - WidthMultiplier = 1; - } - } - - private void BuildGump() - { - backgroundTexture = SolidColorTextureCache.GetTexture(new Color(30, 30, 30)); - _gText = RenderedText.Create - ( - TheMacro.Name, - 0x03b2, - 255, - true, - FontStyle.BlackBorder, - TEXT_ALIGN_TYPE.TS_CENTER, - Width - ); - } - - protected override void OnMouseEnter(int x, int y) - { - backgroundTexture = SolidColorTextureCache.GetTexture(Color.DimGray); - base.OnMouseEnter(x, y); - } - - protected override void OnMouseExit(int x, int y) - { - backgroundTexture = SolidColorTextureCache.GetTexture(new Color(30, 30, 30)); - base.OnMouseExit(x, y); - } - - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - base.OnMouseUp(x, y, MouseButtonType.Left); - - Point offset = Mouse.LDragOffset; - - if (ProfileManager.CurrentProfile.CastSpellsByOneClick && button == MouseButtonType.Left && !Keyboard.Alt && Math.Abs(offset.X) < 5 && Math.Abs(offset.Y) < 5) - { - RunMacro(); - } - } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if (ProfileManager.CurrentProfile.CastSpellsByOneClick || button != MouseButtonType.Left) - { - return false; - } - - RunMacro(); - - return true; - } - - private void RunMacro() - { - if (TheMacro != null) - { - GameScene gs = Client.Game.GetScene(); - gs.Macros.SetMacroToExecute(TheMacro.Items as MacroObject); - gs.Macros.WaitForTargetTimer = 0; - gs.Macros.Update(); - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - - batcher.Draw - ( - backgroundTexture, - new Rectangle - ( - x, - y, - Width, - Height - ), - hueVector - ); - - if (Graphic.HasValue) - { - //var texture = GumpsLoader.Instance.GetGumpTexture(, out Rectangle bounds); - ref readonly var texture = ref Client.Game.Gumps.GetGump(Graphic.Value); - if (texture.Texture != null) - { - Rectangle rect = new Rectangle(x, y, Width, Height); - batcher.Draw - ( - texture.Texture, - rect, - texture.UV, - hueVector - ); - } - } - else - { - batcher.DrawRectangle - ( - SolidColorTextureCache.GetTexture(Color.Gray), - x, - y, - Width, - Height, - hueVector - ); - } - - if (!HideLabel && _gText != null) - { - _gText.Hue = (ushort)(MouseIsOver ? 53 : 0x03b2); - _gText.Draw(batcher, x, y + ((Height >> 1) - (_gText.Height >> 1)), Alpha); - } - - - base.Draw(batcher, x, y); - - return true; - } - - public override void Save(XmlTextWriter writer) - { - if (TheMacro != null) - { - // hack to give macro buttons a unique id for use in anchor groups - int macroid = Client.Game.GetScene().Macros.GetAllMacros().IndexOf(TheMacro); - - LocalSerial = (uint)macroid + 1000; - - base.Save(writer); - - writer.WriteAttributeString("name", TheMacro.Name); - } - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - - Macro macro = Client.Game.GetScene().Macros.FindMacro(xml.GetAttribute("name")); - - if (macro != null) - { - TheMacro = macro; - BuildGump(); - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/MacroGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/MacroGump.cs deleted file mode 100644 index 708ad0907..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/MacroGump.cs +++ /dev/null @@ -1,45 +0,0 @@ - -using ClassicUO.Configuration; -using ClassicUO.Game.UI.Controls; - -namespace ClassicUO.Game.UI.Gumps -{ - internal sealed class MacroGump : Gump - { - public MacroGump(string name) : base(0, 0) - { - CanMove = true; - CanCloseWithRightClick = true; - var camera = Client.Game.Scene.Camera; - - AlphaBlendControl macroGumpBackground = new AlphaBlendControl - { - Width = 360, - Height = 200, - X = camera.Bounds.Width / 2 - 125, - Y = 150, - Alpha = 0.8f - }; - - Label text = new Label($"Edit macro: {name}", true, 15) - { - X = camera.Bounds.Width / 2 - 105, - Y = macroGumpBackground.Y + 2 - }; - - Add(macroGumpBackground); - Add(text); - - Add - ( - new MacroControl(name, true) - { - X = macroGumpBackground.X + 20, - Y = macroGumpBackground.Y + 20, - } - ); - - SetInScreen(); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/MapGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/MapGump.cs deleted file mode 100644 index 6e65b533c..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/MapGump.cs +++ /dev/null @@ -1,553 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Network; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class MapGump : Gump - { - private readonly Button[] _buttons = new Button[3]; - private readonly List _container = new List(); - private PinControl _currentPin; - private Point _lastPoint; - private HitBox _hit; - private Texture2D _mapTexture; - private ResizePic mapGump; - - private uint _pinTimer; - - public MapGump(uint serial, ushort gumpid, int width, int height) : base(serial, 0) - { - AcceptMouseInput = false; - CanMove = true; - CanCloseWithRightClick = true; - Width = width; - Height = height; - - WantUpdateSize = false; - - Add - (mapGump = - new ResizePic(0x1432) - { - Width = width + 44, - Height = height + 61 - } - ); - - Add(_buttons[0] = new Button((int)ButtonType.PlotCourse, 0x1398, 0x1398) { X = (width - 100) >> 1, Y = 5, ButtonAction = ButtonAction.Activate }); - - Add(_buttons[1] = new Button((int)ButtonType.StopPlotting, 0x1399, 0x1399) { X = (width - 70) >> 1, Y = 5, ButtonAction = ButtonAction.Activate }); - - Add(_buttons[2] = new Button((int)ButtonType.ClearCourse, 0x139A, 0x139A) { X = (width - 66) >> 1, Y = height + 37, ButtonAction = ButtonAction.Activate }); - - _buttons[0].IsVisible = _buttons[0].IsEnabled = PlotState == 0; - - _buttons[1].IsVisible = _buttons[1].IsEnabled = PlotState == 1; - - _buttons[2].IsVisible = _buttons[2].IsEnabled = PlotState == 1; - - - - _hit = new HitBox(24, 31, width, height, null, 0f) { CanMove = true }; - Add(_hit); - - _hit.MouseUp += TextureControlOnMouseUp; - - MenuButton menu = new MenuButton(25, Color.Black.PackedValue, 0.75f, "Menu") { X = width + 44 - 43, Y = 6 }; - - menu.MouseUp += (s, e) => { - menu.ContextMenu?.Show(); - }; - menu.ContextMenu = new ContextMenuControl(); - menu.ContextMenu.Add(new ContextMenuItemEntry("Show approximate location on world map", () => - { - if (foundMapLoc) - { - WorldMapGump map = UIManager.GetGump(); - if (map != null) - { - if (mapFacet != -1) - { - if (World.MapIndex != mapFacet) - GameActions.Print("You're on the wrong facet!", 32); - else - map.GoToMarker(mapX, mapY, true); - } - else - map.GoToMarker(mapX, mapY, true); - } - } - })); - menu.ContextMenu.Add(new ContextMenuItemEntry("Try to pathfind", () => { - if (foundMapLoc) - { - int distance = Math.Max(Math.Abs(World.Player.X - mapX), Math.Abs(World.Player.Y - mapY)); - - if(distance > 10) - { - GameActions.Print("You're too far away to try to pathfind, you need to be within 10 tiles.", 32); - return; - } - - if (mapFacet != -1) - { - if (World.MapIndex != mapFacet) - GameActions.Print("You're on the wrong facet!", 32); - else - Pathfinder.WalkTo(mapX, mapY, 0, 1); - } - else - Pathfinder.WalkTo(mapX, mapY, 0, 1); - } - })); - menu.ContextMenu.Add(new ContextMenuItemEntry("Close", () => { Dispose(); })); - menu.CanCloseWithRightClick = false; - - Add(new GumpPic(width - 20, height - 20, 0x0139D, 0)); - Add(menu); - } - - - public int PlotState { get; private set; } - - public void SetMapTexture(Texture2D texture) - { - _mapTexture?.Dispose(); - _mapTexture = texture; - - Width = texture.Width; - Height = texture.Height; - - WantUpdateSize = true; - } - - private int mapX = 0, mapY = 0, mapFacet = -1, mapEndX = 0, mapEndY = 0; - private bool foundMapLoc = false; - - public void MapInfos(int x, int y, int endX, int endY, int facet = -1) - { - mapX = x; - mapY = y; - mapEndX = endX; - mapEndY = endY; - mapFacet = facet; - } - - public void AddPin(int x, int y) - { - PinControl c = new PinControl(x, y); - c.X += c.Width + 5; - c.Y += c.Height; - c.NumberText = (_container.Count + 1).ToString(); - _container.Add(c); - Add(c); - if (!foundMapLoc) - { - //multiplier = float((mapinfo.MapEnd.X) - (mapinfo.MapOrigin.X)) / float(width) - // multiX = mapinfo.PinPosition.X * multiplier - // multiY = mapinfo.PinPosition.Y * multiplier - // finalX = int(mapinfo.MapOrigin.X + multiX) - // finalY = int(mapinfo.MapOrigin.Y + multiY) - - float multiplier = (float)Width / 300f; - //if (Width == 200) - // multiplier = 0.666666666f; - //if (Width == 600) - // multiplier = 2f; - if (CUOEnviroment.Debug) - GameActions.Print($"Width: {Width}, Multiplier: {multiplier}, Facet: {mapFacet}, MapData: {mapX}, {mapY}, {mapEndX}, {mapEndY}"); - - mapX = (int)(mapX + (x * multiplier)); - mapY = (int)(mapY + (y * multiplier)); - - //mapX = mapX + x; - //mapY = mapY + y; - foundMapLoc = true; - - _hit?.SetTooltip($"Estimated loc: {mapX}, {mapY}"); - } - } - - public void ClearContainer() - { - foreach (Control s in _container) - { - s.Dispose(); - } - - _container.Clear(); - } - - public void SetPlotState(int s) - { - PlotState = s; - - _buttons[0].IsVisible = _buttons[0].IsEnabled = PlotState == 0; - - _buttons[1].IsVisible = _buttons[1].IsEnabled = PlotState == 1; - - _buttons[2].IsVisible = _buttons[2].IsEnabled = PlotState == 1; - } - - public override void OnButtonClick(int buttonID) - { - ButtonType b = (ButtonType)buttonID; - - switch (b) - { - case ButtonType.PlotCourse: - case ButtonType.StopPlotting: - NetClient.Socket.Send_MapMessage(LocalSerial, - 6, - (byte)PlotState, - unchecked((ushort)-24), - unchecked((ushort)-31)); - - SetPlotState(PlotState == 0 ? 1 : 0); - - break; - - case ButtonType.ClearCourse: - NetClient.Socket.Send_MapMessage(LocalSerial, - 5, - 0, - unchecked((ushort)-24), - unchecked((ushort)-31)); - - ClearContainer(); - - break; - } - } - - - public override void Update() - { - base.Update(); - - if (_currentPin != null) - { - if (Mouse.LDragOffset != Point.Zero && Mouse.LDragOffset != _lastPoint) - { - _currentPin.Location += Mouse.LDragOffset - _lastPoint; - - if (_currentPin.X < _hit.X) - { - _currentPin.X = _hit.X; - } - else if (_currentPin.X >= _hit.Width) - { - _currentPin.X = _hit.Width; - } - - if (_currentPin.Y < _hit.Y) - { - _currentPin.Y = _hit.Y; - } - else if (_currentPin.Y >= _hit.Height) - { - _currentPin.Y = _hit.Height; - } - - - _lastPoint = Mouse.LDragOffset; - } - } - } - - - private void TextureControlOnMouseUp(object sender, MouseEventArgs e) - { - Point offset = Mouse.LDragOffset; - - if (Math.Abs(offset.X) < 5 && Math.Abs(offset.Y) < 5) - { - if (PlotState != 0 && _currentPin == null && _pinTimer > Time.Ticks) - { - ushort x = (ushort)(e.X + 5); - ushort y = (ushort)e.Y; - - NetClient.Socket.Send_MapMessage(LocalSerial, - 1, - 0, - x, - y); - - AddPin(x, y); - } - } - - _currentPin = null; - _lastPoint = Point.Zero; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - batcher.Draw - ( - _mapTexture, - new Rectangle(x + _hit.X, y + _hit.Y, _hit.Width, _hit.Height), - hueVector - ); - - var texture = SolidColorTextureCache.GetTexture(Color.White); - - for (int i = 0; i < _container.Count; i++) - { - // HACK: redraw because pins are drawn when calling base.Draw(batcher, x, y); - _container[i].Draw(batcher, x + _container[i].X, y + _container[i].Y); - - if (i + 1 >= _container.Count) - { - break; - } - - Control c0 = _container[i]; - Control c1 = _container[i + 1]; - - batcher.DrawLine - ( - texture, - new Vector2(c0.ScreenCoordinateX, c0.ScreenCoordinateY), - new Vector2(c1.ScreenCoordinateX, c1.ScreenCoordinateY), - hueVector, - 1 - ); - } - - return true; - } - - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - base.OnMouseUp(x, y, button); - _currentPin = null; - _lastPoint = Point.Zero; - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - _pinTimer = Time.Ticks + 300; - - if (PlotState != 0 && UIManager.MouseOverControl is PinControl pin) - { - _currentPin = pin; - } - } - - - private int LineUnderMouse(ref int x1, ref int y1, ref int x2, ref int y2) - { - int tempX = x2 - x1; - int tempY = y2 - y1; - - float testOfsX = tempX; - - if (testOfsX == 0.0f) - { - testOfsX = 1.0f; - } - - float pi = (float)Math.PI; - - float a = -(float)(Math.Atan(tempY / testOfsX) * 180f / pi); - - bool inverseCheck = false; - - if (x1 >= x2 && y1 <= y2) - { - inverseCheck = true; - } - else if (x1 >= x2 && y1 >= y2) - { - inverseCheck = true; - } - - float sinA = (float)Math.Sin(a * pi / 180f); - float cosA = (float)Math.Sin(a * pi / 180f); - - int offsetX = (int)(tempX * cosA - tempY * sinA); - int offsetY = (int)(tempX * sinA + tempY * cosA); - - int endX2 = x1 + offsetX; - int endY2 = y1 + offsetY; - - tempX = Mouse.Position.X - x1; // TODO: must be position relative to the gump - tempY = Mouse.Position.Y - y1; - - offsetX = (int)(tempX * cosA - tempY * sinA); - offsetY = (int)(tempX * sinA + tempY * cosA); - - Point mousePoint = new Point(x1 + offsetX, y1 + offsetY); - - const int POLY_OFFSET = 5; - - int result = 0; - - - if (!inverseCheck) - { - Rectangle rect = new Rectangle - { - X = x1 - POLY_OFFSET, - Y = y1 - POLY_OFFSET, - Width = endX2 + POLY_OFFSET, - Height = endY2 + POLY_OFFSET - }; - - if (rect.Contains(mousePoint)) - { - x1 = x1 + (x2 - x1) / 2; - y1 = y1 + (y2 - y1) / 2; - result = 1; - } - } - else - { - Rectangle rect = new Rectangle - { - X = endX2 - POLY_OFFSET, - Y = endY2 - POLY_OFFSET, - Width = x1 + POLY_OFFSET, - Height = x2 + POLY_OFFSET - }; - - if (rect.Contains(mousePoint)) - { - x1 = x2 + (x1 - x2) / 2; - y1 = y2 + (y1 - y2) / 2; - result = 2; - } - } - - return result; - } - - public override void Dispose() - { - _hit.MouseUp -= TextureControlOnMouseUp; - _mapTexture?.Dispose(); - base.Dispose(); - } - - private enum ButtonType - { - PlotCourse, - StopPlotting, - ClearCourse - } - - private class PinControl : Control - { - private readonly GumpPic _pic; - private readonly RenderedText _text; - - public PinControl(int x, int y) - { - X = x; - Y = y; - - - _text = RenderedText.Create(string.Empty, font: 0, isunicode: false); - - _pic = new GumpPic(0, 0, 0x139B, 0); - Add(_pic); - - WantUpdateSize = false; - Width = _pic.Width; - Height = _pic.Height; - - AcceptMouseInput = true; - CanMove = false; - - _pic.AcceptMouseInput = true; - - Priority = ClickPriority.High; - } - - - //public override bool Contains(int x, int y) - //{ - // //x = Mouse.Position.X - ScreenCoordinateX; - // //y = Mouse.Position.Y - ScreenCoordinateY; - - // return _pic.Contains(x, y); - //} - - public string NumberText - { - get => _text.Text; - set => _text.Text = value; - } - - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (MouseIsOver) - { - _pic.Hue = 0x35; - } - else if (_pic.Hue != 0) - { - _pic.Hue = 0; - } - - base.Draw(batcher, x, y); - _text.Draw(batcher, x - _text.Width - 1, y); - - return true; - } - - public override void Dispose() - { - _text?.Destroy(); - - base.Dispose(); - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/MarkersManagerGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/MarkersManagerGump.cs deleted file mode 100644 index 8428d0ec5..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/MarkersManagerGump.cs +++ /dev/null @@ -1,547 +0,0 @@ -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using ClassicUO.Resources; -using Microsoft.Xna.Framework.Graphics; -using static ClassicUO.Game.UI.Gumps.WorldMapGump; -using ClassicUO.Renderer; - -namespace ClassicUO.Game.UI.Gumps -{ - internal sealed class MarkersManagerGump : Gump - { - private const int WIDTH = 620; - private const int HEIGHT = 500; - private const ushort HUE_FONT = 0xFFFF; - - private bool _isMarkerListModified; - - private ScrollArea _scrollArea; - private readonly SearchTextBoxControl _searchTextBox; - - private string _searchText = ""; - private int _categoryId = 0; - - private static List _markers = new List(); - - private static readonly List _markerFiles = WorldMapGump._markerFiles; - - private readonly string _userMarkersFilePath = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Client", $"{USER_MARKERS_FILE}.usr"); - - private readonly int MARKERS_CATEGORY_GROUP_INDEX = 10; - - private enum ButtonsOption - { - SEARCH_BTN = 100, - CLEAR_SEARCH_BTN - } - - internal MarkersManagerGump() : base(0, 0) - { - X = 50; - Y = 50; - CanMove = true; - AcceptMouseInput = true; - - var button_width = 50; - if (_markerFiles.Count > 0) - { - _markers = _markerFiles[0].Markers; - button_width = WIDTH / _markerFiles.Count; - } - - Add - ( - new AlphaBlendControl(0.95f) - { - X = 1, - Y = 1, - Width = WIDTH, - Height = HEIGHT, - Hue = 999, - AcceptMouseInput = true, - CanCloseWithRightClick = true, - CanMove = true, - } - ); - - #region Boarder - Add - ( - new Line - ( - 0, - 0, - WIDTH, - 1, - Color.Gray.PackedValue - ) - ); - - Add - ( - new Line - ( - 0, - 0, - 1, - HEIGHT, - Color.Gray.PackedValue - ) - ); - - Add - ( - new Line - ( - 0, - HEIGHT, - WIDTH, - 1, - Color.Gray.PackedValue - ) - ); - - Add - ( - new Line - ( - WIDTH, - 0, - 1, - HEIGHT, - Color.Gray.PackedValue - ) - ); - #endregion - - var initY = 10; - - #region Legend - - Add(new Label(ResGumps.MarkerIcon, true, HUE_FONT, 185, 255, FontStyle.BlackBorder) { X = 5, Y = initY }); - - Add(new Label(ResGumps.MarkerName, true, HUE_FONT, 185, 255, FontStyle.BlackBorder) { X = 50, Y = initY }); - - Add(new Label(ResGumps.MarkerX, true, HUE_FONT, 35, 255, FontStyle.BlackBorder) { X = 315, Y = initY }); - - Add(new Label(ResGumps.MarkerY, true, HUE_FONT, 35, 255, FontStyle.BlackBorder) { X = 380, Y = initY }); - - Add(new Label(ResGumps.MarkerColor, true, HUE_FONT, 35, 255, FontStyle.BlackBorder) { X = 420, Y = initY }); - - Add(new Label(ResGumps.Edit, true, HUE_FONT, 35, 255, FontStyle.BlackBorder) { X = 475, Y = initY }); - - Add(new Label(ResGumps.Remove, true, HUE_FONT, 40, 255, FontStyle.BlackBorder) { X = 505, Y = initY }); - - Add(new Label(ResGumps.MarkerGoTo, true, HUE_FONT, 40, 255, FontStyle.BlackBorder) { X = 550, Y = initY }); - - #endregion - - Add - ( - new Line - ( - 0, - initY + 20, - WIDTH, - 1, - Color.Gray.PackedValue - ) - ); - - // Search Field - Add(_searchTextBox = new SearchTextBoxControl(WIDTH / 2 - 150, 40)); - - DrawArea(_markerFiles[_categoryId].IsEditable); - - var initX = 0; - foreach (var file in _markerFiles) - { - var b = new NiceButton( - button_width * initX, - HEIGHT - 40, - button_width, - 40, - ButtonAction.Activate, - file.Name, - MARKERS_CATEGORY_GROUP_INDEX - ) - { - ButtonParameter = initX, - IsSelectable = true, - }; - - b.SetTooltip(file.Name); - if (initX == 0) b.IsSelected = true; - - Add(b); - - Add - ( - new Line - ( - b.X, - b.Y, - 1, - b.Height, - Color.Gray.PackedValue - ) - ); - initX++; - } - - Add - ( - new Line - ( - 0, - HEIGHT - 40, - WIDTH, - 1, - Color.Gray.PackedValue - ) - ); - - SetInScreen(); - } - - private void DrawArea(bool isEditable) - { - _scrollArea = new ScrollArea - ( - 10, - 80, - WIDTH - 20, - 370, - true - ); - - int i = 0; - - foreach (var marker in _markers.Select((value, idx) => new { idx, value })) - { - if (!string.IsNullOrEmpty(_searchText) && !marker.value.Name.ToLower().Contains(_searchText.ToLower())) - { - continue; - } - - var newElement = new MakerManagerControl(marker.value, i, marker.idx, isEditable); - newElement.RemoveMarkerEvent += MarkerRemoveEventHandler; - newElement.EditMarkerEvent += MarkerEditEventHandler; - - _scrollArea.Add(newElement); - i += 25; - } - Add(_scrollArea); - } - - private void MarkerRemoveEventHandler(object sender, EventArgs e) - { - if (sender is int idx) - { - _markers.RemoveAt(idx); - // Clear area - Remove(_scrollArea); - //Redraw List - DrawArea(_markerFiles[_categoryId].IsEditable); - //Mark list as Modified - _isMarkerListModified = true; - } - } - - public override void OnButtonClick(int buttonID) - { - switch (buttonID) - { - case (int)ButtonsOption.SEARCH_BTN: - if (_searchText.Equals(_searchTextBox.SearchText)) - return; - _searchText = _searchTextBox.SearchText; - break; - case (int)ButtonsOption.CLEAR_SEARCH_BTN: - _searchTextBox.ClearText(); - _searchText = ""; - break; - default: - _categoryId = buttonID; - _markers = _markerFiles[buttonID].Markers; - break; - } - - _scrollArea.Clear(); - DrawArea(_markerFiles[_categoryId].IsEditable); - } - - public override void OnKeyboardReturn(int textID, string text) - { - if (_searchText.Equals(_searchTextBox.SearchText)) - return; - - _scrollArea.Clear(); - _searchText = _searchTextBox.SearchText; - DrawArea(_markerFiles[_categoryId].IsEditable); - } - - private void MarkerEditEventHandler(object sender, EventArgs e) - { - _isMarkerListModified = true; - } - - public override void Dispose() - { - if (_isMarkerListModified) - { - using (StreamWriter writer = new StreamWriter(_userMarkersFilePath, false)) - { - foreach (var marker in _markers) - { - var newLine = $"{marker.X},{marker.Y},{marker.MapId},{marker.Name},{marker.MarkerIconName},{marker.ColorName},4"; - - writer.WriteLine(newLine); - } - } - _isMarkerListModified = false; - ReloadUserMarkers(); - } - base.Dispose(); - } - - internal class DrawTexture : Control - { - public Texture2D Texture; - - public DrawTexture(Texture2D texture) - { - Texture = texture; - Width = Height = 15; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - batcher.Draw(Texture, new Rectangle(x, y + 7, Width, Height), hueVector); - return true; - } - } - - private sealed class MakerManagerControl : Control - { - private readonly WMapMarker _marker; - private readonly int _y; - private readonly int _idx; - private readonly bool _isEditable; - - private Label _labelName; - private Label _labelX; - private Label _labelY; - private Label _labelColor; - - private DrawTexture _iconTexture; - - public event EventHandler RemoveMarkerEvent; - public event EventHandler EditMarkerEvent; - - private enum ButtonsOption - { - EDIT_MARKER_BTN, - REMOVE_MARKER_BTN, - GOTO_MARKER_BTN - } - - public MakerManagerControl(WMapMarker marker, int y, int idx, bool isEditable) - { - CanMove = true; - - _idx = idx; - _marker = marker; - _y = y; - _isEditable = isEditable; - - DrawData(); - } - - private void DrawData() - { - if (_marker.MarkerIcon != null) - { - _iconTexture = new DrawTexture(_marker.MarkerIcon) { X = 0, Y = _y - 5 }; - Add(_iconTexture); - } - - _labelName = new Label($"{_marker.Name}", true, HUE_FONT, 280) { X = 30, Y = _y }; - Add(_labelName); - - _labelX = new Label($"{_marker.X}", true, HUE_FONT, 35) { X = 305, Y = _y }; - Add(_labelX); - - _labelY = new Label($"{_marker.Y}", true, HUE_FONT, 35) { X = 350, Y = _y }; - Add(_labelY); - - _labelColor = new Label($"{_marker.ColorName}", true, HUE_FONT, 35) { X = 410, Y = _y }; - Add(_labelColor); - - if (_isEditable) - { - Add( - new Button((int)ButtonsOption.EDIT_MARKER_BTN, 0xFAB, 0xFAC) - { - X = 470, - Y = _y, - ButtonAction = ButtonAction.Activate, - } - ); - - Add( - new Button((int)ButtonsOption.REMOVE_MARKER_BTN, 0xFB1, 0xFB2) - { - X = 505, - Y = _y, - ButtonAction = ButtonAction.Activate, - } - ); - } - - Add( - new Button((int)ButtonsOption.GOTO_MARKER_BTN, 0xFA5, 0xFA7) - { - X = 540, - Y = _y, - ButtonAction = ButtonAction.Activate, - } - ); - } - - private void OnEditEnd(object sender, EventArgs e) - { - if (sender is WMapMarker editedMarker) - { - _labelName.Text = editedMarker.Name; - _labelColor.Text = editedMarker.ColorName; - _labelX.Text = editedMarker.X.ToString(); - _labelY.Text = editedMarker.Y.ToString(); - if (editedMarker.MarkerIcon != null) - { - _iconTexture?.Dispose(); - _iconTexture = new DrawTexture(editedMarker.MarkerIcon); - } - - - EditMarkerEvent.Raise(); - } - } - - public override void OnButtonClick(int buttonId) - { - switch (buttonId) - { - case (int)ButtonsOption.EDIT_MARKER_BTN: - UserMarkersGump existingGump = UIManager.GetGump(); - - existingGump?.Dispose(); - - var editUserMarkerGump = new UserMarkersGump(_marker.X, _marker.Y, _markers, _marker.ColorName, _marker.MarkerIconName, true, _idx); - editUserMarkerGump.EditEnd += OnEditEnd; - - UIManager.Add(editUserMarkerGump); - - break; - case (int)ButtonsOption.REMOVE_MARKER_BTN: - RemoveMarkerEvent.Raise(_idx); - break; - case (int)ButtonsOption.GOTO_MARKER_BTN: - var wmGump = UIManager.GetGump(); - if (wmGump != null) - { - wmGump.GoToMarker(_marker.X, _marker.Y, false); - } - break; - } - } - } - - private sealed class SearchTextBoxControl : Control - { - private readonly StbTextBox _textBox; - public string SearchText { get => _textBox.Text; } - - public SearchTextBoxControl(int x, int y) - { - AcceptMouseInput = true; - AcceptKeyboardInput = true; - - Add - ( - new Label - ( - ResGumps.MarkerSearch, - true, - HUE_FONT, - 50, - 1 - ) - { - X = x, - Y = y - } - ); - - Add - ( - new ResizePic(0x0BB8) - { - X = x + 50, - Y = y, - Width = 200, - Height = 25 - } - ); - - _textBox = new StbTextBox - ( - 0xFF, - 30, - 200, - true, - FontStyle.BlackBorder | FontStyle.Fixed - ) - { - X = x + 53, - Y = y + 3, - Width = 200, - Height = 25 - }; - - Add(_textBox); - - Add( - new Button((int)ButtonsOption.SEARCH_BTN, 0xFB7, 0xFB9) - { - X = x + 250, - Y = y + 1, - ButtonAction = ButtonAction.Activate, - } - ); - - Add( - new Button((int)ButtonsOption.CLEAR_SEARCH_BTN, 0xFB1, 0xFB2) - { - X = x + 285, - Y = y + 1, - ButtonAction = ButtonAction.Activate, - } - ); - } - - public void ClearText() - { - _textBox.SetText(""); - } - } - } - -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/MenuGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/MenuGump.cs deleted file mode 100644 index 032d3dbdc..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/MenuGump.cs +++ /dev/null @@ -1,361 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Linq; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Assets; -using ClassicUO.Network; -using ClassicUO.Renderer; -using ClassicUO.Utility.Logging; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class MenuGump : Gump - { - private readonly ContainerHorizontal _container; - private bool _isDown, - _isLeft; - private readonly HSliderBar _slider; - - public MenuGump(uint serial, uint serv, string name) : base(serial, serv) - { - CanMove = true; - AcceptMouseInput = true; - CanCloseWithRightClick = true; - IsFromServer = true; - - Add(new GumpPic(0, 0, 0x0910, 0)); - - Add(new ColorBox(217, 49, 1) { X = 40, Y = 42 }); - - Label label = new Label(name, false, 0x0386, 200, 1, FontStyle.Fixed) - { - X = 39, - Y = 18 - }; - - Add(label); - - _container = new ContainerHorizontal - { - X = 40, - Y = 42, - Width = 217, - Height = 49, - WantUpdateSize = false, - }; - - Add(_container); - - Add( - _slider = new HSliderBar( - 40, - _container.Y + _container.Height + 12, - 217, - 0, - 1, - 0, - HSliderBarStyle.MetalWidgetRecessedBar - ) - ); - - _slider.ValueChanged += (sender, e) => - { - _container.Value = _slider.Value; - }; - - HitBox left = new HitBox(25, 60, 10, 15) { Alpha = 0f }; - - left.MouseDown += (sender, e) => - { - _isDown = true; - _isLeft = true; - }; - - left.MouseUp += (sender, e) => - { - _isDown = false; - }; - Add(left); - - HitBox right = new HitBox(260, 60, 10, 15) { Alpha = 0f }; - - right.MouseDown += (sender, e) => - { - _isDown = true; - _isLeft = false; - }; - - right.MouseUp += (sender, e) => - { - _isDown = false; - }; - Add(right); - } - - public override void Update() - { - base.Update(); - - if (_isDown) - { - _container.Value += _isLeft ? -1 : 1; - } - } - - public void AddItem(ushort graphic, ushort hue, string name, int x, int y, int index) - { - var view = new ItemView(graphic, hue) - { - X = x, - Y = y - }; - - view.MouseDoubleClick += (sender, e) => - { - NetClient.Socket.Send_MenuResponse( - LocalSerial, - (ushort)ServerSerial, - index, - graphic, - hue - ); - Dispose(); - e.Result = true; - }; - - view.SetTooltip(name); - - _container.Add(view); - - _container.CalculateWidth(); - _slider.MaxValue = _container.MaxValue; - } - - protected override void CloseWithRightClick() - { - base.CloseWithRightClick(); - - NetClient.Socket.Send_MenuResponse(LocalSerial, (ushort)ServerSerial, 0, 0, 0); - } - - class ItemView : Control - { - private readonly ushort _graphic; - private readonly ushort _hue; - private readonly bool _isPartial; - - public ItemView(ushort graphic, ushort hue) - { - AcceptMouseInput = true; - WantUpdateSize = true; - - _graphic = graphic; - - ref readonly var artInfo = ref Client.Game.Arts.GetArt(_graphic); - - Width = artInfo.UV.Width; - Height = artInfo.UV.Height; - _hue = hue; - _isPartial = TileDataLoader.Instance.StaticData[graphic].IsPartialHue; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (_graphic != 0) - { - ref readonly var artInfo = ref Client.Game.Arts.GetArt(_graphic); - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(_hue, _isPartial, 1f); - - batcher.Draw(artInfo.Texture, new Vector2(x, y), artInfo.UV, hueVector); - } - - return base.Draw(batcher, x, y); - } - } - - private class ContainerHorizontal : Control - { - private int _value; - - public int Value - { - get => _value; - set - { - if (value < 0) - { - value = 0; - } - else if (value > MaxValue) - { - value = MaxValue; - } - - _value = value; - } - } - - public int MaxValue { get; private set; } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (batcher.ClipBegin(x, y, Width, Height)) - { - int width = 0; - int maxWidth = Value + Width; - bool drawOnly1 = true; - - foreach (Control child in Children) - { - if (!child.IsVisible) - { - continue; - } - - child.X = width - Value; - - if (width + child.Width <= Value) { } - else if (width + child.Width <= maxWidth) - { - child.Draw(batcher, child.X + x, y); - } - else - { - if (drawOnly1) - { - child.Draw(batcher, child.X + x, y); - drawOnly1 = false; - } - } - - width += child.Width; - } - - batcher.ClipEnd(); - } - - return true; // base.Draw(batcher,position, hue); - } - - public void CalculateWidth() - { - MaxValue = Children.Sum(s => s.Width) - Width; - - if (MaxValue < 0) - { - MaxValue = 0; - } - } - } - } - - internal class GrayMenuGump : Gump - { - private readonly ResizePic _resizePic; - - public GrayMenuGump(uint local, uint serv, string name) : base(local, serv) - { - CanMove = true; - AcceptMouseInput = true; - CanCloseWithRightClick = false; - IsFromServer = true; - - Add(_resizePic = new ResizePic(0x13EC) { Width = 400, Height = 111111 }); - - Label l; - - Add(l = new Label(name, false, 0x0386, 370, 1) { X = 20, Y = 16 }); - - Width = _resizePic.Width; - Height = l.Height; - } - - public void SetHeight(int h) - { - _resizePic.Height = h; - Width = _resizePic.Width; - Height = _resizePic.Height; - } - - public int AddItem(string name, int y) - { - RadioButton radio = new RadioButton(0, 0x138A, 0x138B, name, 1, 0x0386, false, 330) - { - X = 50, - Y = y - }; - - Add(radio); - - return radio.Height; - } - - public override void OnButtonClick(int buttonID) - { - switch (buttonID) - { - case 0: // cancel - NetClient.Socket.Send_GrayMenuResponse(LocalSerial, (ushort)ServerSerial, 0); - - Dispose(); - - break; - - case 1: // continue - - ushort index = 1; - - foreach (RadioButton radioButton in Children.OfType()) - { - if (radioButton.IsChecked) - { - NetClient.Socket.Send_GrayMenuResponse( - LocalSerial, - (ushort)ServerSerial, - index - ); - - Dispose(); - break; - } - - index++; - } - - break; - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/MessageBoxGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/MessageBoxGump.cs deleted file mode 100644 index d1c69eb07..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/MessageBoxGump.cs +++ /dev/null @@ -1,286 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Renderer; -using SDL2; - -namespace ClassicUO.Game.UI.Gumps -{ - enum MessageButtonType - { - OK, - OK_CANCEL, - - } - - internal class MessageBoxGump : Gump - { - private readonly Action _action; - - public MessageBoxGump(int w, int h, string message, Action action, bool hasBackground = false, MessageButtonType menuType = MessageButtonType.OK) : base(0, 0) - { - CanMove = true; - CanCloseWithRightClick = false; - CanCloseWithEsc = false; - AcceptMouseInput = true; - AcceptKeyboardInput = true; - - IsModal = true; - LayerOrder = UILayer.Over; - WantUpdateSize = false; - - Width = w; - Height = h; - _action = action; - - Add - ( - new ResizePic(0x0A28) - { - Width = w, Height = h - } - ); - - if (hasBackground) - { - ResizePic background = new ResizePic(3000) - { - X = X + 30, - Y = Y + 40, - Width = Width - 60, - Height = Height - 100 - }; - - Add(background); - } - - Add - ( - new Label - ( - message, - false, - 0x0386, - Width - 90, - 1 - ) - { - X = 40, - Y = 45 - } - ); - - X = (Client.Game.Window.ClientBounds.Width - Width) >> 1; - Y = (Client.Game.Window.ClientBounds.Height - Height) >> 1; - - // OK - Button b; - - Add - ( - b = new Button(0, 0x0481, 0x0483, 0x0482) - { - Y = Height - 45, - ButtonAction = ButtonAction.Activate - } - ); - - b.X = (Width - b.Width) >> 1; - - - if (menuType == MessageButtonType.OK_CANCEL) - { - Button bCancel; - - Add - ( - bCancel = new Button(1, 0x047E, 0x047F, 0x0480) - { - Y = Height - 45, - ButtonAction = ButtonAction.Activate - } - ); - - b.X = Width / 2 - bCancel.Width; - bCancel.X = Width / 2 - bCancel.Width; - bCancel.X += b.Width + 5; - } - - - WantUpdateSize = false; - - UIManager.KeyboardFocusControl = this; - UIManager.KeyboardFocusControl.SetKeyboardFocus(); - } - - protected override void OnKeyUp(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - base.OnKeyUp(key, mod); - - if (key == SDL.SDL_Keycode.SDLK_RETURN && mod == 0) - { - OnButtonClick(0); - } - } - - public override void OnButtonClick(int buttonID) - { - switch (buttonID) - { - case 0: - _action?.Invoke(true); - Dispose(); - - break; - - case 1: - _action?.Invoke(false); - Dispose(); - - break; - } - } - } - - - internal class EntryDialog : Gump - { - private readonly Action _action; - private readonly StbTextBox _textBox; - - public EntryDialog(int w, int h, string message, Action action) : base(0, 0) - { - CanMove = false; - CanCloseWithRightClick = false; - CanCloseWithEsc = false; - AcceptMouseInput = false; - - IsModal = true; - LayerOrder = UILayer.Over; - WantUpdateSize = false; - - Width = w; - Height = h; - _action = action; - - Add - ( - new ResizePic(0x0A28) - { - Width = w, - Height = h - } - ); - - Label l; - - Add - ( - l = new Label - ( - message, - false, - 0x0386, - Width - 90, - 1 - ) - { - X = 40, - Y = 45 - } - ); - - Add - ( - new ResizePic(0x0BB8) - { - X = 40, - Y = 45 + l.Height + 5, - Width = w - 90, - Height = 25 - } - ); - - int ww = w - 94; - - _textBox = new StbTextBox - ( - 0xFF, - -1, - ww, - true, - FontStyle.BlackBorder | FontStyle.Fixed - ) - { - X = 42, - Y = 45 + l.Height + 7, - Width = ww, - Height = 25 - }; - - Add(_textBox); - - X = (Client.Game.Window.ClientBounds.Width - Width) >> 1; - Y = (Client.Game.Window.ClientBounds.Height - Height) >> 1; - - - // OK - Button b; - - Add - ( - b = new Button(0, 0x0481, 0x0482, 0x0483) - { - Y = Height - 45, - ButtonAction = ButtonAction.Activate - } - ); - - b.X = (Width - b.Width) >> 1; - } - - public override void OnButtonClick(int buttonID) - { - switch (buttonID) - { - case 0: - _action?.Invoke(_textBox.Text); - Dispose(); - - break; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/MiniMapGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/MiniMapGump.cs deleted file mode 100644 index a0a29a9c2..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/MiniMapGump.cs +++ /dev/null @@ -1,480 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.IO; -using System.Xml; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Map; -using ClassicUO.Input; -using ClassicUO.IO; -using ClassicUO.Assets; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class MiniMapGump : Gump - { - private bool _draw; - private int _lastMap = -1; - private long _timeMS; - private bool _useLargeMap; - private ushort _x, - _y; - private static readonly uint[][] _blankGumpsPixels = new uint[4][]; - - const ushort SMALL_MAP_GRAPHIC = 5010; - const ushort BIG_MAP_GRAPHIC = 5011; - - public MiniMapGump() : base(0, 0) - { - CanMove = true; - AcceptMouseInput = true; - CanCloseWithRightClick = true; - } - - public override GumpType GumpType => GumpType.MiniMap; - - public override void Save(XmlTextWriter writer) - { - base.Save(writer); - writer.WriteAttributeString("isminimized", _useLargeMap.ToString()); - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - _useLargeMap = bool.Parse(xml.GetAttribute("isminimized")); - CreateMap(); - } - - private void CreateMap() - { - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump( - _useLargeMap ? BIG_MAP_GRAPHIC : SMALL_MAP_GRAPHIC - ); - - int index = _useLargeMap ? 1 : 0; - - if (_blankGumpsPixels[index] == null) - { - int size = gumpInfo.UV.Width * gumpInfo.UV.Height; - _blankGumpsPixels[index] = new uint[size]; - _blankGumpsPixels[index + 2] = new uint[size]; - gumpInfo.Texture.GetData(0, gumpInfo.UV, _blankGumpsPixels[index], 0, size); - - Array.Copy(_blankGumpsPixels[index], 0, _blankGumpsPixels[index + 2], 0, size); - } - - Width = gumpInfo.UV.Width; - Height = gumpInfo.UV.Height; - CreateMiniMapTexture(gumpInfo.Texture, gumpInfo.UV, true); - } - - public override void Update() - { - if (!World.InGame) - { - return; - } - - if (_lastMap != World.MapIndex) - { - CreateMap(); - _lastMap = World.MapIndex; - } - - if (_timeMS < Time.Ticks) - { - _draw = !_draw; - _timeMS = (long)Time.Ticks + 500; - } - } - - public bool ToggleSize(bool? large = null) - { - if (large.HasValue) - { - _useLargeMap = large.Value; - } - else - { - _useLargeMap = !_useLargeMap; - } - - CreateMap(); - - return _useLargeMap; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsDisposed) - { - return false; - } - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump( - _useLargeMap ? BIG_MAP_GRAPHIC : SMALL_MAP_GRAPHIC - ); - - if (gumpInfo.Texture == null) - { - Dispose(); - - return false; - } - - batcher.Draw(gumpInfo.Texture, new Vector2(x, y), gumpInfo.UV, hueVector); - - CreateMiniMapTexture(gumpInfo.Texture, gumpInfo.UV); - - batcher.Draw(gumpInfo.Texture, new Vector2(x, y), gumpInfo.UV, hueVector); - - if (_draw) - { - int w = Width >> 1; - int h = Height >> 1; - - Texture2D mobilesTextureDot = SolidColorTextureCache.GetTexture(Color.Red); - - foreach (Mobile mob in World.Mobiles.Values) - { - if (mob == World.Player) - { - continue; - } - - int xx = mob.X - World.Player.X; - int yy = mob.Y - World.Player.Y; - - int gx = xx - yy; - int gy = xx + yy; - - hueVector = ShaderHueTranslator.GetHueVector( - Notoriety.GetHue(mob.NotorietyFlag) - ); - - batcher.Draw( - mobilesTextureDot, - new Rectangle(x + w + gx, y + h + gy, 2, 2), - hueVector - ); - } - - //DRAW PLAYER DOT - hueVector = ShaderHueTranslator.GetHueVector(0); - - batcher.Draw( - SolidColorTextureCache.GetTexture(Color.White), - new Rectangle(x + w, y + h, 2, 2), - hueVector - ); - } - - return base.Draw(batcher, x, y); - } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - ToggleSize(); - - return true; - } - - return false; - } - - protected override void UpdateContents() - { - CreateMap(); - } - - private unsafe void CreateMiniMapTexture( - Texture2D texture, - Rectangle bounds, - bool force = false - ) - { - ushort lastX = World.Player.X; - ushort lastY = World.Player.Y; - - if (_x != lastX || _y != lastY) - { - _x = lastX; - _y = lastY; - } - else if (!force) - { - return; - } - - int blockOffsetX = Width >> 2; - int blockOffsetY = Height >> 2; - int gumpCenterX = Width >> 1; - //int gumpCenterY = Height >> 1; - - //0xFF080808 - pixel32 - //0x8421 - pixel16 - int minBlockX = ((lastX - blockOffsetX) >> 3) - 1; - int minBlockY = ((lastY - blockOffsetY) >> 3) - 1; - int maxBlockX = ((lastX + blockOffsetX) >> 3) + 1; - int maxBlockY = ((lastY + blockOffsetY) >> 3) + 1; - - if (minBlockX < 0) - { - minBlockX = 0; - } - - if (minBlockY < 0) - { - minBlockY = 0; - } - - int maxBlockIndex = World.Map.BlocksCount; - int mapBlockHeight = MapLoader.Instance.MapBlocksSize[World.MapIndex, 1]; - int index = _useLargeMap ? 1 : 0; - - _blankGumpsPixels[index].CopyTo(_blankGumpsPixels[index + 2], 0); - - uint[] data = _blankGumpsPixels[index + 2]; - - Point* table = stackalloc Point[2]; - table[0].X = 0; - table[0].Y = 0; - table[1].X = 0; - table[1].Y = 1; - - for (int i = minBlockX; i <= maxBlockX; i++) - { - int blockIndexOffset = i * mapBlockHeight; - - for (int j = minBlockY; j <= maxBlockY; j++) - { - int blockIndex = blockIndexOffset + j; - - if (blockIndex >= maxBlockIndex) - { - break; - } - - ref IndexMap indexMap = ref World.Map.GetIndex(i, j); - - if (indexMap.MapAddress == 0) - { - break; - } - - MapBlock* mp = (MapBlock*)indexMap.MapAddress; - MapCells* cells = (MapCells*)&mp->Cells; - StaticsBlock* sb = (StaticsBlock*)indexMap.StaticAddress; - uint staticCount = indexMap.StaticCount; - - Chunk block = World.Map.GetChunk(blockIndex); - int realBlockX = i << 3; - int realBlockY = j << 3; - - for (int x = 0; x < 8; x++) - { - int px = realBlockX + x - lastX + gumpCenterX; - - for (int y = 0; y < 8; y++) - { - ref MapCells cell = ref cells[(y << 3) + x]; - int color = cell.TileID; - bool isLand = true; - int z = cell.Z; - - for (int c = 0; c < staticCount; ++c) - { - ref StaticsBlock stblock = ref sb[c]; - - if ( - stblock.X == x - && stblock.Y == y - && stblock.Color > 0 - && stblock.Color != 0xFFFF - && GameObject.CanBeDrawn(stblock.Color) - ) - { - if (stblock.Z >= z) - { - color = - stblock.Hue > 0 - ? (ushort)(stblock.Hue + 0x4000) - : stblock.Color; - isLand = stblock.Hue > 0; - - z = stblock.Z; - } - } - } - - if (block != null) - { - GameObject obj = block.Tiles[x, y]; - - while (obj?.TNext != null) - { - obj = obj.TNext; - } - - for (; obj != null; obj = obj.TPrevious) - { - if (obj is Multi) - { - if (obj.Hue == 0) - { - color = obj.Graphic; - isLand = false; - } - else - { - color = obj.Hue + 0x4000; - } - - break; - } - } - } - - if (!isLand) - { - color += 0x4000; - } - - int tableSize = 2; - - if (isLand && color > 0x4000) - { - color = HuesLoader.Instance.GetHueColorRgba5551(16, (ushort) (color - 0x4000)); - } - else - { - color = HuesLoader.Instance.GetRadarColorData(color); - } - - int py = realBlockY + y - lastY; - int gx = px - py; - int gy = px + py; - - CreatePixels( - data, - 0x8000 | color, - gx, - gy, - Width, - Height, - table, - tableSize - ); - } - } - } - } - - fixed (uint* ptr = data) - { - texture.SetDataPointerEXT(0, bounds, (IntPtr)ptr, data.Length * sizeof(uint)); - } - } - - private unsafe void CreatePixels( - uint[] data, - int color, - int x, - int y, - int w, - int h, - Point* table, - int count - ) - { - int px = x; - int py = y; - - for (int i = 0; i < count; i++) - { - px += table[i].X; - py += table[i].Y; - - int gx = px; - - if (gx < 0 || gx >= w) - { - continue; - } - - int gy = py; - - if (gy < 0 || gy >= h) - { - break; - } - - int block = gy * w + gx; - - if (data[block] == 0xFF080808) - { - data[block] = HuesHelper.Color16To32((ushort)color) | 0xFF_00_00_00; - } - } - } - - public override bool Contains(int x, int y) - { - x -= Offset.X; - y -= Offset.Y; - - if (x >= 0 && y >= 0 && x < Width && y < Height) - { - int index = (_useLargeMap ? 1 : 0) + 2; - int pos = (y * Width) + x; - - if (pos < _blankGumpsPixels[index].Length) - { - return _blankGumpsPixels[index][pos] != 0; - } - } - - return false; - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/ModernBookGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/ModernBookGump.cs deleted file mode 100644 index e33b74d95..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/ModernBookGump.cs +++ /dev/null @@ -1,885 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Text; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Network; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class ModernBookGump : Gump - { - internal const int MAX_BOOK_LINES = 8; - private const int MAX_BOOK_CHARS_PER_LINE = 53; - private const int LEFT_X = 38; - private const int RIGHT_X = 223; - private const int UPPER_MARGIN = 34; - private const int PAGE_HEIGHT = 166; - private StbPageTextBox _bookPage; - - private GumpPic _forwardGumpPic, _backwardGumpPic; - private StbTextBox _titleTextBox, _authorTextBox; - - public ModernBookGump - ( - uint serial, - ushort page_count, - string title, - string author, - bool is_editable, - bool old_packet - ) : base(serial, 0) - { - CanMove = true; - AcceptMouseInput = true; - - BookPageCount = page_count; - IsEditable = is_editable; - UseNewHeader = !old_packet; - - BuildGump(title, author); - } - - internal string[] BookLines => _bookPage._pageLines; - internal bool[] _pagesChanged => _bookPage._pagesChanged; - - - public ushort BookPageCount { get; internal set; } - public HashSet KnownPages { get; internal set; } = new HashSet(); - public static bool IsNewBook => Client.Version > ClientVersion.CV_200; - public bool UseNewHeader { get; set; } = true; - public static byte DefaultFont => (byte) (IsNewBook ? 1 : 4); - - public bool IntroChanges => _pagesChanged[0]; - internal int MaxPage => (BookPageCount >> 1) + 1; - - internal void ServerSetBookText() - { - if (BookLines == null || BookLines.Length <= 0) - { - return; - } - - StringBuilder sb = new StringBuilder(); - int sw = _bookPage.renderedText.GetCharWidth(' '); - - for (int i = 0, l = BookLines.Length; i < l; i++) - { - if (BookLines[i] != null && BookLines[i].Contains("\n")) - { - BookLines[i] = BookLines[i].Replace("\n", ""); - } - } - - for (int i = 0, l = BookLines.Length; i < l; i++) - { - int w = IsNewBook ? FontsLoader.Instance.GetWidthUnicode(_bookPage.renderedText.Font, BookLines[i]) : FontsLoader.Instance.GetWidthASCII(_bookPage.renderedText.Font, BookLines[i]); - - sb.Append(BookLines[i]); - - if (BookLines[i] == null) - continue; - - if (i + 1 < l && (string.IsNullOrWhiteSpace(BookLines[i]) && !BookLines[i].Contains("\n") || w + sw < _bookPage.renderedText.MaxWidth)) - { - sb.Append('\n'); - BookLines[i] += '\n'; - } - } - - _bookPage._ServerUpdate = true; - _bookPage.SetText(sb.ToString()); - _bookPage.CaretIndex = 0; - _bookPage.UpdatePageCoords(); - _bookPage._ServerUpdate = false; - } - - - private void BuildGump(string title, string author) - { - CanCloseWithRightClick = true; - - Add - ( - new GumpPic(0, 0, 0x1FE, 0) - { - CanMove = true - } - ); - - Add(_backwardGumpPic = new GumpPic(0, 0, 0x1FF, 0)); - - Add(_forwardGumpPic = new GumpPic(356, 0, 0x200, 0)); - - _forwardGumpPic.MouseUp += (sender, e) => - { - if (e.Button == MouseButtonType.Left && sender is Control ctrl) - { - SetActivePage(ActivePage + 1); - } - }; - - _forwardGumpPic.MouseDoubleClick += (sender, e) => - { - if (e.Button == MouseButtonType.Left && sender is Control ctrl) - { - SetActivePage(MaxPage); - } - }; - - _backwardGumpPic.MouseUp += (sender, e) => - { - if (e.Button == MouseButtonType.Left && sender is Control ctrl) - { - SetActivePage(ActivePage - 1); - } - }; - - _backwardGumpPic.MouseDoubleClick += (sender, e) => - { - if (e.Button == MouseButtonType.Left && sender is Control ctrl) - { - SetActivePage(1); - } - }; - - _bookPage = new StbPageTextBox - ( - DefaultFont, - BookPageCount, - this, - MAX_BOOK_CHARS_PER_LINE * MAX_BOOK_LINES * BookPageCount, - 156, - IsNewBook, - FontStyle.ExtraHeight, - 2 - ) - { - X = 0, - Y = 0, - Height = PAGE_HEIGHT * BookPageCount, - Width = 156, - IsEditable = IsEditable, - Multiline = true - }; - - Add - ( - _titleTextBox = new StbTextBox(DefaultFont, 47, 150, IsNewBook) - { - X = 40, - Y = 60, - Height = 25, - Width = 155, - IsEditable = IsEditable - }, - 1 - ); - - _titleTextBox.SetText(title); - _titleTextBox.TextChanged += PageZero_TextChanged; - Add(new Label(ResGumps.By, true, 1) { X = 40, Y = 130 }, 1); - - Add - ( - _authorTextBox = new StbTextBox(DefaultFont, 29, 150, IsNewBook) - { - X = 40, - Y = 160, - Height = 25, - Width = 155, - IsEditable = IsEditable - }, - 1 - ); - - _authorTextBox.SetText(author); - _authorTextBox.TextChanged += PageZero_TextChanged; - - for (int k = 1, x = 38; k <= BookPageCount; k++) - { - if (k % 2 == 1) - { - x = 223; //right hand page - } - else - { - x = 38; - } - - int page = k + 1; - - if (page % 2 == 1) - { - page += 1; - } - - page >>= 1; - Add(new Label(k.ToString(), true, 1) { X = x + 80, Y = 200 }, page); - } - - ActivePage = 1; - UpdatePageButtonVisibility(); - - Client.Game.Audio.PlaySound(0x0055); - } - - private void PageZero_TextChanged(object sender, EventArgs e) - { - _pagesChanged[0] = true; - } - - private void UpdatePageButtonVisibility() - { - if (ActivePage == 1) - { - _backwardGumpPic.IsVisible = false; - _forwardGumpPic.IsVisible = true; - } - else if (ActivePage == MaxPage) - { - _forwardGumpPic.IsVisible = false; - _backwardGumpPic.IsVisible = true; - } - else - { - _backwardGumpPic.IsVisible = true; - _forwardGumpPic.IsVisible = true; - } - } - - public void SetTile(string title, bool editable) - { - _titleTextBox.SetText(title); - _titleTextBox.IsEditable = editable; - } - - public void SetAuthor(string author, bool editable) - { - _authorTextBox.SetText(author); - _authorTextBox.IsEditable = editable; - } - - private void SetActivePage(int page) - { - page = Math.Min(Math.Max(page, 1), MaxPage); //clamp the value between 1..MaxPage - - if (page != ActivePage) - { - Client.Game.Audio.PlaySound(0x0055); - } - - //Non-editable books may only have data for the currently displayed pages, - //but some servers send their entire contents in one go so we need to keep track of which pages we know - if (!IsEditable) - { - int leftPage = (page - 1) << 1; - int rightPage = leftPage + 1; - - if (leftPage > 0 && !KnownPages.Contains(leftPage)) - { - NetClient.Socket.Send_BookPageDataRequest(LocalSerial, (ushort)leftPage); - } - - if (rightPage < MaxPage * 2 && !KnownPages.Contains(rightPage)) - { - NetClient.Socket.Send_BookPageDataRequest(LocalSerial, (ushort)rightPage); - } - } - else - { - for (int i = 0; i < _pagesChanged.Length; i++) - { - if (_pagesChanged[i]) - { - _pagesChanged[i] = false; - - if (i < 1) - { - if (UseNewHeader) - { - NetClient.Socket.Send_BookHeaderChanged(LocalSerial, _titleTextBox.Text, _authorTextBox.Text); - } - else - { - NetClient.Socket.Send_BookHeaderChanged_Old(LocalSerial, _titleTextBox.Text, _authorTextBox.Text); - } - } - else - { - string[] text = new string[MAX_BOOK_LINES]; - - for (int x = (i - 1) * MAX_BOOK_LINES, l = 0; x < (i - 1) * MAX_BOOK_LINES + 8; x++, l++) - { - text[l] = BookLines[x]; - } - - NetClient.Socket.Send_BookPageData(LocalSerial, text, i); - } - } - } - } - - ActivePage = page; - UpdatePageButtonVisibility(); - - if (UIManager.KeyboardFocusControl == null || UIManager.KeyboardFocusControl != UIManager.SystemChat.TextBoxControl && UIManager.KeyboardFocusControl != _bookPage && page != _bookPage._focusPage / 2 + 1) - { - UIManager.SystemChat.TextBoxControl.SetKeyboardFocus(); - } - } - - public override void OnButtonClick(int buttonID) - { - } - - protected override void CloseWithRightClick() - { - SetActivePage(0); - - base.CloseWithRightClick(); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - if (batcher.ClipBegin(x, y, Width, Height)) - { - RenderedText t = _bookPage.renderedText; - int startpage = (ActivePage - 1) * 2; - - if (startpage < BookPageCount) - { - int poy = _bookPage._pageCoords[startpage, 0], phy = _bookPage._pageCoords[startpage, 1]; - - _bookPage.DrawSelection - ( - batcher, - x + RIGHT_X, - y + UPPER_MARGIN, - poy, - poy + phy - ); - - t.Draw - ( - batcher, - x + RIGHT_X, - y + UPPER_MARGIN, - 0, - poy, - t.Width, - phy - ); - - if (startpage == _bookPage._caretPage) - { - if (_bookPage._caretPos.Y < poy + phy) - { - if (_bookPage._caretPos.Y >= poy) - { - if (_bookPage.HasKeyboardFocus) - { - _bookPage.renderedCaret.Draw - ( - batcher, - _bookPage._caretPos.X + x + RIGHT_X, - _bookPage._caretPos.Y + y + UPPER_MARGIN - poy, - 0, - 0, - _bookPage.renderedCaret.Width, - _bookPage.renderedCaret.Height - ); - } - } - else - { - _bookPage._caretPage = _bookPage.GetCaretPage(); - } - } - else if (_bookPage._caretPos.Y <= _bookPage.Height) - { - if (_bookPage._caretPage + 2 < _bookPage._pagesChanged.Length) - { - _bookPage._focusPage = _bookPage._caretPage++; - SetActivePage(_bookPage._caretPage / 2 + 2); - } - } - } - } - - startpage--; - - if (startpage > 0) - { - int poy = _bookPage._pageCoords[startpage, 0], phy = _bookPage._pageCoords[startpage, 1]; - - _bookPage.DrawSelection - ( - batcher, - x + LEFT_X, - y + UPPER_MARGIN, - poy, - poy + phy - ); - - t.Draw - ( - batcher, - x + LEFT_X, - y + UPPER_MARGIN, - 0, - poy, - t.Width, - phy - ); - - if (startpage == _bookPage._caretPage) - { - if (_bookPage._caretPos.Y < poy + phy) - { - if (_bookPage._caretPos.Y >= poy) - { - if (_bookPage.HasKeyboardFocus) - { - _bookPage.renderedCaret.Draw - ( - batcher, - _bookPage._caretPos.X + x + LEFT_X, - _bookPage._caretPos.Y + y + UPPER_MARGIN - poy, - 0, - 0, - _bookPage.renderedCaret.Width, - _bookPage.renderedCaret.Height - ); - } - } - else if (_bookPage._caretPage > 0) - { - _bookPage._focusPage = _bookPage._caretPage--; - SetActivePage(_bookPage._caretPage / 2 + 1); - } - } - else if (_bookPage._caretPos.Y <= _bookPage.Height) - { - if (_bookPage._caretPage + 2 < _bookPage._pagesChanged.Length) - { - _bookPage._caretPage++; - } - } - } - } - - batcher.ClipEnd(); - } - - return true; - } - - public override void Dispose() - { - base.Dispose(); - _bookPage?.Dispose(); - } - - public override void OnHitTestSuccess(int x, int y, ref Control res) - { - if (!IsDisposed) - { - int page = -1; - - if (ActivePage > 1 && x >= LEFT_X + X && x <= LEFT_X + X + _bookPage.Width) - { - page = (ActivePage - 1) * 2 - 1; - } - else if (ActivePage - 1 < BookPageCount >> 1 && x >= RIGHT_X + X && x <= RIGHT_X + _bookPage.Width + X) - { - page = (ActivePage - 1) * 2; - } - - if (page >= 0 && page < BookPageCount && y >= UPPER_MARGIN + Y && y <= UPPER_MARGIN + PAGE_HEIGHT + Y) - { - _bookPage._focusPage = page; - res = _bookPage; - } - } - } - - private class StbPageTextBox : StbTextBox - { - private static readonly StringBuilder _sb = new StringBuilder(); - private static string[] _handler; - private readonly ModernBookGump _gump; - - public StbPageTextBox - ( - byte font, - int bookpages, - ModernBookGump gump, - int max_char_count = -1, - int maxWidth = 0, - bool isunicode = true, - FontStyle style = FontStyle.None, - ushort hue = 0 - ) : base - ( - font, - max_char_count, - maxWidth, - isunicode, - style, - hue - ) - { - _pageCoords = new int[bookpages, 2]; - _pageLines = new string[bookpages * MAX_BOOK_LINES]; - _pagesChanged = new bool[bookpages + 1]; - Priority = ClickPriority.High; - _gump = gump; - } - - internal Point _caretPos => _caretScreenPosition; - - internal RenderedText renderedText => _rendererText; - internal RenderedText renderedCaret => _rendererCaret; - internal int _caretPage, _focusPage; - internal readonly int[,] _pageCoords; - internal readonly string[] _pageLines; - internal readonly bool[] _pagesChanged; - - internal bool _ServerUpdate; - - internal int GetCaretPage() - { - Point p = _rendererText.GetCaretPosition(CaretIndex); - - for (int i = 0, l = _pageCoords.GetLength(0); i < l; i++) - { - if (p.Y >= _pageCoords[i, 0] && p.Y < _pageCoords[i, 0] + _pageCoords[i, 1]) - { - return i; - } - } - - return 0; - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - if (IsEditable) - { - SetKeyboardFocus(); - } - - if (!NoSelection) - { - _leftWasDown = true; - } - - if (_focusPage >= 0 && _focusPage < _pageCoords.GetLength(0)) - { - if (_focusPage % 2 == 0) - { - x -= RIGHT_X + _gump.X; - } - else - { - x -= LEFT_X + _gump.X; - } - - y += _pageCoords[_focusPage, 0] - (UPPER_MARGIN + _gump.Y); - } - - Stb.Click(x, y); - UpdateCaretScreenPosition(); - _caretPage = GetCaretPage(); - } - } - - protected override void OnMouseOver(int x, int y) - { - if (_leftWasDown) - { - if (_focusPage >= 0 && _focusPage < _pageCoords.GetLength(0)) - { - if (_focusPage % 2 == 0) - { - x -= RIGHT_X + _gump.X; - } - else - { - x -= LEFT_X + _gump.X; - } - - y += _pageCoords[_focusPage, 0] - (UPPER_MARGIN + _gump.Y); - } - - Stb.Drag(x, y); - } - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (_focusPage >= 0 && _focusPage < _pageCoords.GetLength(0)) - { - if (_focusPage % 2 == 0) - { - x -= RIGHT_X + _gump.X; - } - else - { - x -= LEFT_X + _gump.X; - } - - y += _pageCoords[_focusPage, 0] - (UPPER_MARGIN + _gump.Y); - } - - base.OnMouseUp(x, y, button); - } - - internal void UpdatePageCoords() - { - MultilinesFontInfo info = _rendererText.GetInfo(); - - for (int page = 0, y = 0; page < _pageCoords.GetLength(0); page++) - { - _pageCoords[page, 0] = y; - _pageCoords[page, 1] = 0; - - for (int i = 0; i < MAX_BOOK_LINES; i++) - { - if (info == null) - { - break; - } - - _pageCoords[page, 1] += info.MaxHeight; - info = info.Next; - } - - y += _pageCoords[page, 1]; - } - } - - internal void DrawSelection(UltimaBatcher2D batcher, int x, int y, int starty, int endy) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0, false, 0.5f); - - int selectStart = Math.Min(Stb.SelectStart, Stb.SelectEnd); - int selectEnd = Math.Max(Stb.SelectStart, Stb.SelectEnd); - - if (selectStart < selectEnd) - { - MultilinesFontInfo info = _rendererText.GetInfo(); - - int drawY = 1; - int start = 0; - - while (info != null && selectStart < selectEnd) - { - // ok we are inside the selection - if (selectStart >= start && selectStart < start + info.CharCount) - { - int startSelectionIndex = selectStart - start; - - // calculate offset x - int drawX = 0; - - for (int i = 0; i < startSelectionIndex; i++) - { - drawX += _rendererText.GetCharWidth(info.Data[i].Item); - } - - // selection is gone. Bye bye - if (selectEnd >= start && selectEnd < start + info.CharCount) - { - int count = selectEnd - selectStart; - - int endX = 0; - - // calculate width - for (int k = 0; k < count; k++) - { - endX += _rendererText.GetCharWidth(info.Data[startSelectionIndex + k].Item); - } - - if (drawY >= starty && drawY <= endy) - { - batcher.Draw - ( - SolidColorTextureCache.GetTexture(SELECTION_COLOR), - new Rectangle - ( - x + drawX, - y + drawY - starty, - endX, - info.MaxHeight + 1 - ), - hueVector - ); - } - - break; - } - - - // do the whole line - if (drawY >= starty && drawY <= endy) - { - batcher.Draw - ( - SolidColorTextureCache.GetTexture(SELECTION_COLOR), - new Rectangle - ( - x + drawX, - y + drawY - starty, - info.Width - drawX, - info.MaxHeight + 1 - ), - hueVector - ); - } - - // first selection is gone. M - selectStart = start + info.CharCount; - } - - start += info.CharCount; - drawY += info.MaxHeight; - info = info.Next; - } - } - } - - protected override void OnTextChanged() - { - _is_writing = true; - - if (!_ServerUpdate) - { - if (_handler == null || _handler.Length < _pageLines.Length) - { - _handler = new string[_pageLines.Length]; - } - - string[] split = Text.Split('\n'); - - for (int i = 0, l = 0; i < split.Length && l < _pageLines.Length; i++) - { - if (split[i].Length > 0) - { - for (int p = 0, w = 0, pw = _rendererText.GetCharWidth(split[i][p]);; pw = _rendererText.GetCharWidth(split[i][p])) - { - if (w + pw > _rendererText.MaxWidth) - { - _handler[l] = _sb.ToString(); - _sb.Clear(); - l++; - //CaretIndex++; - w = 0; - - if (l >= _pageLines.Length) - { - break; - } - } - - w += pw; - _sb.Append(split[i][p]); - p++; - - if (p >= split[i].Length) - { - _sb.Append('\n'); - _handler[l] = _sb.ToString(); - _sb.Clear(); - l++; - - break; - } - } - } - else - { - _handler[l] = "\n"; - l++; - //_sb.Append('\n'); - } - } - - _sb.Clear(); - - for (int i = 0; i < _pageLines.Length; i++) - { - if (!_pagesChanged[(i >> 3) + 1] && _handler[i] != _pageLines[i]) - { - _pagesChanged[(i >> 3) + 1] = true; - } - - _sb.Append(_pageLines[i] = _handler[i]); - } - - _rendererText.Text = _sb.ToString(); //whole reformatted book - _sb.Clear(); - UpdatePageCoords(); - } - - base.OnTextChanged(); - _is_writing = false; - } - - protected override void CloseWithRightClick() - { - if (_gump != null && !_gump.IsDisposed) - { - _gump.CloseWithRightClick(); - } - else - { - base.CloseWithRightClick(); - } - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/ModernColorPicker.cs b/src/ClassicUO.Client/Game/UI/Gumps/ModernColorPicker.cs deleted file mode 100644 index 4a3303d4f..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/ModernColorPicker.cs +++ /dev/null @@ -1,223 +0,0 @@ -using ClassicUO.Assets; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using System; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class ModernColorPicker : Gump - { - private const int WIDTH = 200, HEIGHT = 400; - - private BorderControl borderControl; - private GumpPicTiled backgroundTexture; - private Area area; - - private const int ROWS = 20; - private const int COLUMNS = 10; - private readonly Action hueChanged; - private readonly uint serial; - private int _cPage = 0; - private int cPage - { - get { return _cPage; } - set - { - if (value < 0) - { - _cPage = 14; - return; - } - if (value > 14) - { - _cPage = 0; - return; - } - - _cPage = value; - } - } - - public ModernColorPicker(Action hueChanged, uint serial = 0) : base(0, 0) - { - CanCloseWithRightClick = true; - CanMove = true; - AcceptMouseInput = true; - this.hueChanged = hueChanged; - this.serial = serial; - borderControl = new BorderControl(0, 0, WIDTH, HEIGHT, 10); - int graphic = 9270, borderSize = 10; - backgroundTexture = new GumpPicTiled(borderSize, borderSize, WIDTH - borderSize * 2, HEIGHT - borderSize * 2, (ushort)(graphic + 4)); - - borderControl.T_Left = (ushort)graphic; - borderControl.H_Border = (ushort)(graphic + 1); - borderControl.T_Right = (ushort)(graphic + 2); - borderControl.V_Border = (ushort)(graphic + 3); - borderControl.V_Right_Border = (ushort)(graphic + 5); - borderControl.B_Left = (ushort)(graphic + 6); - borderControl.H_Bottom_Border = (ushort)(graphic + 7); - borderControl.B_Right = (ushort)(graphic + 8); - Add(borderControl); - Add(backgroundTexture); - Add(area = new Area(false) { X = borderSize, Y = borderSize }); - - FillHueDisplays(); - NiceButton prev, next; - - Label page = new Label(cPage.ToString(), true, 0xffff, 30, align: TEXT_ALIGN_TYPE.TS_CENTER); - page.X = (WIDTH / 2) - 10; - page.Y = HEIGHT - borderSize - 20; - Add(page); - - Add(prev = new NiceButton(borderSize, HEIGHT - borderSize - 20, 20, 20, ButtonAction.Activate, "<") { IsSelectable = false }); - prev.MouseUp += (sender, e) => { if (e.Button == Input.MouseButtonType.Left) { cPage--; FillHueDisplays(cPage); page.Text = (cPage + 1).ToString(); } }; - - Add(next = new NiceButton(WIDTH - borderSize - 20, HEIGHT - borderSize - 20, 20, 20, ButtonAction.Activate, ">") { IsSelectable = false }); - next.MouseUp += (sender, e) => { if (e.Button == Input.MouseButtonType.Left) { cPage++; FillHueDisplays(cPage); page.Text = (cPage + 1).ToString(); } }; - - } - - private void FillHueDisplays(int page = 0) - { - if (page < 0) - page = 0; - foreach (Control c in area.Children) - c.Dispose(); - - for (int col = 1; col < COLUMNS + 1; col++) - { - for (int row = 1; row < ROWS + 1; row++) - { - int _ = row + ((col - 1) * ROWS); - area.Add(new HueDisplay((ushort)(_ + (page * (ROWS * COLUMNS)) - 1), hueChanged, sendSysMessage: serial == 8787 ? true : false) { X = (col - 1) * 18, Y = (row - 1) * 18 }); - } - } - } - - public class HueDisplay : Control - { - private ushort hue; - private readonly Action hueChanged; - private readonly bool isClickable; - private readonly bool sendSysMessage; - private Rectangle rect; - private Rectangle bounds; - private Texture2D texture; - private Vector3 hueVector; - private bool flash = false; - private float flashAlpha = 1f; - private bool rev = false; - - public ushort Hue - { - get { return hue; } - set - { - hue = value; - HueChanged?.Invoke(this, null); - hueChanged?.Invoke(value); - if (!isClickable) - SetTooltip(hue.ToString()); - else - SetTooltip($"Click to select a hue ({hue})"); - } - } - - public event EventHandler HueChanged; - - public HueDisplay(ushort hue, Action hueChanged, bool isClickable = false, bool sendSysMessage = false) - { - hueVector = ShaderHueTranslator.GetHueVector(hue, true, 1); - ref readonly var staticArt = ref Client.Game.Arts.GetArt(0x0FAB); - texture = staticArt.Texture; - rect = Client.Game.Arts.GetRealArtBounds(0x0FAB); - Width = 18; - Height = 18; - this.bounds = staticArt.UV; - CanMove = true; - CanCloseWithRightClick = true; - AcceptMouseInput = true; - if (!isClickable) - SetTooltip(hue.ToString()); - else - SetTooltip($"Click to select a hue ({hue})"); - this.hue = hue; - this.hueChanged = hueChanged; - this.isClickable = isClickable; - this.sendSysMessage = sendSysMessage; - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - base.OnMouseUp(x, y, button); - - if (button == MouseButtonType.Left) - { - if (isClickable) - { - UIManager.GetGump()?.Dispose(); - UIManager.Add(new ModernColorPicker(s => Hue = s) { X = 100, Y = 100 }); - } - else - { - hueChanged?.Invoke(hue); - flash = true; - } - if (sendSysMessage) - GameActions.Print($"Selected hue: {hue}"); - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - if (texture != null) - { - if (isClickable) - hueVector = ShaderHueTranslator.GetHueVector(hue, true, 1); - if (flash) - { - hueVector.Z = flashAlpha; - if (!rev) - flashAlpha -= 0.1f; - else - flashAlpha += 0.1f; - if (flashAlpha <= 0) - rev = true; - else if (flashAlpha >= 1) - { - rev = false; - flash = false; - } - - } - batcher.Draw - ( - texture, - new Rectangle - ( - x, - y, - Width, - Height - ), - new Rectangle - ( - bounds.X + rect.X, - bounds.Y + rect.Y, - rect.Width, - rect.Height - ), - hueVector - ); - } - return true; - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/ModernOptionsGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/ModernOptionsGump.cs deleted file mode 100644 index f13a34829..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/ModernOptionsGump.cs +++ /dev/null @@ -1,6343 +0,0 @@ -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using SDL2; -using StbTextEditSharp; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net.Http; -using System.Threading.Tasks; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class ModernOptionsGump : Gump - { - private LeftSideMenuRightSideContent mainContent; - private List options = new List(); - - public static string SearchText { get; private set; } = string.Empty; - public static event EventHandler SearchValueChanged; - private Profile profile; - private ModernOptionsGumpLanguage lang; - - - public ModernOptionsGump() : base(0, 0) - { - lang = Language.Instance.GetModernOptionsGumpLanguage; - profile = ProfileManager.CurrentProfile; - CanMove = true; - CanCloseWithRightClick = true; - AcceptMouseInput = true; - Width = 900; - Height = 700; - - X = (Client.Game.Window.ClientBounds.Width >> 1) - (Width >> 1); - Y = (Client.Game.Window.ClientBounds.Height >> 1) - (Height >> 1); - - Add(new ColorBox(Width, Height, Theme.BACKGROUND) { AcceptMouseInput = true, CanMove = true, Alpha = 0.85f }); - - Add(new ColorBox(Width, 40, Theme.SEARCH_BACKGROUND) { AcceptMouseInput = true, CanMove = true, Alpha = 0.85f }); - - Add(new TextBox(lang.OptionsTitle, Theme.FONT, 30, null, Color.White, strokeEffect: false) { X = 10, Y = 7 }); - - Control c; - Add(c = new TextBox(lang.Search, Theme.FONT, 30, null, Color.White, strokeEffect: false) { Y = 7 }); - - InputField search; - Add(search = new InputField(400, 30) { X = Width - 405, Y = 5 }); - search.TextChanged += (s, e) => { SearchText = search.Text; SearchValueChanged.Raise(); }; - - c.X = search.X - c.Width - 5; - - Add(mainContent = new LeftSideMenuRightSideContent(Width, Height - 40, (int)(Width * 0.23)) { Y = 40 }); - - ModernButton b; - mainContent.AddToLeft(b = CategoryButton(lang.ButtonGeneral, (int)PAGE.General, mainContent.LeftWidth)); - b.IsSelected = true; - mainContent.AddToLeft(CategoryButton(lang.ButtonSound, (int)PAGE.Sound, mainContent.LeftWidth)); - mainContent.AddToLeft(CategoryButton(lang.ButtonVideo, (int)PAGE.Video, mainContent.LeftWidth)); - mainContent.AddToLeft(CategoryButton(lang.ButtonMacros, (int)PAGE.Macros, mainContent.LeftWidth)); - mainContent.AddToLeft(CategoryButton(lang.ButtonTooltips, (int)PAGE.Tooltip, mainContent.LeftWidth)); - mainContent.AddToLeft(CategoryButton(lang.ButtonSpeech, (int)PAGE.Speech, mainContent.LeftWidth)); - mainContent.AddToLeft(CategoryButton(lang.ButtonCombatSpells, (int)PAGE.CombatSpells, mainContent.LeftWidth)); - mainContent.AddToLeft(CategoryButton(lang.ButtonCounters, (int)PAGE.Counters, mainContent.LeftWidth)); - mainContent.AddToLeft(CategoryButton(lang.ButtonInfobar, (int)PAGE.InfoBar, mainContent.LeftWidth)); - mainContent.AddToLeft(CategoryButton(lang.ButtonContainers, (int)PAGE.Containers, mainContent.LeftWidth)); - mainContent.AddToLeft(CategoryButton(lang.ButtonExperimental, (int)PAGE.Experimental, mainContent.LeftWidth)); - mainContent.AddToLeft(b = new ModernButton(0, 0, mainContent.LeftWidth, 40, ButtonAction.Activate, lang.ButtonIgnoreList, Theme.BUTTON_FONT_COLOR) { ButtonParameter = 999 }); - b.MouseUp += (s, e) => - { - UIManager.GetGump()?.Dispose(); - UIManager.Add(new IgnoreManagerGump()); - }; - mainContent.AddToLeft(CategoryButton(lang.ButtonNameplates, (int)PAGE.NameplateOptions, mainContent.LeftWidth)); - mainContent.AddToLeft(CategoryButton(lang.ButtonCooldowns, (int)PAGE.TUOCooldowns, mainContent.LeftWidth)); - mainContent.AddToLeft(CategoryButton(lang.ButtonTazUO, (int)PAGE.TUOOptions, mainContent.LeftWidth)); - - BuildGeneral(); - BuildSound(); - BuildVideo(); - BuildMacros(); - BuildTooltips(); - BuildSpeech(); - BuildCombatSpells(); - BuildCounters(); - BuildInfoBar(); - BuildContainers(); - BuildExperimental(); - BuildNameplates(); - BuildCooldowns(); - BuildTazUO(); - - foreach (SettingsOption option in options) - { - mainContent.AddToRight(option.FullControl, false, (int)option.OptionsPage); - } - - ChangePage((int)PAGE.General); - } - - private void BuildGeneral() - { - LeftSideMenuRightSideContent content = new LeftSideMenuRightSideContent(mainContent.RightWidth, mainContent.Height, (int)(mainContent.RightWidth * 0.3)); - Control c; - int page; - - #region General - page = ((int)PAGE.General + 1000); - content.AddToLeft(SubCategoryButton(lang.ButtonGeneral, page, content.LeftWidth)); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.HighlightObjects, isChecked: profile.HighlightGameObjects, valueChanged: (b) => { profile.HighlightGameObjects = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.Pathfinding, isChecked: profile.EnablePathfind, valueChanged: (b) => { profile.EnablePathfind = b; }), true, page); - content.Indent(); - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.ShiftPathfinding, isChecked: profile.UseShiftToPathfind, valueChanged: (b) => { profile.UseShiftToPathfind = b; }), true, page); - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.SingleClickPathfind, isChecked: profile.PathfindSingleClick, valueChanged: (b) => { profile.PathfindSingleClick = b; }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.AlwaysRun, isChecked: profile.AlwaysRun, valueChanged: (b) => { profile.AlwaysRun = b; }), true, page); - content.Indent(); - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.RunUnlessHidden, isChecked: profile.AlwaysRunUnlessHidden, valueChanged: (b) => { profile.AlwaysRunUnlessHidden = b; }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.AutoOpenDoors, isChecked: profile.AutoOpenDoors, valueChanged: (b) => { profile.AutoOpenDoors = b; }), true, page); - content.Indent(); - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.AutoOpenPathfinding, isChecked: profile.SmoothDoors, valueChanged: (b) => { profile.SmoothDoors = b; }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.AutoOpenCorpse, isChecked: profile.AutoOpenCorpses, valueChanged: (b) => { profile.AutoOpenCorpses = b; }), true, page); - content.Indent(); - content.AddToRight(new SliderWithLabel(lang.GetGeneral.CorpseOpenDistance, 0, Theme.SLIDER_WIDTH, 0, 5, profile.AutoOpenCorpseRange, (r) => { profile.AutoOpenCorpseRange = r; }), true, page); - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.CorpseSkipEmpty, isChecked: profile.SkipEmptyCorpse, valueChanged: (b) => { profile.SkipEmptyCorpse = b; }), true, page); - content.AddToRight(new ComboBoxWithLabel(lang.GetGeneral.CorpseOpenOptions, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetGeneral.CorpseOptNone, lang.GetGeneral.CorpseOptNotTarg, lang.GetGeneral.CorpseOptNotHiding, lang.GetGeneral.CorpseOptBoth }, profile.CorpseOpenOptions, (s, n) => { profile.CorpseOpenOptions = s; }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.OutRangeColor, isChecked: profile.NoColorObjectsOutOfRange, valueChanged: (b) => { profile.NoColorObjectsOutOfRange = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(c = new CheckboxWithLabel(lang.GetGeneral.SallosEasyGrab, isChecked: profile.SallosEasyGrab, valueChanged: (b) => { profile.SallosEasyGrab = b; }), true, page); - c.SetTooltip(lang.GetGeneral.SallosTooltip); - - if (Client.Version > ClientVersion.CV_70796) - { - content.BlankLine(); - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.ShowHouseContent, isChecked: profile.ShowHouseContent, valueChanged: (b) => { profile.ShowHouseContent = b; }), true, page); - } - - if (Client.Version >= ClientVersion.CV_7090) - { - content.BlankLine(); - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.SmoothBoat, isChecked: profile.UseSmoothBoatMovement, valueChanged: (b) => { profile.UseSmoothBoatMovement = b; }), true, page); - } - - content.BlankLine(); - #endregion - - #region Mobiles - page = ((int)PAGE.General + 1001); - content.AddToLeft(SubCategoryButton(lang.ButtonMobiles, page, content.LeftWidth)); - content.ResetRightSide(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.ShowMobileHP, isChecked: profile.ShowMobilesHP, valueChanged: (b) => { profile.ShowMobilesHP = b; }), true, page); - content.Indent(); - content.AddToRight(new ComboBoxWithLabel(lang.GetGeneral.MobileHPType, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetGeneral.HPTypePerc, lang.GetGeneral.HPTypeBar, lang.GetGeneral.HPTypeNBoth }, profile.MobileHPType, (s, n) => { profile.MobileHPType = s; }), true, page); - content.AddToRight(new ComboBoxWithLabel(lang.GetGeneral.HPShowWhen, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetGeneral.HPShowWhen_Always, lang.GetGeneral.HPShowWhen_Less100, lang.GetGeneral.HPShowWhen_Smart }, profile.MobileHPShowWhen, (s, n) => { profile.MobileHPShowWhen = s; }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.HighlightPoisoned, isChecked: profile.HighlightMobilesByPoisoned, valueChanged: (b) => { profile.HighlightMobilesByPoisoned = b; }), true, page); - content.Indent(); - content.AddToRight(new ModernColorPickerWithLabel(lang.GetGeneral.PoisonHighlightColor, profile.PoisonHue, (h) => { profile.PoisonHue = h; }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.HighlightPara, isChecked: profile.HighlightMobilesByParalize, valueChanged: (b) => { profile.HighlightMobilesByParalize = b; }), true, page); - content.Indent(); - content.AddToRight(new ModernColorPickerWithLabel(lang.GetGeneral.ParaHighlightColor, profile.ParalyzedHue, (h) => { profile.ParalyzedHue = h; }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.HighlightInvul, isChecked: profile.HighlightMobilesByInvul, valueChanged: (b) => { profile.HighlightMobilesByInvul = b; }), true, page); - content.Indent(); - content.AddToRight(new ModernColorPickerWithLabel(lang.GetGeneral.InvulHighlightColor, profile.InvulnerableHue, (h) => { profile.InvulnerableHue = h; }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.IncomingMobiles, isChecked: profile.ShowNewMobileNameIncoming, valueChanged: (b) => { profile.ShowNewMobileNameIncoming = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.IncomingCorpses, isChecked: profile.ShowNewCorpseNameIncoming, valueChanged: (b) => { profile.ShowNewCorpseNameIncoming = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new ComboBoxWithLabel(lang.GetGeneral.AuraUnderFeet, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetGeneral.AuraOptDisabled, lang.GetGeneral.AuroOptWarmode, lang.GetGeneral.AuraOptCtrlShift, lang.GetGeneral.AuraOptAlways }, profile.AuraUnderFeetType, (s, n) => { profile.AuraUnderFeetType = s; }), true, page); - content.Indent(); - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.AuraForParty, isChecked: profile.PartyAura, valueChanged: (b) => { profile.PartyAura = b; }), true, page); - content.Indent(); - content.AddToRight(new ModernColorPickerWithLabel(lang.GetGeneral.AuraPartyColor, profile.PartyAuraHue, (h) => { profile.PartyAuraHue = h; }), true, page); - content.RemoveIndent(); - content.RemoveIndent(); - #endregion - - #region Gumps & Context - page = ((int)PAGE.General + 1002); - content.AddToLeft(SubCategoryButton(lang.ButtonGumpContext, page, content.LeftWidth)); - content.ResetRightSide(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.DisableTopMenu, isChecked: profile.TopbarGumpIsDisabled, valueChanged: (b) => { profile.TopbarGumpIsDisabled = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.AltForAnchorsGumps, isChecked: profile.HoldDownKeyAltToCloseAnchored, valueChanged: (b) => { profile.HoldDownKeyAltToCloseAnchored = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.AltToMoveGumps, isChecked: profile.HoldAltToMoveGumps, valueChanged: (b) => { profile.HoldAltToMoveGumps = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.CloseEntireAnchorWithRClick, isChecked: profile.CloseAllAnchoredGumpsInGroupWithRightClick, valueChanged: (b) => { profile.CloseAllAnchoredGumpsInGroupWithRightClick = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.OriginalSkillsGump, isChecked: profile.StandardSkillsGump, valueChanged: (b) => { profile.StandardSkillsGump = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.OldStatusGump, isChecked: profile.UseOldStatusGump, valueChanged: (b) => { profile.UseOldStatusGump = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.PartyInviteGump, isChecked: profile.PartyInviteGump, valueChanged: (b) => { profile.PartyInviteGump = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.ModernHealthBars, isChecked: profile.CustomBarsToggled, valueChanged: (b) => { profile.CustomBarsToggled = b; }), true, page); - content.Indent(); - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.ModernHPBlackBG, isChecked: profile.CBBlackBGToggled, valueChanged: (b) => { profile.CBBlackBGToggled = b; }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.SaveHPBars, isChecked: profile.SaveHealthbars, valueChanged: (b) => { profile.SaveHealthbars = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new ComboBoxWithLabel(lang.GetGeneral.CloseHPGumpsWhen, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetGeneral.CloseHPOptDisable, lang.GetGeneral.CloseHPOptOOR, lang.GetGeneral.CloseHPOptDead, lang.GetGeneral.CloseHPOptBoth }, profile.CloseHealthBarType, (s, n) => { profile.CloseHealthBarType = s; }), true, page); - - content.BlankLine(); - - content.AddToRight(c = new ComboBoxWithLabel(lang.GetGeneral.GridLoot, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetGeneral.GridLootOptDisable, lang.GetGeneral.GridLootOptOnly, lang.GetGeneral.GridLootOptBoth }, profile.GridLootType, (s, n) => { profile.GridLootType = s; }), true, page); - c.SetTooltip(lang.GetGeneral.GridLootTooltip); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.ShiftContext, isChecked: profile.HoldShiftForContext, valueChanged: (b) => { profile.HoldShiftForContext = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.ShiftSplit, isChecked: profile.HoldShiftToSplitStack, valueChanged: (b) => { profile.HoldShiftToSplitStack = b; }), true, page); - #endregion - - #region Misc - page = ((int)PAGE.General + 1003); - content.AddToLeft(SubCategoryButton(lang.ButtonMisc, page, content.LeftWidth)); - content.ResetRightSide(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.EnableCOT, isChecked: profile.UseCircleOfTransparency, valueChanged: (b) => { profile.UseCircleOfTransparency = b; }), true, page); - content.Indent(); - content.AddToRight(new SliderWithLabel(lang.GetGeneral.COTDistance, 0, Theme.SLIDER_WIDTH, Constants.MIN_CIRCLE_OF_TRANSPARENCY_RADIUS, Constants.MAX_CIRCLE_OF_TRANSPARENCY_RADIUS, profile.CircleOfTransparencyRadius, (r) => { profile.CircleOfTransparencyRadius = r; }), true, page); - content.AddToRight(new ComboBoxWithLabel(lang.GetGeneral.COTType, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetGeneral.COTTypeOptFull, lang.GetGeneral.COTTypeOptGrad, lang.GetGeneral.COTTypeOptModern }, profile.CircleOfTransparencyType, (s, n) => { profile.CircleOfTransparencyType = s; }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.HideScreenshotMessage, isChecked: profile.HideScreenshotStoredInMessage, valueChanged: (b) => { profile.HideScreenshotStoredInMessage = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.ObjFade, isChecked: profile.UseObjectsFading, valueChanged: (b) => { profile.UseObjectsFading = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.TextFade, isChecked: profile.TextFading, valueChanged: (b) => { profile.TextFading = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.CursorRange, isChecked: profile.ShowTargetRangeIndicator, valueChanged: (b) => { profile.ShowTargetRangeIndicator = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.DragSelectHP, isChecked: profile.EnableDragSelect, valueChanged: (b) => { profile.EnableDragSelect = b; }), true, page); - content.Indent(); - content.AddToRight(new ComboBoxWithLabel(lang.GetGeneral.DragKeyMod, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetGeneral.SharedNone, lang.GetGeneral.SharedCtrl, lang.GetGeneral.SharedShift }, profile.DragSelectModifierKey, (s, n) => { profile.DragSelectModifierKey = s; }), true, page); - content.AddToRight(new ComboBoxWithLabel(lang.GetGeneral.DragPlayersOnly, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetGeneral.SharedNone, lang.GetGeneral.SharedCtrl, lang.GetGeneral.SharedShift }, profile.DragSelect_PlayersModifier, (s, n) => { profile.DragSelect_PlayersModifier = s; }), true, page); - content.AddToRight(new ComboBoxWithLabel(lang.GetGeneral.DragMobsOnly, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetGeneral.SharedNone, lang.GetGeneral.SharedCtrl, lang.GetGeneral.SharedShift }, profile.DragSelect_MonstersModifier, (s, n) => { profile.DragSelect_MonstersModifier = s; }), true, page); - content.AddToRight(new ComboBoxWithLabel(lang.GetGeneral.DragNameplatesOnly, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetGeneral.SharedNone, lang.GetGeneral.SharedCtrl, lang.GetGeneral.SharedShift }, profile.DragSelect_NameplateModifier, (s, n) => { profile.DragSelect_NameplateModifier = s; }), true, page); - content.AddToRight(new SliderWithLabel(lang.GetGeneral.DragX, 0, Theme.SLIDER_WIDTH, 0, Client.Game.Scene.Camera.Bounds.Width, profile.DragSelectStartX, (r) => { profile.DragSelectStartX = r; }), true, page); - content.AddToRight(new SliderWithLabel(lang.GetGeneral.DragY, 0, Theme.SLIDER_WIDTH, 0, Client.Game.Scene.Camera.Bounds.Width, profile.DragSelectStartY, (r) => { profile.DragSelectStartY = r; }), true, page); - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.DragAnchored, isChecked: profile.DragSelectAsAnchor, valueChanged: (b) => { profile.DragSelectAsAnchor = b; }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.ShowStatsChangedMsg, isChecked: profile.ShowStatsChangedMessage, valueChanged: (b) => { profile.ShowStatsChangedMessage = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.ShowSkillsChangedMsg, isChecked: profile.ShowSkillsChangedMessage, valueChanged: (b) => { profile.ShowStatsChangedMessage = b; }), true, page); - content.Indent(); - content.AddToRight(new SliderWithLabel(lang.GetGeneral.ChangeVolume, 0, Theme.SLIDER_WIDTH, 0, 100, profile.ShowSkillsChangedDeltaValue, (r) => { profile.ShowSkillsChangedDeltaValue = r; }), true, page); - content.RemoveIndent(); - #endregion - - #region Terrain and statics - page = ((int)PAGE.General + 1004); - content.AddToLeft(SubCategoryButton(lang.ButtonTerrainStatics, page, content.LeftWidth)); - content.ResetRightSide(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.HideRoof, isChecked: !profile.DrawRoofs, valueChanged: (b) => { profile.DrawRoofs = !b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.TreesToStump, isChecked: profile.TreeToStumps, valueChanged: (b) => { profile.TreeToStumps = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetGeneral.HideVegetation, isChecked: profile.HideVegetation, valueChanged: (b) => { profile.HideVegetation = b; }), true, page); - - //content.BlankLine(); - - //content.AddToRight(new CheckboxWithLabel("Mark cave tiles", isChecked: profile.EnableCaveBorder, valueChanged: (b) => { profile.EnableCaveBorder = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new ComboBoxWithLabel(lang.GetGeneral.MagicFieldType, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetGeneral.MagicFieldOpt_Normal, lang.GetGeneral.MagicFieldOpt_Static, lang.GetGeneral.MagicFieldOpt_Tile }, profile.FieldsType, (s, n) => { profile.FieldsType = s; }), true, page); - - #endregion - - options.Add(new SettingsOption( - "", - content, - mainContent.RightWidth, - PAGE.General - )); - } - - private void BuildSound() - { - SettingsOption s; - - PositionHelper.Reset(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetSound.EnableSound, 0, profile.EnableSound, (b) => { profile.EnableSound = b; }), - mainContent.RightWidth, - PAGE.Sound - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.Indent(); - - options.Add(s = new SettingsOption( - "", - new SliderWithLabel(lang.GetSound.SharedVolume, 0, Theme.SLIDER_WIDTH, 0, 100, profile.SoundVolume, (i) => { profile.SoundVolume = i; }), - mainContent.RightWidth, - PAGE.Sound - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.RemoveIndent(); - PositionHelper.BlankLine(); - - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetSound.EnableMusic, 0, profile.EnableMusic, (b) => { profile.EnableMusic = b; }), - mainContent.RightWidth, - PAGE.Sound - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.Indent(); - - options.Add(s = new SettingsOption( - "", - new SliderWithLabel(lang.GetSound.SharedVolume, 0, Theme.SLIDER_WIDTH, 0, 100, profile.MusicVolume, (i) => { profile.MusicVolume = i; }), - mainContent.RightWidth, - PAGE.Sound - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.RemoveIndent(); - PositionHelper.BlankLine(); - - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetSound.LoginMusic, 0, Settings.GlobalSettings.LoginMusic, (b) => { Settings.GlobalSettings.LoginMusic = b; }), - mainContent.RightWidth, - PAGE.Sound - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.Indent(); - - options.Add(s = new SettingsOption( - "", - new SliderWithLabel(lang.GetSound.SharedVolume, 0, Theme.SLIDER_WIDTH, 0, 100, Settings.GlobalSettings.LoginMusicVolume, (i) => { Settings.GlobalSettings.LoginMusicVolume = i; }), - mainContent.RightWidth, - PAGE.Sound - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.RemoveIndent(); - PositionHelper.BlankLine(); - - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetSound.PlayFootsteps, 0, profile.EnableFootstepsSound, (b) => { profile.EnableFootstepsSound = b; }), - mainContent.RightWidth, - PAGE.Sound - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.BlankLine(); - - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetSound.CombatMusic, 0, profile.EnableCombatMusic, (b) => { profile.EnableCombatMusic = b; }), - mainContent.RightWidth, - PAGE.Sound - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.BlankLine(); - - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetSound.BackgroundMusic, 0, profile.ReproduceSoundsInBackground, (b) => { profile.ReproduceSoundsInBackground = b; }), - mainContent.RightWidth, - PAGE.Sound - )); - PositionHelper.PositionControl(s.FullControl); - } - - private void BuildVideo() - { - LeftSideMenuRightSideContent content = new LeftSideMenuRightSideContent(mainContent.RightWidth, mainContent.Height, (int)(mainContent.RightWidth * 0.3)); - #region Game window - int page = ((int)PAGE.Video + 1000); - content.AddToLeft(SubCategoryButton(lang.ButtonGameWindow, page, content.LeftWidth)); - - content.AddToRight(new SliderWithLabel(lang.GetVideo.FPSCap, 0, Theme.SLIDER_WIDTH, Constants.MIN_FPS, Constants.MAX_FPS, Settings.GlobalSettings.FPS, (r) => { Settings.GlobalSettings.FPS = r; Client.Game.SetRefreshRate(r); }), true, page); - content.Indent(); - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.BackgroundFPS, isChecked: profile.ReduceFPSWhenInactive, valueChanged: (b) => { profile.ReduceFPSWhenInactive = b; }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.FullsizeViewport, isChecked: profile.GameWindowFullSize, valueChanged: (b) => - { - profile.GameWindowFullSize = b; - if (b) - { - UIManager.GetGump()?.ResizeGameWindow(new Point(Client.Game.Window.ClientBounds.Width, Client.Game.Window.ClientBounds.Height)); - UIManager.GetGump()?.SetGameWindowPosition(new Point(-5, -5)); - profile.GameWindowPosition = new Point(-5, -5); - } - else - { - UIManager.GetGump()?.ResizeGameWindow(new Point(600, 480)); - UIManager.GetGump()?.SetGameWindowPosition(new Point(25, 25)); - profile.GameWindowPosition = new Point(25, 25); - } - }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.FullScreen, isChecked: profile.WindowBorderless, valueChanged: (b) => { profile.WindowBorderless = b; Client.Game.SetWindowBorderless(b); }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.LockViewport, isChecked: profile.GameWindowLock, valueChanged: (b) => { profile.GameWindowLock = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new SliderWithLabel(lang.GetVideo.ViewportX, 0, Theme.SLIDER_WIDTH, 0, Client.Game.Window.ClientBounds.Width, profile.GameWindowPosition.X, (r) => { profile.GameWindowPosition = new Point(r, profile.GameWindowPosition.Y); UIManager.GetGump()?.SetGameWindowPosition(profile.GameWindowPosition); }), true, page); - content.AddToRight(new SliderWithLabel(lang.GetVideo.ViewportY, 0, Theme.SLIDER_WIDTH, 0, Client.Game.Window.ClientBounds.Height, profile.GameWindowPosition.Y, (r) => { profile.GameWindowPosition = new Point(profile.GameWindowPosition.X, r); UIManager.GetGump()?.SetGameWindowPosition(profile.GameWindowPosition); }), true, page); - - content.BlankLine(); - - content.AddToRight(new SliderWithLabel(lang.GetVideo.ViewportW, 0, Theme.SLIDER_WIDTH, 0, Client.Game.Window.ClientBounds.Width, profile.GameWindowSize.X, (r) => { profile.GameWindowSize = new Point(r, profile.GameWindowSize.Y); UIManager.GetGump()?.ResizeGameWindow(profile.GameWindowSize); }), true, page); - content.AddToRight(new SliderWithLabel(lang.GetVideo.ViewportH, 0, Theme.SLIDER_WIDTH, 0, Client.Game.Window.ClientBounds.Height, profile.GameWindowSize.Y, (r) => { profile.GameWindowSize = new Point(profile.GameWindowSize.X, r); UIManager.GetGump()?.ResizeGameWindow(profile.GameWindowSize); }), true, page); - - #endregion - - #region Zoom - page = ((int)PAGE.Video + 1001); - content.AddToLeft(SubCategoryButton(lang.ButtonZoom, page, content.LeftWidth)); - content.ResetRightSide(); - - var cameraZoomCount = (int)((Client.Game.Scene.Camera.ZoomMax - Client.Game.Scene.Camera.ZoomMin) / Client.Game.Scene.Camera.ZoomStep); - var cameraZoomIndex = cameraZoomCount - (int)((Client.Game.Scene.Camera.ZoomMax - Client.Game.Scene.Camera.Zoom) / Client.Game.Scene.Camera.ZoomStep); - content.AddToRight(new SliderWithLabel(lang.GetVideo.DefaultZoom, 0, Theme.SLIDER_WIDTH, 0, cameraZoomCount, cameraZoomIndex, (r) => { profile.DefaultScale = Client.Game.Scene.Camera.Zoom = (r * Client.Game.Scene.Camera.ZoomStep) + Client.Game.Scene.Camera.ZoomMin; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.ZoomWheel, isChecked: profile.EnableMousewheelScaleZoom, valueChanged: (b) => { profile.EnableMousewheelScaleZoom = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.ReturnDefaultZoom, isChecked: profile.RestoreScaleAfterUnpressCtrl, valueChanged: (b) => { profile.RestoreScaleAfterUnpressCtrl = b; }), true, page); - #endregion - - #region Lighting - page = ((int)PAGE.Video + 1002); - content.AddToLeft(SubCategoryButton(lang.ButtonLighting, page, content.LeftWidth)); - content.ResetRightSide(); - - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.AltLights, isChecked: profile.UseAlternativeLights, valueChanged: (b) => { profile.UseAlternativeLights = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.CustomLLevel, isChecked: profile.UseCustomLightLevel, valueChanged: (b) => - { - profile.UseCustomLightLevel = b; - if (b) - { - World.Light.Overall = profile.LightLevelType == 1 ? Math.Min(World.Light.RealOverall, profile.LightLevel) : profile.LightLevel; - World.Light.Personal = 0; - } - else - { - World.Light.Overall = World.Light.RealOverall; - World.Light.Personal = World.Light.RealPersonal; - } - }), true, page); - content.Indent(); - content.AddToRight(new SliderWithLabel(lang.GetVideo.Level, 0, Theme.SLIDER_WIDTH, 0, 0x1E, 0x1E - profile.LightLevel, (r) => - { - profile.LightLevel = (byte)(0x1E - r); - if (profile.UseCustomLightLevel) - { - World.Light.Overall = profile.LightLevelType == 1 ? Math.Min(World.Light.RealOverall, profile.LightLevel) : profile.LightLevel; - World.Light.Personal = 0; - } - else - { - World.Light.Overall = World.Light.RealOverall; - World.Light.Personal = World.Light.RealPersonal; - } - }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new ComboBoxWithLabel(lang.GetVideo.LightType, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetVideo.LightType_Absolute, lang.GetVideo.LightType_Minimum }, profile.LightLevelType, (s, n) => { profile.LightLevelType = s; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.DarkNight, isChecked: profile.UseDarkNights, valueChanged: (b) => { profile.UseDarkNights = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.ColoredLight, isChecked: profile.UseColoredLights, valueChanged: (b) => { profile.UseColoredLights = b; }), true, page); - - #endregion - - #region Misc - page = ((int)PAGE.Video + 1003); - content.AddToLeft(SubCategoryButton(lang.ButtonMisc, page, content.LeftWidth)); - content.ResetRightSide(); - - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.EnableDeathScreen, isChecked: profile.EnableDeathScreen, valueChanged: (b) => { profile.EnableDeathScreen = b; }), true, page); - content.Indent(); - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.BWDead, isChecked: profile.EnableBlackWhiteEffect, valueChanged: (b) => { profile.EnableBlackWhiteEffect = b; }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.MouseThread, isChecked: Settings.GlobalSettings.RunMouseInASeparateThread, valueChanged: (b) => { Settings.GlobalSettings.RunMouseInASeparateThread = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.TargetAura, isChecked: profile.AuraOnMouse, valueChanged: (b) => { profile.AuraOnMouse = b; }), true, page); - - content.BlankLine(); - - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.AnimWater, isChecked: profile.AnimatedWaterEffect, valueChanged: (b) => { profile.AnimatedWaterEffect = b; }), true, page); - #endregion - - #region Shadows - page = ((int)PAGE.Video + 1004); - content.AddToLeft(SubCategoryButton(lang.ButtonShadows, page, content.LeftWidth)); - content.ResetRightSide(); - - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.EnableShadows, isChecked: profile.ShadowsEnabled, valueChanged: (b) => { profile.ShadowsEnabled = b; }), true, page); - content.Indent(); - content.AddToRight(new CheckboxWithLabel(lang.GetVideo.RockTreeShadows, isChecked: profile.ShadowsStatics, valueChanged: (b) => { profile.ShadowsStatics = b; }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new SliderWithLabel(lang.GetVideo.TerrainShadowLevel, 0, Theme.SLIDER_WIDTH, Constants.MIN_TERRAIN_SHADOWS_LEVEL, Constants.MAX_TERRAIN_SHADOWS_LEVEL, profile.TerrainShadowsLevel, (r) => { profile.TerrainShadowsLevel = r; }), true, page); - #endregion - - options.Add(new SettingsOption( - "", - content, - mainContent.RightWidth, - PAGE.Video - )); - } - - private void BuildMacros() - { - LeftSideMenuRightSideContent content = new LeftSideMenuRightSideContent(mainContent.RightWidth, mainContent.Height, (int)(mainContent.RightWidth * 0.3)); - int page = ((int)PAGE.Macros + 1000); - - #region New Macro - ModernButton b; - content.AddToLeft(b = new ModernButton(0, 0, content.LeftWidth, 40, ButtonAction.Activate, lang.GetMacros.NewMacro, Theme.BUTTON_FONT_COLOR) { ButtonParameter = page, IsSelectable = false }); - - b.MouseUp += (sender, e) => - { - EntryDialog dialog = new EntryDialog - ( - 250, - 150, - ResGumps.MacroName, - name => - { - if (string.IsNullOrWhiteSpace(name)) - { - return; - } - - MacroManager manager = Client.Game.GetScene().Macros; - - if (manager.FindMacro(name) != null) - { - return; - } - - ModernButton nb; - - MacroControl macroControl = new MacroControl(name); - - content.AddToLeft(nb = new ModernButton(0, 0, content.LeftWidth, 40, ButtonAction.SwitchPage, name, Theme.BUTTON_FONT_COLOR) { ButtonParameter = page + 1 + content.LeftArea.Children.Count, Tag = macroControl.Macro }); - content.ResetRightSide(); - content.AddToRight(macroControl, true, nb.ButtonParameter); - - nb.IsSelected = true; - content.ActivePage = nb.ButtonParameter; - - manager.PushToBack(macroControl.Macro); - - nb.DragBegin += (sss, eee) => - { - ModernButton mupNiceButton = (ModernButton)sss; - - Macro m = mupNiceButton.Tag as Macro; - - if (m == null) - { - return; - } - - if (UIManager.DraggingControl != this || UIManager.MouseOverControl != sss) - { - return; - } - - UIManager.Gumps.OfType().FirstOrDefault(s => s.TheMacro == m)?.Dispose(); - - MacroButtonGump macroButtonGump = new MacroButtonGump(m, Mouse.Position.X, Mouse.Position.Y); - - macroButtonGump.X = Mouse.Position.X - (macroButtonGump.Width >> 1); - macroButtonGump.Y = Mouse.Position.Y - (macroButtonGump.Height >> 1); - - UIManager.Add(macroButtonGump); - - UIManager.AttemptDragControl(macroButtonGump, true); - }; - } - ) - { - CanCloseWithRightClick = true - }; - - UIManager.Add(dialog); - }; - #endregion - - #region Delete Macro - page = ((int)PAGE.Macros + 1001); - content.AddToLeft(b = new ModernButton(0, 0, content.LeftWidth, 40, ButtonAction.Activate, lang.GetMacros.DelMacro, Theme.BUTTON_FONT_COLOR) { ButtonParameter = page, IsSelectable = false }); - - b.MouseUp += (ss, ee) => - { - ModernButton nb = content.LeftArea.FindControls().SingleOrDefault(a => a.IsSelected); - - if (nb != null) - { - QuestionGump dialog = new QuestionGump - ( - ResGumps.MacroDeleteConfirmation, - b => - { - if (!b) - { - return; - } - - if (nb.Tag is Macro macro) - { - UIManager.Gumps.OfType().FirstOrDefault(s => s.TheMacro == macro)?.Dispose(); - Client.Game.GetScene().Macros.Remove(macro); - nb.Dispose(); - } - } - ); - - UIManager.Add(dialog); - } - }; - #endregion - - content.AddToLeft(new Line(0, 0, content.LeftWidth, 1, Color.Gray.PackedValue)); - - #region Macros - page = ((int)PAGE.Macros + 1002); - MacroManager macroManager = Client.Game.GetScene().Macros; - for (Macro macro = (Macro)macroManager.Items; macro != null; macro = (Macro)macro.Next) - { - content.AddToLeft(b = new ModernButton(0, 0, content.LeftWidth, 40, ButtonAction.SwitchPage, macro.Name, Theme.BUTTON_FONT_COLOR) { ButtonParameter = page + 1 + content.LeftArea.Children.Count, Tag = macro }); - - b.DragBegin += (sss, eee) => - { - ModernButton mupNiceButton = (ModernButton)sss; - - Macro m = mupNiceButton.Tag as Macro; - - if (m == null) - { - return; - } - - if (UIManager.DraggingControl != this || UIManager.MouseOverControl != sss) - { - return; - } - - UIManager.Gumps.OfType().FirstOrDefault(s => s.TheMacro == m)?.Dispose(); - - MacroButtonGump macroButtonGump = new MacroButtonGump(m, Mouse.Position.X, Mouse.Position.Y); - - macroButtonGump.X = Mouse.Position.X - (macroButtonGump.Width >> 1); - macroButtonGump.Y = Mouse.Position.Y - (macroButtonGump.Height >> 1); - - UIManager.Add(macroButtonGump); - - UIManager.AttemptDragControl(macroButtonGump, true); - }; - - content.ResetRightSide(); - content.AddToRight(new MacroControl(macro.Name), true, b.ButtonParameter); - } - - b.IsSelected = true; - content.ActivePage = b.ButtonParameter; - #endregion - - options.Add(new SettingsOption( - "", - content, - mainContent.RightWidth, - PAGE.Macros - )); - } - - private void BuildTooltips() - { - SettingsOption s; - PositionHelper.Reset(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetToolTips.EnableToolTips, 0, profile.UseTooltip, (b) => { profile.UseTooltip = b; }), - mainContent.RightWidth, - PAGE.Tooltip - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.Indent(); - - options.Add(s = new SettingsOption( - "", - new SliderWithLabel(lang.GetToolTips.ToolTipDelay, 0, Theme.SLIDER_WIDTH, 0, 1000, profile.TooltipDelayBeforeDisplay, (i) => { profile.TooltipDelayBeforeDisplay = i; }), - mainContent.RightWidth, - PAGE.Tooltip - )); - PositionHelper.PositionControl(s.FullControl); - - options.Add(s = new SettingsOption( - "", - new SliderWithLabel(lang.GetToolTips.ToolTipBG, 0, Theme.SLIDER_WIDTH, 0, 100, profile.TooltipBackgroundOpacity, (i) => { profile.TooltipBackgroundOpacity = i; }), - mainContent.RightWidth, - PAGE.Tooltip - )); - PositionHelper.PositionControl(s.FullControl); - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetToolTips.ToolTipFont, profile.TooltipTextHue, (h) => { profile.TooltipTextHue = h; }), - mainContent.RightWidth, - PAGE.Tooltip - )); - PositionHelper.PositionControl(s.FullControl); - } - - private void BuildSpeech() - { - SettingsOption s, ss; - PositionHelper.Reset(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetSpeech.ScaleSpeechDelay, 0, profile.ScaleSpeechDelay, (b) => { profile.ScaleSpeechDelay = b; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.Indent(); - - options.Add(s = new SettingsOption( - "", - new SliderWithLabel(lang.GetSpeech.SpeechDelay, 0, Theme.SLIDER_WIDTH, 0, 1000, profile.SpeechDelay, (i) => { profile.SpeechDelay = i; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.RemoveIndent(); - - - PositionHelper.BlankLine(); - - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetSpeech.SaveJournalE, 0, profile.SaveJournalToFile, (b) => { profile.SaveJournalToFile = b; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionControl(s.FullControl); - - - PositionHelper.BlankLine(); - - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetSpeech.ChatEnterActivation, 0, profile.ActivateChatAfterEnter, (b) => { profile.ActivateChatAfterEnter = b; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.Indent(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetSpeech.ChatEnterSpecial, 0, profile.ActivateChatAdditionalButtons, (b) => { profile.ActivateChatAdditionalButtons = b; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionControl(s.FullControl); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetSpeech.ShiftEnterChat, 0, profile.ActivateChatShiftEnterSupport, (b) => { profile.ActivateChatShiftEnterSupport = b; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.RemoveIndent(); - - - PositionHelper.BlankLine(); - - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetSpeech.ChatGradient, 0, profile.HideChatGradient, (b) => { profile.HideChatGradient = b; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionControl(s.FullControl); - - - PositionHelper.BlankLine(); - - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetSpeech.HideGuildChat, 0, profile.IgnoreGuildMessages, (b) => { profile.IgnoreGuildMessages = b; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionControl(s.FullControl); - - - PositionHelper.BlankLine(); - - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetSpeech.HideAllianceChat, 0, profile.IgnoreAllianceMessages, (b) => { profile.IgnoreAllianceMessages = b; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionControl(s.FullControl); - - - PositionHelper.BlankLine(); - - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetSpeech.SpeechColor, profile.SpeechHue, (h) => { profile.SpeechHue = h; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionControl(s.FullControl); - ss = s; - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetSpeech.YellColor, profile.YellHue, (h) => { profile.YellHue = h; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionExact(s.FullControl, 200, ss.FullControl.Y); - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetSpeech.PartyColor, profile.PartyMessageHue, (h) => { profile.PartyMessageHue = h; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionControl(s.FullControl); - ss = s; - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetSpeech.AllianceColor, profile.AllyMessageHue, (h) => { profile.AllyMessageHue = h; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionExact(s.FullControl, 200, ss.FullControl.Y); - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetSpeech.EmoteColor, profile.EmoteHue, (h) => { profile.EmoteHue = h; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionControl(s.FullControl); - ss = s; - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetSpeech.WhisperColor, profile.WhisperHue, (h) => { profile.WhisperHue = h; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionExact(s.FullControl, 200, ss.FullControl.Y); - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetSpeech.GuildColor, profile.GuildMessageHue, (h) => { profile.GuildMessageHue = h; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionControl(s.FullControl); - ss = s; - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetSpeech.CharColor, profile.ChatMessageHue, (h) => { profile.ChatMessageHue = h; }), - mainContent.RightWidth, - PAGE.Speech - )); - PositionHelper.PositionExact(s.FullControl, 200, ss.FullControl.Y); - } - - private void BuildCombatSpells() - { - SettingsOption s; - PositionHelper.Reset(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetCombatSpells.HoldTabForCombat, 0, profile.HoldDownKeyTab, (b) => { profile.HoldDownKeyTab = b; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionControl(s.FullControl); - - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetCombatSpells.QueryBeforeAttack, 0, profile.EnabledCriminalActionQuery, (b) => { profile.EnabledCriminalActionQuery = b; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionControl(s.FullControl); - - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetCombatSpells.QueryBeforeBeneficial, 0, profile.EnabledBeneficialCriminalActionQuery, (b) => { profile.EnabledBeneficialCriminalActionQuery = b; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionControl(s.FullControl); - - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetCombatSpells.EnableOverheadSpellFormat, 0, profile.EnabledSpellFormat, (b) => { profile.EnabledSpellFormat = b; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionControl(s.FullControl); - - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetCombatSpells.EnableOverheadSpellHue, 0, profile.EnabledSpellHue, (b) => { profile.EnabledSpellHue = b; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionControl(s.FullControl); - - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetCombatSpells.SingleClickForSpellIcons, 0, profile.CastSpellsByOneClick, (b) => { profile.CastSpellsByOneClick = b; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionControl(s.FullControl); - - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetCombatSpells.ShowBuffDurationOnOldStyleBuffBar, 0, profile.BuffBarTime, (b) => { profile.BuffBarTime = b; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionControl(s.FullControl); - - PositionHelper.BlankLine(); - - Control c; - options.Add(s = new SettingsOption( - "", - c = new CheckboxWithLabel(lang.GetCombatSpells.EnableFastSpellHotkeyAssigning, 0, profile.FastSpellsAssign, (b) => { profile.FastSpellsAssign = b; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionControl(s.FullControl); - c.SetTooltip(lang.GetCombatSpells.TooltipFastSpellAssign); - - PositionHelper.BlankLine(); - - SettingsOption ss; - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetCombatSpells.InnocentColor, profile.InnocentHue, (h) => { profile.InnocentHue = h; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionControl(s.FullControl); - ss = s; - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetCombatSpells.BeneficialSpell, profile.BeneficHue, (h) => { profile.BeneficHue = h; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionExact(s.FullControl, 200, ss.FullControl.Y); - ss = s; - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetCombatSpells.FriendColor, profile.FriendHue, (h) => { profile.FriendHue = h; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionControl(s.FullControl); - ss = s; - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetCombatSpells.HarmfulSpell, profile.HarmfulHue, (h) => { profile.HarmfulHue = h; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionExact(s.FullControl, 200, ss.FullControl.Y); - ss = s; - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetCombatSpells.Criminal, profile.CriminalHue, (h) => { profile.CriminalHue = h; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionControl(s.FullControl); - ss = s; - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetCombatSpells.NeutralSpell, profile.NeutralHue, (h) => { profile.NeutralHue = h; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionExact(s.FullControl, 200, ss.FullControl.Y); - ss = s; - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetCombatSpells.CanBeAttackedHue, profile.CanAttackHue, (h) => { profile.CanAttackHue = h; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionControl(s.FullControl); - ss = s; - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetCombatSpells.Murderer, profile.MurdererHue, (h) => { profile.MurdererHue = h; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionExact(s.FullControl, 200, ss.FullControl.Y); - ss = s; - - options.Add(s = new SettingsOption( - "", - new ModernColorPickerWithLabel(lang.GetCombatSpells.Enemy, profile.EnemyHue, (h) => { profile.EnemyHue = h; }), - mainContent.RightWidth, - PAGE.CombatSpells - )); - PositionHelper.PositionControl(s.FullControl); - - PositionHelper.BlankLine(); - - InputField spellFormat; - options.Add(s = new SettingsOption( - lang.GetCombatSpells.SpellOverheadFormat, - spellFormat = new InputField(200, 40), - mainContent.RightWidth, - PAGE.CombatSpells - )); - spellFormat.SetText(profile.SpellDisplayFormat); - spellFormat.TextChanged += (s, e) => - { - profile.SpellDisplayFormat = spellFormat.Text; - }; - PositionHelper.PositionControl(s.FullControl); - s.FullControl.SetTooltip(lang.GetCombatSpells.TooltipSpellFormat); - } - - private void BuildCounters() - { - SettingsOption s; - PositionHelper.Reset(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetCounters.EnableCounters, 0, profile.CounterBarEnabled, (b) => - { - profile.CounterBarEnabled = b; - CounterBarGump counterGump = UIManager.GetGump(); - - if (b) - { - if (counterGump != null) - { - counterGump.IsEnabled = counterGump.IsVisible = b; - } - else - { - UIManager.Add(counterGump = new CounterBarGump(200, 200)); - } - } - else - { - if (counterGump != null) - { - counterGump.IsEnabled = counterGump.IsVisible = b; - } - } - - counterGump?.SetLayout(profile.CounterBarCellSize, profile.CounterBarRows, profile.CounterBarColumns); - }), - mainContent.RightWidth, - PAGE.Counters - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.Indent(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetCounters.HighlightItemsOnUse, 0, profile.CounterBarHighlightOnUse, (b) => { profile.CounterBarHighlightOnUse = b; }), - mainContent.RightWidth, - PAGE.Counters - )); - PositionHelper.PositionControl(s.FullControl); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetCounters.AbbreviatedValues, 0, profile.CounterBarDisplayAbbreviatedAmount, (b) => { profile.CounterBarDisplayAbbreviatedAmount = b; }), - mainContent.RightWidth, - PAGE.Counters - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.Indent(); - - options.Add(s = new SettingsOption( - lang.GetCounters.AbbreviateIfAmountExceeds, - new InputField(100, 40, text: profile.CounterBarAbbreviatedAmount.ToString(), numbersOnly: true, onTextChanges: (s, e) => - { - if (int.TryParse(((InputField.StbTextBox)s).Text, out int v)) - { - profile.CounterBarAbbreviatedAmount = v; - } - }), - mainContent.RightWidth, - PAGE.Counters - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.RemoveIndent(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetCounters.HighlightRedWhenAmountIsLow, 0, profile.CounterBarHighlightOnAmount, (b) => { profile.CounterBarHighlightOnAmount = b; }), - mainContent.RightWidth, - PAGE.Counters - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.Indent(); - - options.Add(s = new SettingsOption( - lang.GetCounters.HighlightRedIfAmountIsBelow, - new InputField(100, 40, text: profile.CounterBarHighlightAmount.ToString(), numbersOnly: true, onTextChanges: (s, e) => - { - if (int.TryParse(((InputField.StbTextBox)s).Text, out int v)) - { - profile.CounterBarHighlightAmount = v; - } - }), - mainContent.RightWidth, - PAGE.Counters - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.RemoveIndent(); - PositionHelper.RemoveIndent(); - - PositionHelper.BlankLine(); - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption( - lang.GetCounters.CounterLayout, - new Area(false), - mainContent.RightWidth, - PAGE.Counters - )); - PositionHelper.PositionControl(s.FullControl); - - PositionHelper.Indent(); - - options.Add(s = new SettingsOption( - "", - new SliderWithLabel(lang.GetCounters.GridSize, 0, Theme.SLIDER_WIDTH, 30, 100, profile.CounterBarCellSize, (v) => - { - profile.CounterBarCellSize = v; - UIManager.GetGump()?.SetLayout(profile.CounterBarCellSize, profile.CounterBarRows, profile.CounterBarColumns); - }), - mainContent.RightWidth, - PAGE.Counters - )); - PositionHelper.PositionControl(s.FullControl); - - options.Add(s = new SettingsOption( - lang.GetCounters.Rows, - new InputField(100, 40, text: profile.CounterBarRows.ToString(), numbersOnly: true, onTextChanges: (s, e) => - { - if (int.TryParse(((InputField.StbTextBox)s).Text, out int v)) - { - profile.CounterBarRows = v; - UIManager.GetGump()?.SetLayout(profile.CounterBarCellSize, profile.CounterBarRows, profile.CounterBarColumns); - } - }), - mainContent.RightWidth, - PAGE.Counters - )); - PositionHelper.PositionControl(s.FullControl); - SettingsOption ss = s; - - options.Add(s = new SettingsOption( - lang.GetCounters.Columns, - new InputField(100, 40, text: profile.CounterBarColumns.ToString(), numbersOnly: true, onTextChanges: (s, e) => - { - if (int.TryParse(((InputField.StbTextBox)s).Text, out int v)) - { - profile.CounterBarColumns = v; - UIManager.GetGump()?.SetLayout(profile.CounterBarCellSize, profile.CounterBarRows, profile.CounterBarColumns); - } - }), - mainContent.RightWidth, - PAGE.Counters - )); - PositionHelper.PositionExact(s.FullControl, ss.FullControl.X + ss.FullControl.Width + 30, ss.FullControl.Y); - } - - private void BuildInfoBar() - { - SettingsOption s; - PositionHelper.Reset(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetInfoBars.ShowInfoBar, 0, profile.ShowInfoBar, (b) => - { - profile.ShowInfoBar = b; - InfoBarGump infoBarGump = UIManager.GetGump(); - - if (b) - { - if (infoBarGump == null) - { - UIManager.Add(new InfoBarGump { X = 300, Y = 300 }); - } - else - { - infoBarGump.ResetItems(); - infoBarGump.SetInScreen(); - } - } - else - { - infoBarGump?.Dispose(); - } - }), - mainContent.RightWidth, - PAGE.InfoBar - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.Indent(); - - options.Add(s = new SettingsOption( - "", - new ComboBoxWithLabel(lang.GetInfoBars.HighlightType, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetInfoBars.HighLightOpt_TextColor, lang.GetInfoBars.HighLightOpt_ColoredBars }, profile.InfoBarHighlightType, (i, s) => { profile.InfoBarHighlightType = i; }), - mainContent.RightWidth, - PAGE.InfoBar - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.RemoveIndent(); - - PositionHelper.BlankLine(); - - DataBox infoBarItems = new DataBox(0, 0, 0, 0) { AcceptMouseInput = true }; - - ModernButton addItem; - options.Add(s = new SettingsOption( - "", - addItem = new ModernButton(0, 0, 150, 40, ButtonAction.Activate, lang.GetInfoBars.AddItem, Theme.BUTTON_FONT_COLOR) { ButtonParameter = -1, IsSelectable = true, IsSelected = true }, - mainContent.RightWidth, - PAGE.InfoBar - )); - addItem.MouseUp += (s, e) => - { - InfoBarItem ibi; - InfoBarBuilderControl ibbc = new InfoBarBuilderControl(ibi = new InfoBarItem("HP", InfoBarVars.HP, 0x3B9)); - infoBarItems.Add(ibbc); - infoBarItems.ReArrangeChildren(); - infoBarItems.ForceSizeUpdate(); - infoBarItems.Parent?.ForceSizeUpdate(); - Client.Game.GetScene().InfoBars?.AddItem(ibi); - UIManager.GetGump()?.ResetItems(); - }; - PositionHelper.PositionControl(s.FullControl); - SettingsOption ss = s; - PositionHelper.BlankLine(); - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption(lang.GetInfoBars.Label, new Area(false), mainContent.RightWidth, PAGE.InfoBar)); - PositionHelper.PositionExact(s.FullControl, ss.FullControl.X, ss.FullControl.Y + ss.FullControl.Height + 40); - ss = s; - - options.Add(s = new SettingsOption(lang.GetInfoBars.Color, new Area(false), mainContent.RightWidth, PAGE.InfoBar)); - PositionHelper.PositionExact(s.FullControl, ss.FullControl.X + 150, ss.FullControl.Y); - ss = s; - - options.Add(s = new SettingsOption(lang.GetInfoBars.Data, new Area(false), mainContent.RightWidth, PAGE.InfoBar)); - PositionHelper.PositionExact(s.FullControl, ss.FullControl.X + 55, ss.FullControl.Y); - ss = s; - - options.Add(s = new SettingsOption( - "", - new Line(0, 0, mainContent.RightWidth, 1, Color.Gray.PackedValue) { AcceptMouseInput = false }, - mainContent.RightWidth, - PAGE.InfoBar - )); - PositionHelper.PositionExact(s.FullControl, ss.FullControl.X - 205, ss.FullControl.Y + ss.FullControl.Height + 2); - PositionHelper.BlankLine(); - - - InfoBarManager ibmanager = Client.Game.GetScene().InfoBars; - List _infoBarItems = ibmanager.GetInfoBars(); - - for (int i = 0; i < _infoBarItems.Count; i++) - { - InfoBarBuilderControl ibbc = new InfoBarBuilderControl(_infoBarItems[i]); - infoBarItems.Add(ibbc); - } - infoBarItems.ReArrangeChildren(); - infoBarItems.ForceSizeUpdate(); - - options.Add(s = new SettingsOption( - "", - infoBarItems, - mainContent.RightWidth, - PAGE.InfoBar - )); - PositionHelper.PositionControl(s.FullControl); - } - - private void BuildContainers() - { - SettingsOption s; - PositionHelper.Reset(); - - options.Add(s = new SettingsOption( - lang.GetContainers.Description, - new Area(false), - mainContent.RightWidth, - PAGE.Containers - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.BlankLine(); - PositionHelper.BlankLine(); - PositionHelper.BlankLine(); - - if (Client.Version >= ClientVersion.CV_705301) - { - options.Add(s = new SettingsOption( - "", - new ComboBoxWithLabel(lang.GetContainers.CharacterBackpackStyle, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetContainers.BackpackOpt_Default, lang.GetContainers.BackpackOpt_Suede, lang.GetContainers.BackpackOpt_PolarBear, lang.GetContainers.BackpackOpt_GhoulSkin }, profile.BackpackStyle, (i, s) => { profile.BackpackStyle = i; }), - mainContent.RightWidth, - PAGE.Containers - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.BlankLine(); - } - - options.Add(s = new SettingsOption( - "", - new SliderWithLabel(lang.GetContainers.ContainerScale, 0, Theme.SLIDER_WIDTH, Constants.MIN_CONTAINER_SIZE_PERC, Constants.MAX_CONTAINER_SIZE_PERC, profile.ContainersScale, (i) => - { - profile.ContainersScale = (byte)i; - UIManager.ContainerScale = (byte)i / 100f; - foreach (ContainerGump resizableGump in UIManager.Gumps.OfType()) - { - resizableGump.RequestUpdateContents(); - } - }), - mainContent.RightWidth, - PAGE.Containers - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.Indent(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetContainers.AlsoScaleItems, 0, profile.ScaleItemsInsideContainers, (b) => { profile.ScaleItemsInsideContainers = b; }), - mainContent.RightWidth, - PAGE.Containers - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.RemoveIndent(); - PositionHelper.BlankLine(); - - if (Client.Version >= ClientVersion.CV_706000) - { - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetContainers.UseLargeContainerGumps, 0, profile.UseLargeContainerGumps, (b) => { profile.UseLargeContainerGumps = b; }), - mainContent.RightWidth, - PAGE.Containers - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.BlankLine(); - } - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetContainers.DoubleClickToLootItemsInsideContainers, 0, profile.DoubleClickToLootInsideContainers, (b) => { profile.DoubleClickToLootInsideContainers = b; }), - mainContent.RightWidth, - PAGE.Containers - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetContainers.RelativeDragAndDropItemsInContainers, 0, profile.RelativeDragAndDropItems, (b) => { profile.RelativeDragAndDropItems = b; }), - mainContent.RightWidth, - PAGE.Containers - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.BlankLine(); - - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetContainers.HighlightContainerOnGroundWhenMouseIsOverAContainerGump, 0, profile.HighlightContainerWhenSelected, (b) => { profile.HighlightContainerWhenSelected = b; }), - mainContent.RightWidth, - PAGE.Containers - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.BlankLine(); - - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetContainers.RecolorContainerGumpByWithContainerHue, 0, profile.HueContainerGumps, (b) => { profile.HueContainerGumps = b; }), - mainContent.RightWidth, - PAGE.Containers - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetContainers.OverrideContainerGumpLocations, 0, profile.OverrideContainerLocation, (b) => { profile.OverrideContainerLocation = b; }), - mainContent.RightWidth, - PAGE.Containers - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.Indent(); - - options.Add(s = new SettingsOption( - "", - new ComboBoxWithLabel(lang.GetContainers.OverridePosition, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetContainers.PositionOpt_NearContainer, lang.GetContainers.PositionOpt_TopRight, lang.GetContainers.PositionOpt_LastDraggedPosition, lang.GetContainers.RememberEachContainer }, profile.OverrideContainerLocationSetting, (i, s) => { profile.OverrideContainerLocationSetting = i; }), - mainContent.RightWidth, - PAGE.Containers - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.BlankLine(); - - ModernButton rebuildContainers; - options.Add(s = new SettingsOption( - "", - rebuildContainers = new ModernButton(0, 0, 130, 40, ButtonAction.Activate, lang.GetContainers.RebuildContainersTxt, Theme.BUTTON_FONT_COLOR, 999) { IsSelected = true, IsSelectable = true }, - mainContent.RightWidth, - PAGE.Containers - )); - rebuildContainers.MouseUp += (s, e) => - { - ContainerManager.BuildContainerFile(true); - }; - PositionHelper.PositionControl(s.FullControl); - } - - private void BuildExperimental() - { - SettingsOption s; - PositionHelper.Reset(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetExperimental.DisableDefaultUoHotkeys, 0, profile.DisableDefaultHotkeys, (b) => { profile.DisableDefaultHotkeys = b; }), - mainContent.RightWidth, - PAGE.Experimental - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetExperimental.DisableArrowsNumlockArrowsPlayerMovement, 0, profile.DisableArrowBtn, (b) => { profile.DisableArrowBtn = b; }), - mainContent.RightWidth, - PAGE.Experimental - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetExperimental.DisableTabToggleWarmode, 0, profile.DisableTabBtn, (b) => { profile.DisableTabBtn = b; }), - mainContent.RightWidth, - PAGE.Experimental - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetExperimental.DisableCtrlQWMessageHistory, 0, profile.DisableCtrlQWBtn, (b) => { profile.DisableCtrlQWBtn = b; }), - mainContent.RightWidth, - PAGE.Experimental - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption( - "", - new CheckboxWithLabel(lang.GetExperimental.DisableRightLeftClickAutoMove, 0, profile.DisableAutoMove, (b) => { profile.DisableAutoMove = b; }), - mainContent.RightWidth, - PAGE.Experimental - )); - PositionHelper.PositionControl(s.FullControl); - } - - private void BuildNameplates() - { - LeftSideMenuRightSideContent content = new LeftSideMenuRightSideContent(mainContent.RightWidth, mainContent.Height, (int)(mainContent.RightWidth * 0.3)); - int page = ((int)PAGE.NameplateOptions + 1000); - - #region New entry - ModernButton b; - content.AddToLeft(b = new ModernButton(0, 0, content.LeftWidth, 40, ButtonAction.Activate, lang.GetNamePlates.NewEntry, Theme.BUTTON_FONT_COLOR) { ButtonParameter = page, IsSelectable = false }); - - b.MouseUp += (sender, e) => - { - EntryDialog dialog = new - ( - 250, - 150, - lang.GetNamePlates.NameOverheadEntryName, - name => - { - if (string.IsNullOrWhiteSpace(name)) - { - return; - } - if (NameOverHeadManager.FindOption(name) != null) - { - return; - } - - NameOverheadOption option = new NameOverheadOption(name); - - ModernButton nb; - content.AddToLeft - ( - nb = new ModernButton - ( - 0, - 0, - content.LeftWidth, - 40, - ButtonAction.SwitchPage, - name, - Theme.BUTTON_FONT_COLOR - ) - { - ButtonParameter = page + 1 + content.LeftArea.Children.Count, - Tag = option - } - ); - nb.IsSelected = true; - content.ActivePage = nb.ButtonParameter; - NameOverHeadManager.AddOption(option); - - content.AddToRight(new NameOverheadAssignControl(option), false, nb.ButtonParameter); - } - ) - { - CanCloseWithRightClick = true - }; - UIManager.Add(dialog); - }; - #endregion - - #region Delete entry - page = ((int)PAGE.Macros + 1001); - content.AddToLeft(b = new ModernButton(0, 0, content.LeftWidth, 40, ButtonAction.Activate, lang.GetNamePlates.DeleteEntry, Theme.BUTTON_FONT_COLOR) { ButtonParameter = page, IsSelectable = false }); - - b.MouseUp += (ss, ee) => - { - ModernButton nb = content.LeftArea.FindControls().SingleOrDefault(a => a.IsSelected); - - if (nb != null) - { - QuestionGump dialog = new QuestionGump - ( - ResGumps.MacroDeleteConfirmation, - b => - { - if (!b) - { - return; - } - - if (nb.Tag is NameOverheadOption option) - { - NameOverHeadManager.RemoveOption(option); - nb.Dispose(); - } - } - ); - - UIManager.Add(dialog); - } - }; - #endregion - - content.AddToLeft(new Line(0, 0, content.LeftWidth, 1, Color.Gray.PackedValue)); - - var opts = NameOverHeadManager.GetAllOptions(); - ModernButton nb = null; - - for (int i = 0; i < opts.Count; i++) - { - var option = opts[i]; - if (option == null) - { - continue; - } - - content.AddToLeft - ( - nb = new ModernButton - ( - 0, - 0, - content.LeftWidth, - 40, - ButtonAction.SwitchPage, - option.Name, - Theme.BUTTON_FONT_COLOR - ) - { - ButtonParameter = page + 1 + content.LeftArea.Children.Count, - Tag = option - } - ); - - content.AddToRight(new NameOverheadAssignControl(option), false, nb.ButtonParameter); - } - - if (nb != null) - { - nb.IsSelected = true; - content.ActivePage = nb.ButtonParameter; - } - - options.Add(new SettingsOption( - "", - content, - mainContent.RightWidth, - PAGE.NameplateOptions - )); - } - - private void BuildCooldowns() - { - SettingsOption s; - PositionHelper.Reset(); - - options.Add(s = new SettingsOption( - lang.GetCooldowns.CustomCooldownBars, - new Area(false), - mainContent.RightWidth, - PAGE.TUOCooldowns - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.Indent(); - - options.Add(s = new SettingsOption( - lang.GetCooldowns.PositionX, - new InputField(100, 40, text: profile.CoolDownX.ToString(), numbersOnly: true, onTextChanges: (s, e) => - { - if (int.TryParse(((InputField.StbTextBox)s).Text, out int v)) - { - profile.CoolDownX = v; - } - }), - mainContent.RightWidth, - PAGE.TUOCooldowns - )); - PositionHelper.PositionControl(s.FullControl); - - options.Add(s = new SettingsOption( - lang.GetCooldowns.PositionY, - new InputField(100, 40, text: profile.CoolDownY.ToString(), numbersOnly: true, onTextChanges: (s, e) => - { - if (int.TryParse(((InputField.StbTextBox)s).Text, out int v)) - { - profile.CoolDownY = v; - } - }), - mainContent.RightWidth, - PAGE.TUOCooldowns - )); - PositionHelper.PositionControl(s.FullControl); - - options.Add(s = new SettingsOption( - string.Empty, - new CheckboxWithLabel(lang.GetCooldowns.UseLastMovedBarPosition, 0, profile.UseLastMovedCooldownPosition, (b) => { profile.UseLastMovedCooldownPosition = b; }), - mainContent.RightWidth, - PAGE.TUOCooldowns - )); - PositionHelper.PositionControl(s.FullControl); - PositionHelper.RemoveIndent(); - - PositionHelper.BlankLine(); - PositionHelper.BlankLine(); - - options.Add(s = new SettingsOption( - lang.GetCooldowns.Conditions, - new Area(false), - mainContent.RightWidth, - PAGE.TUOCooldowns - )); - PositionHelper.PositionControl(s.FullControl); - - DataBox conditionsDataBox = new DataBox(0, 0, 0, 0) { WantUpdateSize = true }; - - ModernButton addcond; - options.Add(s = new SettingsOption( - "", - addcond = new ModernButton(0, 0, 175, 40, ButtonAction.Activate, lang.GetCooldowns.AddCondition, Theme.BUTTON_FONT_COLOR), - mainContent.RightWidth, - PAGE.TUOCooldowns - )); - addcond.MouseUp += (s, e) => - { - CoolDownBar.CoolDownConditionData.GetConditionData(profile.CoolDownConditionCount, true); - - Gump g = UIManager.GetGump(); - if (g != null) - { - Point pos = g.Location; - g.Dispose(); - g = new ModernOptionsGump() { Location = pos }; - g.ChangePage((int)PAGE.TUOCooldowns); - UIManager.Add(g); - } - }; - PositionHelper.PositionControl(s.FullControl); - - int count = profile.CoolDownConditionCount; - for (int i = 0; i < count; i++) - { - conditionsDataBox.Add(GenConditionControl(i, mainContent.RightWidth - 19, false)); - } - conditionsDataBox.ReArrangeChildren(); - conditionsDataBox.ForceSizeUpdate(); - - options.Add(s = new SettingsOption( - "", - conditionsDataBox, - mainContent.RightWidth, - PAGE.TUOCooldowns - )); - PositionHelper.PositionControl(s.FullControl); - } - - private void BuildTazUO() - { - LeftSideMenuRightSideContent content = new LeftSideMenuRightSideContent(mainContent.RightWidth, mainContent.Height, (int)(mainContent.RightWidth * 0.3)); - Control c; - int page; - - #region General - page = ((int)PAGE.TUOOptions + 1000); - content.AddToLeft(SubCategoryButton(lang.GetTazUO.GridContainers, page, content.LeftWidth)); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.EnableGridContainers, 0, profile.UseGridLayoutContainerGumps, (b) => - { - profile.UseGridLayoutContainerGumps = b; - }), true, page); - - content.BlankLine(); - - content.AddToRight(new SliderWithLabel(lang.GetTazUO.GridContainerScale, 0, Theme.SLIDER_WIDTH, 50, 200, profile.GridContainersScale, (i) => - { - profile.GridContainersScale = (byte)i; - }), true, page); - content.Indent(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.AlsoScaleItems, 0, profile.GridContainerScaleItems, (b) => - { - profile.GridContainerScaleItems = b; - }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new SliderWithLabel(lang.GetTazUO.GridItemBorderOpacity, 0, Theme.SLIDER_WIDTH, 0, 100, profile.GridBorderAlpha, (i) => - { - profile.GridBorderAlpha = (byte)i; - }), true, page); - content.Indent(); - content.AddToRight(new ModernColorPickerWithLabel(lang.GetTazUO.BorderColor, profile.GridBorderHue, (h) => - { - profile.GridBorderHue = h; - }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new SliderWithLabel(lang.GetTazUO.ContainerOpacity, 0, Theme.SLIDER_WIDTH, 0, 100, profile.ContainerOpacity, (i) => - { - profile.ContainerOpacity = (byte)i; - GridContainer.UpdateAllGridContainers(); - }), true, page); - content.Indent(); - content.AddToRight(new ModernColorPickerWithLabel(lang.GetTazUO.BackgroundColor, profile.AltGridContainerBackgroundHue, (h) => - { - profile.AltGridContainerBackgroundHue = h; - GridContainer.UpdateAllGridContainers(); - }), true, page); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.UseContainersHue, 0, profile.Grid_UseContainerHue, (b) => - { - profile.Grid_UseContainerHue = b; - GridContainer.UpdateAllGridContainers(); - }), true, page); - content.RemoveIndent(); - - content.BlankLine(); - - content.AddToRight(new ComboBoxWithLabel(lang.GetTazUO.SearchStyle, 0, Theme.COMBO_BOX_WIDTH, new string[] { lang.GetTazUO.OnlyShow, lang.GetTazUO.Highlight }, profile.GridContainerSearchMode, (i, s) => - { - profile.GridContainerSearchMode = i; - }), true, page); - content.BlankLine(); - content.AddToRight(c = new CheckboxWithLabel(lang.GetTazUO.EnableContainerPreview, 0, profile.GridEnableContPreview, (b) => - { - profile.GridEnableContPreview = b; - }), true, page); - c.SetTooltip(lang.GetTazUO.TooltipPreview); - - content.BlankLine(); - - content.AddToRight(c = new CheckboxWithLabel(lang.GetTazUO.MakeAnchorable, 0, profile.EnableGridContainerAnchor, (b) => - { - profile.EnableGridContainerAnchor = b; - GridContainer.UpdateAllGridContainers(); - }), true, page); - c.SetTooltip(lang.GetTazUO.TooltipGridAnchor); - - content.BlankLine(); - - content.AddToRight(new ComboBoxWithLabel(lang.GetTazUO.ContainerStyle, 0, Theme.COMBO_BOX_WIDTH, Enum.GetNames(typeof(GridContainer.BorderStyle)), profile.Grid_BorderStyle, (i, s) => - { - profile.Grid_BorderStyle = i; - GridContainer.UpdateAllGridContainers(); - }), true, page); - - content.BlankLine(); - - content.AddToRight(c = new CheckboxWithLabel(lang.GetTazUO.HideBorders, 0, profile.Grid_HideBorder, (b) => - { - profile.Grid_HideBorder = b; - GridContainer.UpdateAllGridContainers(); - }), true, page); - - content.BlankLine(); - - content.AddToRight(new SliderWithLabel(lang.GetTazUO.DefaultGridRows, 0, Theme.SLIDER_WIDTH, 1, 20, profile.Grid_DefaultRows, (i) => - { - profile.Grid_DefaultRows = i; - }), true, page); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.DefaultGridColumns, 0, Theme.SLIDER_WIDTH, 1, 20, profile.Grid_DefaultColumns, (i) => - { - profile.Grid_DefaultColumns = i; - }), true, page); - - content.BlankLine(); - - content.AddToRight(c = new ModernButton(0, 0, 200, 40, ButtonAction.Activate, lang.GetTazUO.GridHighlightSettings, Theme.BUTTON_FONT_COLOR), true, page); - c.MouseUp += (s, e) => - { - UIManager.GetGump()?.Dispose(); - UIManager.Add(new GridHightlightMenu()); - }; - content.AddToRight(new SliderWithLabel(lang.GetTazUO.GridHighlightSize, 0, Theme.SLIDER_WIDTH, 1, 5, profile.GridHightlightSize, (i) => - { - profile.GridHightlightSize = i; - }), true, page); - #endregion - - #region Journal - page = ((int)PAGE.TUOOptions + 1001); - content.ResetRightSide(); - - content.AddToLeft(SubCategoryButton(lang.GetTazUO.Journal, page, content.LeftWidth)); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.MaxJournalEntries, 0, Theme.SLIDER_WIDTH, 100, 2000, profile.MaxJournalEntries, (i) => - { - profile.MaxJournalEntries = i; - }), true, page); - content.BlankLine(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.JournalOpacity, 0, Theme.SLIDER_WIDTH, 0, 100, profile.JournalOpacity, (i) => - { - profile.JournalOpacity = (byte)i; - ResizableJournal.UpdateJournalOptions(); - }), true, page); - content.Indent(); - content.AddToRight(new ModernColorPickerWithLabel(lang.GetTazUO.JournalBackgroundColor, profile.AltJournalBackgroundHue, (h) => - { - profile.AltJournalBackgroundHue = h; - ResizableJournal.UpdateJournalOptions(); - }), true, page); - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(new ComboBoxWithLabel(lang.GetTazUO.JournalStyle, 0, Theme.COMBO_BOX_WIDTH, Enum.GetNames(typeof(ResizableJournal.BorderStyle)), profile.JournalStyle, (i, s) => - { - profile.JournalStyle = i; - ResizableJournal.UpdateJournalOptions(); - }), true, page); - content.BlankLine(); - content.AddToRight(c = new CheckboxWithLabel(lang.GetTazUO.JournalHideBorders, 0, profile.HideJournalBorder, (b) => - { - profile.HideJournalBorder = b; - ResizableJournal.UpdateJournalOptions(); - }), true, page); - content.BlankLine(); - content.AddToRight(c = new CheckboxWithLabel(lang.GetTazUO.HideTimestamp, 0, profile.HideJournalTimestamp, (b) => - { - profile.HideJournalTimestamp = b; - }), true, page); - #endregion - - #region Modern paperdoll - page = ((int)PAGE.TUOOptions + 1002); - content.AddToLeft(SubCategoryButton(lang.GetTazUO.ModernPaperdoll, page, content.LeftWidth)); - content.ResetRightSide(); - content.AddToRight(c = new CheckboxWithLabel(lang.GetTazUO.EnableModernPaperdoll, 0, profile.UseModernPaperdoll, (b) => - { - profile.UseModernPaperdoll = b; - }), true, page); - content.Indent(); - content.BlankLine(); - content.AddToRight(new ModernColorPickerWithLabel(lang.GetTazUO.PaperdollHue, profile.ModernPaperDollHue, (h) => - { - profile.ModernPaperDollHue = h; - ModernPaperdoll.UpdateAllOptions(); - }), true, page); - content.BlankLine(); - content.AddToRight(new ModernColorPickerWithLabel(lang.GetTazUO.DurabilityBarHue, profile.ModernPaperDollDurabilityHue, (h) => - { - profile.ModernPaperDollDurabilityHue = h; - }), true, page); - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.ShowDurabilityBarBelow, 0, Theme.SLIDER_WIDTH, 1, 100, profile.ModernPaperDoll_DurabilityPercent, (i) => - { - profile.ModernPaperDoll_DurabilityPercent = i; - }), true, page); - #endregion - - #region Nameplates - page = ((int)PAGE.TUOOptions + 1003); - content.AddToLeft(SubCategoryButton(lang.GetTazUO.Nameplates, page, content.LeftWidth)); - content.ResetRightSide(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.NameplatesAlsoActAsHealthBars, 0, profile.NamePlateHealthBar, (b) => - { - profile.NamePlateHealthBar = b; - }), true, page); - content.Indent(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.HpOpacity, 0, Theme.SLIDER_WIDTH, 0, 100, profile.NamePlateHealthBarOpacity, (i) => - { - profile.NamePlateHealthBarOpacity = (byte)i; - }), true, page); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.HideNameplatesIfFullHealth, 0, profile.NamePlateHideAtFullHealth, (b) => - { - profile.NamePlateHideAtFullHealth = b; - }), true, page); - content.Indent(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.OnlyInWarmode, 0, profile.NamePlateHideAtFullHealthInWarmode, (b) => - { - profile.NamePlateHideAtFullHealthInWarmode = b; - }), true, page); - content.RemoveIndent(); - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.BorderOpacity, 0, Theme.SLIDER_WIDTH, 0, 100, profile.NamePlateBorderOpacity, (i) => - { - profile.NamePlateBorderOpacity = (byte)i; - }), true, page); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.BackgroundOpacity, 0, Theme.SLIDER_WIDTH, 0, 100, profile.NamePlateOpacity, (i) => - { - profile.NamePlateOpacity = (byte)i; - }), true, page); - #endregion - - #region Mobiles - page = ((int)PAGE.TUOOptions + 1004); - content.AddToLeft(SubCategoryButton(lang.GetTazUO.Mobiles, page, content.LeftWidth)); - content.ResetRightSide(); - content.AddToRight(c = new ModernColorPickerWithLabel(lang.GetTazUO.DamageToSelf, profile.DamageHueSelf, (h) => - { - profile.DamageHueSelf = h; - }), true, page); - content.AddToRight(c = new ModernColorPickerWithLabel(lang.GetTazUO.DamageToOthers, profile.DamageHueOther, (h) => - { - profile.DamageHueOther = h; - }) - { X = 250, Y = c.Y }, false, page); - content.AddToRight(c = new ModernColorPickerWithLabel(lang.GetTazUO.DamageToPets, profile.DamageHuePet, (h) => - { - profile.DamageHuePet = h; - }), true, page); - content.AddToRight(c = new ModernColorPickerWithLabel(lang.GetTazUO.DamageToAllies, profile.DamageHueAlly, (h) => - { - profile.DamageHueAlly = h; - }) - { X = 250, Y = c.Y }, false, page); - content.AddToRight(c = new ModernColorPickerWithLabel(lang.GetTazUO.DamageToLastAttack, profile.DamageHueLastAttck, (h) => - { - profile.DamageHueLastAttck = h; - }), true, page); - content.BlankLine(); - content.AddToRight(c = new CheckboxWithLabel(lang.GetTazUO.DisplayPartyChatOverPlayerHeads, 0, profile.DisplayPartyChatOverhead, (b) => - { - profile.DisplayPartyChatOverhead = b; - }), true, page); - c.SetTooltip(lang.GetTazUO.TooltipPartyChat); - content.BlankLine(); - content.AddToRight(c = new SliderWithLabel(lang.GetTazUO.OverheadTextWidth, 0, Theme.SLIDER_WIDTH, 0, 600, profile.OverheadChatWidth, (i) => - { - profile.OverheadChatWidth = i; - }), true, page); - c.SetTooltip(lang.GetTazUO.TooltipOverheadText); - content.BlankLine(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.BelowMobileHealthBarScale, 0, Theme.SLIDER_WIDTH, 1, 5, profile.HealthLineSizeMultiplier, (i) => - { - profile.HealthLineSizeMultiplier = (byte)i; - }), true, page); - content.BlankLine(); - content.AddToRight(c = new CheckboxWithLabel(lang.GetTazUO.AutomaticallyOpenHealthBarsForLastAttack, 0, profile.OpenHealthBarForLastAttack, (b) => - { - profile.OpenHealthBarForLastAttack = b; - }), true, page); - content.Indent(); - content.AddToRight(c = new CheckboxWithLabel(lang.GetTazUO.UpdateOneBarAsLastAttack, 0, profile.UseOneHPBarForLastAttack, (b) => - { - profile.UseOneHPBarForLastAttack = b; - }), true, page); - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.HiddenPlayerOpacity, 0, Theme.SLIDER_WIDTH, 0, 100, profile.HiddenBodyAlpha, (i) => - { - profile.HiddenBodyAlpha = (byte)i; - }), true, page); - content.Indent(); - content.AddToRight(c = new ModernColorPickerWithLabel(lang.GetTazUO.HiddenPlayerHue, profile.HiddenBodyHue, (h) => - { - profile.HiddenBodyHue = h; - }), true, page); - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.RegularPlayerOpacity, 0, Theme.SLIDER_WIDTH, 0, 100, profile.PlayerConstantAlpha, (i) => - { - profile.PlayerConstantAlpha = i; - }), true, page); - content.BlankLine(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.AutoFollowDistance, 0, Theme.SLIDER_WIDTH, 0, 10, profile.AutoFollowDistance, (i) => - { - profile.AutoFollowDistance = i; - }), true, page); - content.BlankLine(); - content.AddToRight(c = new CheckboxWithLabel(lang.GetTazUO.DisableMouseInteractionsForOverheadText, 0, profile.DisableMouseInteractionOverheadText, (b) => - { - profile.DisableMouseInteractionOverheadText = b; - }), true, page); - content.BlankLine(); - content.AddToRight(c = new CheckboxWithLabel(lang.GetTazUO.OverridePartyMemberHues, 0, profile.OverridePartyAndGuildHue, (b) => - { - profile.OverridePartyAndGuildHue = b; - }), true, page); - #endregion - - #region Misc - page = ((int)PAGE.TUOOptions + 1005); - content.AddToLeft(SubCategoryButton(lang.GetTazUO.Misc, page, content.LeftWidth)); - content.ResetRightSide(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.DisableSystemChat, 0, profile.DisableSystemChat, (b) => - { - profile.DisableSystemChat = b; - }), true, page); - content.BlankLine(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.EnableImprovedBuffGump, 0, profile.UseImprovedBuffBar, (b) => - { - profile.UseImprovedBuffBar = b; - }), true, page); - content.Indent(); - content.AddToRight(new ModernColorPickerWithLabel(lang.GetTazUO.BuffGumpHue, profile.ImprovedBuffBarHue, (h) => - { - profile.ImprovedBuffBarHue = h; - }), true, page); - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(new ModernColorPickerWithLabel(lang.GetTazUO.MainGameWindowBackground, profile.MainWindowBackgroundHue, (h) => - { - profile.MainWindowBackgroundHue = h; - GameController.UpdateBackgroundHueShader(); - }), true, page); - content.BlankLine(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.EnableHealthIndicatorBorder, 0, profile.EnableHealthIndicator, (b) => - { - profile.EnableHealthIndicator = b; - }), true, page); - content.Indent(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.OnlyShowBelowHp, 0, Theme.SLIDER_WIDTH, 1, 100, (int)profile.ShowHealthIndicatorBelow * 100, (i) => - { - profile.ShowHealthIndicatorBelow = i / 100f; - }), true, page); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.Size, 0, Theme.SLIDER_WIDTH, 1, 25, profile.HealthIndicatorWidth, (i) => - { - profile.HealthIndicatorWidth = i; - }), true, page); - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.SpellIconScale, 0, Theme.SLIDER_WIDTH, 50, 300, profile.SpellIconScale, (i) => - { - profile.SpellIconScale = i; - }), true, page); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.DisplayMatchingHotkeysOnSpellIcons, 0, profile.SpellIcon_DisplayHotkey, (b) => - { - profile.SpellIcon_DisplayHotkey = b; - }), true, page); - content.Indent(); - content.AddToRight(new ModernColorPickerWithLabel(lang.GetTazUO.HotkeyTextHue, profile.SpellIcon_HotkeyHue, (h) => - { - profile.SpellIcon_HotkeyHue = h; - }), true, page); - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.EnableGumpOpacityAdjustViaAltScroll, 0, profile.EnableAlphaScrollingOnGumps, (b) => - { - profile.EnableAlphaScrollingOnGumps = b; - }), true, page); - content.BlankLine(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.EnableAdvancedShopGump, 0, profile.UseModernShopGump, (b) => - { - profile.UseModernShopGump = b; - }), true, page); - content.BlankLine(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.DisplaySkillProgressBarOnSkillChanges, 0, profile.DisplaySkillBarOnChange, (b) => - { - profile.DisplaySkillBarOnChange = b; - }), true, page); - content.Indent(); - content.AddToRight(new InputFieldWithLabel(lang.GetTazUO.TextFormat, Theme.INPUT_WIDTH, profile.SkillBarFormat, false, (s, e) => - { - profile.SkillBarFormat = ((InputField.StbTextBox)s).Text; - }), true, page); - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.EnableSpellIndicatorSystem, 0, profile.EnableSpellIndicators, (b) => - { - profile.EnableSpellIndicators = b; - }), true, page); - content.Indent(); - content.AddToRight(c = new ModernButton(0, 0, 200, 40, ButtonAction.Activate, lang.GetTazUO.ImportFromUrl, Theme.BUTTON_FONT_COLOR) { IsSelectable = true, IsSelected = true }, true, page); - c.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - UIManager.Add(new InputRequest(lang.GetTazUO.InputRequestUrl, lang.GetTazUO.Download, lang.GetTazUO.Cancel, (r, s) => - { - if (r == InputRequest.Result.BUTTON1 && !string.IsNullOrEmpty(s)) - { - if (Uri.TryCreate(s, UriKind.Absolute, out var uri)) - { - GameActions.Print(lang.GetTazUO.AttemptingToDownloadSpellConfig); - Task.Factory.StartNew(() => - { - try - { - using HttpClient httpClient = new HttpClient(); - string result = httpClient.GetStringAsync(uri).Result; - if (SpellVisualRangeManager.Instance.LoadFromString(result)) - { - GameActions.Print(lang.GetTazUO.SuccesfullyDownloadedNewSpellConfig); - } - } - catch (Exception ex) - { - GameActions.Print(string.Format(lang.GetTazUO.FailedToDownloadTheSpellConfigExMessage, ex.Message)); - } - }); - } - } - }) - { X = (Client.Game.Window.ClientBounds.Width >> 1) - 50, Y = (Client.Game.Window.ClientBounds.Height >> 1) - 50 }); - } - }; - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.AlsoCloseAnchoredHealthbarsWhenAutoClosingHealthbars, content.RightWidth - 30, profile.CloseHealthBarIfAnchored, (b) => - { - profile.CloseHealthBarIfAnchored = b; - }), true, page); - content.BlankLine(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.EnableAutoResyncOnHangDetection, 0, profile.ForceResyncOnHang, (b) => - { - profile.ForceResyncOnHang = b; - }), true, page); - content.BlankLine(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.PlayerOffsetX, 0, Theme.SLIDER_WIDTH, -20, 20, profile.PlayerOffset.X, (i) => - { - profile.PlayerOffset = new Point(i, profile.PlayerOffset.Y); - }), true, page); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.PlayerOffsetY, 0, Theme.SLIDER_WIDTH, -20, 20, profile.PlayerOffset.Y, (i) => - { - profile.PlayerOffset = new Point(profile.PlayerOffset.X, i); - }), true, page); - content.BlankLine(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.UseLandTexturesWhereAvailable, 0, profile.UseLandTextures, (b) => - { - profile.UseLandTextures = b; - }), true, page); - content.BlankLine(); - content.AddToRight(new InputFieldWithLabel(lang.GetTazUO.SOSGumpID, Theme.INPUT_WIDTH, profile.SOSGumpID.ToString(), true, (s, e) => { if (uint.TryParse(((InputField.StbTextBox)s).Text, out uint id)) { profile.SOSGumpID = id; } })); - #endregion - - #region Tooltips - page = ((int)PAGE.TUOOptions + 1006); - content.AddToLeft(SubCategoryButton(lang.GetTazUO.Tooltips, page, content.LeftWidth)); - content.ResetRightSide(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.AlignTooltipsToTheLeftSide, 0, profile.LeftAlignToolTips, (b) => - { - profile.LeftAlignToolTips = b; - }), true, page); - content.Indent(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.AlignMobileTooltipsToCenter, 0, profile.ForceCenterAlignTooltipMobiles, (b) => - { - profile.ForceCenterAlignTooltipMobiles = b; - }), true, page); - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(new ModernColorPickerWithLabel(lang.GetTazUO.BackgroundHue, profile.ToolTipBGHue, (h) => - { - profile.ToolTipBGHue = h; - }), true, page); - content.BlankLine(); - content.AddToRight(new InputFieldWithLabel(lang.GetTazUO.HeaderFormatItemName, Theme.INPUT_WIDTH, profile.TooltipHeaderFormat, false, (s, e) => - { - profile.TooltipHeaderFormat = ((InputField.StbTextBox)s).Text; - }), true, page); - content.BlankLine(); - content.AddToRight(c = new ModernButton(0, 0, 200, 40, ButtonAction.Activate, lang.GetTazUO.TooltipOverrideSettings, Theme.BUTTON_FONT_COLOR) { IsSelectable = true, IsSelected = true }, true, page); - c.MouseUp += (s, e) => { UIManager.GetGump()?.Dispose(); UIManager.Add(new ToolTipOverideMenu()); }; - - #endregion - - #region Font settings - page = ((int)PAGE.TUOOptions + 1007); - content.AddToLeft(SubCategoryButton(lang.GetTazUO.FontSettings, page, content.LeftWidth)); - content.ResetRightSide(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.TtfFontBorder, 0, Theme.SLIDER_WIDTH, 0, 2, profile.TextBorderSize, (i) => - { - profile.TextBorderSize = i; - }), true, page); - content.BlankLine(); - content.BlankLine(); - content.AddToRight(GenerateFontSelector(lang.GetTazUO.InfobarFont, ProfileManager.CurrentProfile.InfoBarFont, (i, s) => - { - ProfileManager.CurrentProfile.InfoBarFont = s; - InfoBarGump.UpdateAllOptions(); - }), true, page); - content.Indent(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.SharedSize, 0, Theme.SLIDER_WIDTH, 5, 40, profile.InfoBarFontSize, (i) => - { - profile.InfoBarFontSize = i; - InfoBarGump.UpdateAllOptions(); - }), true, page); - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(GenerateFontSelector(lang.GetTazUO.SystemChatFont, ProfileManager.CurrentProfile.GameWindowSideChatFont, (i, s) => - { - ProfileManager.CurrentProfile.GameWindowSideChatFont = s; - }), true, page); - content.Indent(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.SharedSize, 0, Theme.SLIDER_WIDTH, 5, 40, profile.GameWindowSideChatFontSize, (i) => - { - profile.GameWindowSideChatFontSize = i; - }), true, page); - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(GenerateFontSelector(lang.GetTazUO.TooltipFont, ProfileManager.CurrentProfile.SelectedToolTipFont, (i, s) => - { - ProfileManager.CurrentProfile.SelectedToolTipFont = s; - }), true, page); - content.Indent(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.SharedSize, 0, Theme.SLIDER_WIDTH, 5, 40, profile.SelectedToolTipFontSize, (i) => - { - profile.SelectedToolTipFontSize = i; - }), true, page); - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(GenerateFontSelector(lang.GetTazUO.OverheadFont, ProfileManager.CurrentProfile.OverheadChatFont, (i, s) => - { - ProfileManager.CurrentProfile.OverheadChatFont = s; - }), true, page); - content.Indent(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.SharedSize, 0, Theme.SLIDER_WIDTH, 5, 40, profile.OverheadChatFontSize, (i) => - { - profile.OverheadChatFontSize = i; - }), true, page); - content.RemoveIndent(); - content.BlankLine(); - content.AddToRight(GenerateFontSelector(lang.GetTazUO.JournalFont, ProfileManager.CurrentProfile.SelectedTTFJournalFont, (i, s) => - { - ProfileManager.CurrentProfile.SelectedTTFJournalFont = s; - }), true, page); - content.Indent(); - content.AddToRight(new SliderWithLabel(lang.GetTazUO.SharedSize, 0, Theme.SLIDER_WIDTH, 5, 40, profile.SelectedJournalFontSize, (i) => - { - profile.SelectedJournalFontSize = i; - }), true, page); - content.RemoveIndent(); - content.BlankLine(); - #endregion - - #region Controller settings - page = ((int)PAGE.TUOOptions + 1008); - content.AddToLeft(SubCategoryButton(lang.GetTazUO.Controller, page, content.LeftWidth)); - content.ResetRightSide(); - - content.AddToRight(new SliderWithLabel(lang.GetTazUO.MouseSesitivity, 0, Theme.SLIDER_WIDTH, 1, 20, profile.ControllerMouseSensativity, (i) => { profile.ControllerMouseSensativity = i; }), true, page); - - #endregion - - #region Settings transfers - page = ((int)PAGE.TUOOptions + 1009); - content.AddToLeft(SubCategoryButton(lang.GetTazUO.SettingsTransfers, page, content.LeftWidth)); - content.ResetRightSide(); - - string rootpath; - - if (string.IsNullOrWhiteSpace(Settings.GlobalSettings.ProfilesPath)) - { - rootpath = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Profiles"); - } - else - { - rootpath = Settings.GlobalSettings.ProfilesPath; - } - - List locations = new List(); - List sameServerLocations = new List(); - string[] allAccounts = Directory.GetDirectories(rootpath); - - foreach (string account in allAccounts) - { - string[] allServers = Directory.GetDirectories(account); - foreach (string server in allServers) - { - string[] allCharacters = Directory.GetDirectories(server); - foreach (string character in allCharacters) - { - locations.Add(new ProfileLocationData(server, account, character)); - if (FileSystemHelper.RemoveInvalidChars(profile.ServerName) == FileSystemHelper.RemoveInvalidChars(Path.GetFileName(server))) - { - sameServerLocations.Add(new ProfileLocationData(server, account, character)); - } - } - } - } - - content.AddToRight(new TextBox( - string.Format(lang.GetTazUO.SettingsWarning, locations.Count), - Theme.FONT, - Theme.STANDARD_TEXT_SIZE, - content.RightWidth - 20, - Theme.TEXT_FONT_COLOR, - FontStashSharp.RichText.TextHorizontalAlignment.Center, - false), true, page); - - content.AddToRight(c = new ModernButton(0, 0, content.RightWidth - 20, 40, ButtonAction.Activate, string.Format(lang.GetTazUO.OverrideAll, locations.Count - 1), Theme.BUTTON_FONT_COLOR) { IsSelectable = true, IsSelected = true }, true, page); - c.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - OverrideAllProfiles(locations); - GameActions.Print(string.Format(lang.GetTazUO.OverrideSuccess, locations.Count - 1), 32, Data.MessageType.System); - } - }; - - content.AddToRight(c = new ModernButton(0, 0, content.RightWidth - 20, 40, ButtonAction.Activate, string.Format(lang.GetTazUO.OverrideSame, sameServerLocations.Count - 1), Theme.BUTTON_FONT_COLOR) { IsSelectable = true, IsSelected = true }, true, page); - c.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - OverrideAllProfiles(sameServerLocations); - GameActions.Print(string.Format(lang.GetTazUO.OverrideSuccess, sameServerLocations.Count - 1), 32, Data.MessageType.System); - } - }; - #endregion - - #region Gump scaling - page = ((int)PAGE.TUOOptions + 1010); - content.AddToLeft(SubCategoryButton(lang.GetTazUO.GumpScaling, page, content.LeftWidth)); - content.ResetRightSide(); - - content.AddToRight(new TextBox(lang.GetTazUO.ScalingInfo, Theme.FONT, Theme.STANDARD_TEXT_SIZE, content.RightWidth - 20, Theme.TEXT_FONT_COLOR, FontStashSharp.RichText.TextHorizontalAlignment.Center, false), true, page); - - content.BlankLine(); - - content.AddToRight(new SliderWithLabel(lang.GetTazUO.PaperdollGump, 0, Theme.SLIDER_WIDTH, 50, 300, (int)(profile.PaperdollScale * 100), (i) => - { - //Must be cast even though VS thinks it's redundant. - double v = (double)i / (double)100; - profile.PaperdollScale = v > 0 ? v : 1f; - }), true, page); - #endregion - - content.AddToLeft(c = new ModernButton(0, 0, content.LeftWidth, 40, ButtonAction.Activate, lang.GetTazUO.AutoLoot, Theme.BUTTON_FONT_COLOR)); - c.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - AutoLootOptions.AddToUI(); - } - }; - - #region Hidden layers - page = ((int)PAGE.TUOOptions + 1011); - content.AddToLeft(SubCategoryButton(lang.GetTazUO.VisibleLayers, page, content.LeftWidth)); - content.ResetRightSide(); - content.AddToRight(new TextBox(lang.GetTazUO.VisLayersInfo, Theme.FONT, Theme.STANDARD_TEXT_SIZE, content.RightWidth - 20, Theme.TEXT_FONT_COLOR, FontStashSharp.RichText.TextHorizontalAlignment.Center, false) { AcceptMouseInput = false }, true, page); - content.BlankLine(); - content.AddToRight(new CheckboxWithLabel(lang.GetTazUO.OnlyForYourself, 0, profile.HideLayersForSelf, (b) => - { - profile.HideLayersForSelf = b; - }), true, page); - content.BlankLine(); - - bool rightSide = false; - foreach (Layer layer in (Layer[])Enum.GetValues(typeof(Layer))) - { - if (layer == Layer.Invalid || layer == Layer.Hair || layer == Layer.Beard || layer == Layer.Backpack || layer == Layer.ShopBuyRestock || layer == Layer.ShopBuy || layer == Layer.ShopSell || layer == Layer.Bank || layer == Layer.Face || layer == Layer.Talisman || layer == Layer.Mount) - { - continue; - } - if (!rightSide) - { - content.AddToRight(c = new CheckboxWithLabel(layer.ToString(), 0, profile.HiddenLayers.Contains((int)layer), (b) => { if (b) { profile.HiddenLayers.Add((int)layer); } else { profile.HiddenLayers.Remove((int)layer); } }), true, page); - rightSide = true; - } - else - { - content.AddToRight(new CheckboxWithLabel(layer.ToString(), 0, profile.HiddenLayers.Contains((int)layer), (b) => { if (b) { profile.HiddenLayers.Add((int)layer); } else { profile.HiddenLayers.Remove((int)layer); } }) { X = 200, Y = c.Y }, false, page); - rightSide = false; - } - } - #endregion - - options.Add( - new SettingsOption( - "", - content, - mainContent.RightWidth, - PAGE.TUOOptions - ) - ); - } - - public string GetPageString() - { - string page = mainContent.ActivePage.ToString(); - - foreach (Control c in mainContent.RightArea.Children) - { - if (c is Area && c.Page == mainContent.ActivePage) - { - foreach (Control c2 in c.Children) - { - if (c2 is LeftSideMenuRightSideContent) - { - page += ":" + c2.ActivePage; - return page; - } - } - } - } - return page; - } - - public void GoToPage(string pageString) - { - string[] parts = pageString.Split(':'); - - if (parts.Length >= 1) - { - if (int.TryParse(parts[0], out int p)) - { - ChangePage(p); - - if (parts.Length >= 2) - { - if (int.TryParse(parts[1], out int pp)) - { - foreach (Control c in mainContent.RightArea.Children) - { - if (c is Area && c.Page == p) - { - foreach (Control c2 in c.Children) - { - if (c2 is LeftSideMenuRightSideContent lsc) - { - lsc.ActivePage = pp; - foreach (Control mb in lsc.LeftArea.Children) - { - if (mb is ModernButton button && button.ButtonParameter == pp && button.IsSelectable) - { - button.IsSelected = true; - break; - } - } - return; - } - } - } - } - } - } - } - } - - - } - - public override void ChangePage(int pageIndex) - { - base.ChangePage(pageIndex); - foreach (Control mb in mainContent.LeftArea.Children) - { - if (mb is ModernButton button && button.ButtonParameter == pageIndex && button.IsSelectable) - { - button.IsSelected = true; - break; - } - } - } - - private void OverrideAllProfiles(List allProfiles) - { - foreach (var profile in allProfiles) - { - ProfileManager.CurrentProfile.Save(profile.ToString(), false); - } - } - - private ComboBoxWithLabel GenerateFontSelector(string label, string selectedFont = "", Action onSelect = null) - { - string[] fontArray = TrueTypeLoader.Instance.Fonts; - int selectedFontInd = Array.IndexOf(fontArray, selectedFont); - return new ComboBoxWithLabel(label, 0, Theme.COMBO_BOX_WIDTH, fontArray, selectedFontInd, onSelect); - } - - private ModernButton CategoryButton(string text, int page, int width, int height = 40) - { - return new ModernButton(0, 0, width, height, ButtonAction.SwitchPage, text, Theme.BUTTON_FONT_COLOR) { ButtonParameter = page, FullPageSwitch = true }; - } - - private ModernButton SubCategoryButton(string text, int page, int width, int height = 40) - { - return new ModernButton(0, 0, width, height, ButtonAction.SwitchPage, text, Theme.BUTTON_FONT_COLOR) { ButtonParameter = page }; - } - - public Control GenConditionControl(int key, int width, bool createIfNotExists) - { - CoolDownBar.CoolDownConditionData data = CoolDownBar.CoolDownConditionData.GetConditionData(key, createIfNotExists); - Area main = new Area - { - Width = width - }; - - AlphaBlendControl _background = new AlphaBlendControl(); - main.Add(_background); - - ModernButton _delete = new ModernButton(1, 1, 30, 40, ButtonAction.Activate, "X", Theme.BUTTON_FONT_COLOR); - _delete.SetTooltip("Delete this cooldown bar"); - _delete.MouseUp += (sender, e) => - { - if (e.Button == MouseButtonType.Left) - { - CoolDownBar.CoolDownConditionData.RemoveCondition(key); - - Gump g = UIManager.GetGump(); - if (g != null) - { - Point pos = g.Location; - g.Dispose(); - g = new ModernOptionsGump() { Location = pos }; - g.ChangePage((int)PAGE.TUOCooldowns); - UIManager.Add(g); - } - } - }; - main.Add(_delete); - - - TextBox _hueLabel = new TextBox("Hue:", Theme.FONT, Theme.STANDARD_TEXT_SIZE, null, Theme.BUTTON_FONT_COLOR, strokeEffect: false); - _hueLabel.X = _delete.X + _delete.Width + 5; - _hueLabel.Y = 10; - main.Add(_hueLabel); - - ModernColorPickerWithLabel _hueSelector = new ModernColorPickerWithLabel(string.Empty, data.hue) { X = _hueLabel.X + _hueLabel.Width + 5, Y = 10 }; - main.Add(_hueSelector); - - - InputField _name = new InputField(140, 40, text: data.label) { X = _hueSelector.X + _hueSelector.Width + 10, Y = 1 }; - main.Add(_name); - - - TextBox _cooldownLabel = new TextBox("Cooldown:", Theme.FONT, Theme.STANDARD_TEXT_SIZE, null, Theme.BUTTON_FONT_COLOR, strokeEffect: false); - _cooldownLabel.X = _name.X + _name.Width + 10; - _cooldownLabel.Y = 10; - main.Add(_cooldownLabel); - - InputField _cooldown = new InputField(45, 40, numbersOnly: true, text: data.cooldown.ToString()) { Y = 1 }; - _cooldown.X = _cooldownLabel.X + _cooldownLabel.Width + 10; - main.Add(_cooldown); - - ComboBoxWithLabel _message_type = new ComboBoxWithLabel(string.Empty, 0, 85, new string[] { "All", "Self", "Other" }, data.message_type) { X = _cooldown.X + _cooldown.Width + 10, Y = 10 }; - main.Add(_message_type); - - InputField _conditionText = new InputField(main.Width - 50, 40, text: data.trigger) { X = 1, Y = _delete.Height + 5 }; - main.Add(_conditionText); - - CheckboxWithLabel _replaceIfExists = new CheckboxWithLabel(isChecked: data.replace_if_exists) { X = _conditionText.X + _conditionText.Width + 2, Y = _conditionText.Y + 5 }; - _replaceIfExists.SetTooltip("Replace any active cooldown of this type with a new one if triggered again."); - main.Add(_replaceIfExists); - - ModernButton _save = new ModernButton(0, 1, 40, 40, ButtonAction.Activate, "Save", Theme.BUTTON_FONT_COLOR); - _save.X = main.Width - _save.Width; - _save.IsSelectable = true; - _save.IsSelected = true; - _save.MouseUp += (s, e) => - { - CoolDownBar.CoolDownConditionData.SaveCondition(key, _hueSelector.Hue, _name.Text, _conditionText.Text, int.Parse(_cooldown.Text), false, _message_type.SelectedIndex, _replaceIfExists.IsChecked); - }; - main.Add(_save); - - ModernButton _preview = new ModernButton(0, 1, 65, 40, ButtonAction.Activate, "Preview", Theme.BUTTON_FONT_COLOR); - _preview.X = _save.X - _preview.Width - 15; - _preview.IsSelectable = true; - _preview.IsSelected = true; - _preview.MouseUp += (s, e) => - { - CoolDownBarManager.AddCoolDownBar(TimeSpan.FromSeconds(int.Parse(_cooldown.Text)), _name.Text, _hueSelector.Hue, _replaceIfExists.IsChecked); - }; - main.Add(_preview); - - main.Height = _conditionText.Bounds.Bottom; - - _background.Width = width; - _background.Height = main.Height; - return main; - } - - public override void OnPageChanged() - { - base.OnPageChanged(); - - mainContent.ActivePage = ActivePage; - } - - public override void Dispose() - { - base.Dispose(); - - SearchValueChanged = null; - } - - public static void SetParentsForMatchingSearch(Control c, int page) - { - for (Control p = c.Parent; p != null; p = p.Parent) - { - if (p is LeftSideMenuRightSideContent content) - { - content.SetMatchingButton(page); - } - } - } - - #region Custom Controls For Options - private class ModernColorPickerWithLabel : Control, SearchableOption - { - private TextBox _label; - private ModernColorPicker.HueDisplay _colorPicker; - - public ModernColorPickerWithLabel(string text, ushort hue, Action hueSelected = null, int maxWidth = 0) - { - AcceptMouseInput = true; - CanMove = true; - WantUpdateSize = false; - - Add(_colorPicker = new ModernColorPicker.HueDisplay(hue, hueSelected, true)); - - Add(_label = new TextBox(text, Theme.FONT, Theme.STANDARD_TEXT_SIZE, maxWidth > 0 ? maxWidth : null, Theme.TEXT_FONT_COLOR, strokeEffect: false) { X = _colorPicker.Width + 5 }); - - Width = _label.Width + _colorPicker.Width + 5; - Height = Math.Max(_colorPicker.Height, _label.MeasuredSize.Y); - - ModernOptionsGump.SearchValueChanged += ModernOptionsGump_SearchValueChanged; - } - - public ushort Hue => _colorPicker.Hue; - - private void ModernOptionsGump_SearchValueChanged(object sender, EventArgs e) - { - if (!string.IsNullOrEmpty(ModernOptionsGump.SearchText)) - { - if (Search(ModernOptionsGump.SearchText)) - { - OnSearchMatch(); - ModernOptionsGump.SetParentsForMatchingSearch(this, Page); - } - else - { - _label.Alpha = Theme.NO_MATCH_SEARCH; - } - } - else - { - _label.Alpha = 1f; - } - } - - public bool Search(string text) - { - return _label.Text.ToLower().Contains(text.ToLower()); - } - - public void OnSearchMatch() - { - _label.Alpha = 1f; - } - } - - private class CheckboxWithLabel : Control, SearchableOption - { - private const int CHECKBOX_SIZE = 30; - - private bool _isChecked; - private readonly TextBox _text; - - public TextBox TextLabel => _text; - - private Vector3 hueVector = ShaderHueTranslator.GetHueVector(Theme.SEARCH_BACKGROUND, false, 0.9f); - - public CheckboxWithLabel( - string text = "", - int maxWidth = 0, - bool isChecked = false, - Action valueChanged = null - ) - { - _isChecked = isChecked; - ValueChanged = valueChanged; - _text = new TextBox(text, Theme.FONT, Theme.STANDARD_TEXT_SIZE, maxWidth == 0 ? null : maxWidth, Theme.TEXT_FONT_COLOR, strokeEffect: false) { X = CHECKBOX_SIZE + 5, AcceptMouseInput = false }; - - Width = CHECKBOX_SIZE + 5 + _text.Width; - Height = Math.Max(CHECKBOX_SIZE, _text.MeasuredSize.Y); - - _text.Y = (Height / 2) - (_text.Height / 2); - - CanMove = true; - AcceptMouseInput = true; - - ModernOptionsGump.SearchValueChanged += ModernOptionsGump_SearchValueChanged; - } - - private void ModernOptionsGump_SearchValueChanged(object sender, EventArgs e) - { - if (!string.IsNullOrEmpty(ModernOptionsGump.SearchText)) - { - if (Search(ModernOptionsGump.SearchText)) - { - OnSearchMatch(); - ModernOptionsGump.SetParentsForMatchingSearch(this, Page); - } - else - { - _text.Alpha = Theme.NO_MATCH_SEARCH; - } - } - else - { - _text.Alpha = 1f; - } - } - - public bool IsChecked - { - get => _isChecked; - set - { - if (_isChecked != value) - { - _isChecked = value; - OnCheckedChanged(); - } - } - } - - public override ClickPriority Priority => ClickPriority.High; - - public string Text => _text.Text; - - public Action ValueChanged { get; } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsDisposed) - { - return false; - } - - batcher.Draw( - SolidColorTextureCache.GetTexture(Color.White), - new Rectangle(x, y, CHECKBOX_SIZE, CHECKBOX_SIZE), - hueVector - ); - - if (IsChecked) - { - batcher.Draw( - SolidColorTextureCache.GetTexture(Color.Black), - new Rectangle(x + (CHECKBOX_SIZE / 2) / 2, y + (CHECKBOX_SIZE / 2) / 2, CHECKBOX_SIZE / 2, CHECKBOX_SIZE / 2), - hueVector - ); - } - - _text.Draw(batcher, x + _text.X, y + _text.Y); - - return base.Draw(batcher, x, y); - } - - protected virtual void OnCheckedChanged() - { - ValueChanged?.Invoke(IsChecked); - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left && MouseIsOver) - { - IsChecked = !IsChecked; - } - } - - public override void Dispose() - { - base.Dispose(); - _text?.Dispose(); - } - - public bool Search(string text) - { - return _text.Text.ToLower().Contains(text.ToLower()); - } - - public void OnSearchMatch() - { - _text.Alpha = 1f; - } - } - - private class SliderWithLabel : Control, SearchableOption - { - private readonly TextBox _label; - private readonly Slider _slider; - - public SliderWithLabel(string label, int textWidth, int barWidth, int min, int max, int value, Action valueChanged = null) - { - AcceptMouseInput = true; - CanMove = true; - - Add(_label = new TextBox(label, Theme.FONT, Theme.STANDARD_TEXT_SIZE, textWidth > 0 ? textWidth : null, Theme.TEXT_FONT_COLOR, strokeEffect: false)); - Add(_slider = new Slider(barWidth, min, max, value, valueChanged) { X = _label.X + _label.Width + 5 }); - - Width = textWidth + barWidth + 5; - Height = Math.Max(_label.Height, _slider.Height); - - _slider.Y = (Height / 2) - (_slider.Height / 2); - - ModernOptionsGump.SearchValueChanged += ModernOptionsGump_SearchValueChanged; - } - - private void ModernOptionsGump_SearchValueChanged(object sender, EventArgs e) - { - if (!string.IsNullOrEmpty(ModernOptionsGump.SearchText)) - { - if (Search(ModernOptionsGump.SearchText)) - { - OnSearchMatch(); - ModernOptionsGump.SetParentsForMatchingSearch(this, Page); - } - else - { - _label.Alpha = Theme.NO_MATCH_SEARCH; - } - } - else - { - _label.Alpha = 1f; - } - } - - public bool Search(string text) - { - return _label.Text.ToLower().Contains(text.ToLower()); - } - - public void OnSearchMatch() - { - _label.Alpha = 1f; - } - - private class Slider : Control - { - private bool _clicked; - private int _sliderX; - private readonly TextBox _text; - private int _value = -1; - - public Slider( - int barWidth, - int min, - int max, - int value, - Action valueChanged = null - ) - { - _text = new TextBox(string.Empty, Theme.FONT, Theme.STANDARD_TEXT_SIZE, barWidth, Theme.TEXT_FONT_COLOR, strokeEffect: false); - - MinValue = min; - MaxValue = max; - BarWidth = barWidth; - AcceptMouseInput = true; - AcceptKeyboardInput = true; - Width = barWidth; - Height = Math.Max(_text.MeasuredSize.Y, 15); - - CalculateOffset(); - - Value = value; - ValueChanged = valueChanged; - } - - public int MinValue { get; set; } - - public int MaxValue { get; set; } - - public int BarWidth { get; set; } - - public float Percents { get; private set; } - - public int Value - { - get => _value; - set - { - if (_value != value) - { - int oldValue = _value; - _value = /*_newValue =*/ - value; - //if (IsInitialized) - // RecalculateSliderX(); - - if (_value < MinValue) - { - _value = MinValue; - } - else if (_value > MaxValue) - { - _value = MaxValue; - } - - if (_text != null) - { - _text.Text = Value.ToString(); - } - - if (_value != oldValue) - { - CalculateOffset(); - } - - ValueChanged?.Invoke(_value); - } - } - } - - public Action ValueChanged { get; } - - public override void Update() - { - base.Update(); - - if (_clicked) - { - int x = Mouse.Position.X - X - ParentX; - int y = Mouse.Position.Y - Y - ParentY; - - CalculateNew(x); - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(Theme.BACKGROUND); - - int mx = x; - - //Draw background line - batcher.Draw( - SolidColorTextureCache.GetTexture(Color.White), - new Rectangle(mx, y + 3, BarWidth, 10), - hueVector - ); - - hueVector = ShaderHueTranslator.GetHueVector(Theme.SEARCH_BACKGROUND); - - batcher.Draw( - SolidColorTextureCache.GetTexture(Color.White), - new Rectangle(mx + _sliderX, y, 15, 16), - hueVector - ); - - _text?.Draw(batcher, mx + BarWidth + 2, y + (Height >> 1) - (_text.Height >> 1)); - - return base.Draw(batcher, x, y); - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - if (button != MouseButtonType.Left) - { - return; - } - - _clicked = true; - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button != MouseButtonType.Left) - { - return; - } - - _clicked = false; - CalculateNew(x); - } - - protected override void OnKeyDown(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - base.OnKeyUp(key, mod); - switch (key) - { - case SDL.SDL_Keycode.SDLK_LEFT: - Value--; - break; - case SDL.SDL_Keycode.SDLK_RIGHT: - Value++; - break; - } - } - - protected override void OnMouseEnter(int x, int y) - { - base.OnMouseEnter(x, y); - UIManager.KeyboardFocusControl = this; - } - - private void CalculateNew(int x) - { - int len = BarWidth; - int maxValue = MaxValue - MinValue; - - len -= 15; - float perc = x / (float)len * 100.0f; - Value = (int)(maxValue * perc / 100.0f) + MinValue; - CalculateOffset(); - } - - private void CalculateOffset() - { - if (Value < MinValue) - { - Value = MinValue; - } - else if (Value > MaxValue) - { - Value = MaxValue; - } - - int value = Value - MinValue; - int maxValue = MaxValue - MinValue; - int length = BarWidth; - - length -= 15; - - if (maxValue > 0) - { - Percents = value / (float)maxValue * 100.0f; - } - else - { - Percents = 0; - } - - _sliderX = (int)(length * Percents / 100.0f); - - if (_sliderX < 0) - { - _sliderX = 0; - } - } - - public override void Dispose() - { - _text?.Dispose(); - base.Dispose(); - } - } - } - - private class ComboBoxWithLabel : Control, SearchableOption - { - private TextBox _label; - private Combobox _comboBox; - private readonly string[] options; - - public ComboBoxWithLabel(string label, int labelWidth, int comboWidth, string[] options, int selectedIndex, Action onOptionSelected = null) - { - AcceptMouseInput = true; - CanMove = true; - - Add(_label = new TextBox(label, Theme.FONT, Theme.STANDARD_TEXT_SIZE, labelWidth > 0 ? labelWidth : null, Theme.TEXT_FONT_COLOR, strokeEffect: false) { AcceptMouseInput = false }); - Add(_comboBox = new Combobox(comboWidth, options, selectedIndex, onOptionSelected: onOptionSelected) { X = _label.MeasuredSize.X + _label.X + 5 }); - - Width = labelWidth + comboWidth + 5; - Height = Math.Max(_label.MeasuredSize.Y, _comboBox.Height); - - ModernOptionsGump.SearchValueChanged += ModernOptionsGump_SearchValueChanged; - this.options = options; - } - - private void ModernOptionsGump_SearchValueChanged(object sender, EventArgs e) - { - if (!string.IsNullOrEmpty(ModernOptionsGump.SearchText)) - { - if (Search(ModernOptionsGump.SearchText)) - { - OnSearchMatch(); - ModernOptionsGump.SetParentsForMatchingSearch(this, Page); - } - else - { - _label.Alpha = Theme.NO_MATCH_SEARCH; - } - } - else - { - _label.Alpha = 1f; - } - } - - public bool Search(string text) - { - if (_label.Text.ToLower().Contains(text.ToLower())) - { - return true; - } - - foreach (string o in options) - { - if (o.ToLower().Contains(text.ToLower())) - { - return true; - } - } - - return false; - } - - public void OnSearchMatch() - { - _label.Alpha = 1f; - } - - public int SelectedIndex => _comboBox.SelectedIndex; - - private class Combobox : Control - { - private readonly string[] _items; - private readonly int _maxHeight; - private TextBox _label; - private int _selectedIndex; - - public Combobox - ( - int width, - string[] items, - int selected = -1, - int maxHeight = 200, - Action onOptionSelected = null - ) - { - Width = width; - Height = 25; - SelectedIndex = selected; - _items = items; - _maxHeight = maxHeight; - OnOptionSelected = onOptionSelected; - AcceptMouseInput = true; - - string initialText = selected > -1 ? items[selected] : string.Empty; - - Add(new ColorBox(Width, Height, Theme.SEARCH_BACKGROUND)); - - Add - ( - _label = new TextBox(initialText, Theme.FONT, Theme.STANDARD_TEXT_SIZE, width, Theme.TEXT_FONT_COLOR, strokeEffect: false) - { - X = 2 - } - ); - _label.Y = (Height >> 1) - (_label.Height >> 1); - } - - public int SelectedIndex - { - get => _selectedIndex; - set - { - _selectedIndex = value; - - if (_items != null) - { - _label.Text = _items[value]; - - OnOptionSelected?.Invoke(value, _items[value]); - } - } - } - - public Action OnOptionSelected { get; } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button != MouseButtonType.Left) - { - return; - } - - int comboY = ScreenCoordinateY + Offset.Y; - - if (comboY < 0) - { - comboY = 0; - } - else if (comboY + _maxHeight > Client.Game.Window.ClientBounds.Height) - { - comboY = Client.Game.Window.ClientBounds.Height - _maxHeight; - } - - UIManager.Add - ( - new ComboboxGump - ( - ScreenCoordinateX, - comboY, - Width, - _maxHeight, - _items, - this - ) - ); - - base.OnMouseUp(x, y, button); - } - - private class ComboboxGump : Gump - { - private readonly Combobox _combobox; - - public ComboboxGump - ( - int x, - int y, - int width, - int maxHeight, - string[] items, - Combobox combobox - ) : base(0, 0) - { - CanMove = false; - AcceptMouseInput = true; - X = x; - Y = y; - - IsModal = true; - LayerOrder = UILayer.Over; - ModalClickOutsideAreaClosesThisControl = true; - - _combobox = combobox; - - ColorBox cb; - Add(cb = new ColorBox(width, 0, Theme.BACKGROUND)); - - HoveredLabel[] labels = new HoveredLabel[items.Length]; - - for (int i = 0; i < items.Length; i++) - { - string item = items[i]; - - if (item == null) - { - item = string.Empty; - } - - HoveredLabel label = new HoveredLabel - ( - item, - Theme.DROPDOWN_OPTION_NORMAL_HUE, - Theme.DROPDOWN_OPTION_HOVER_HUE, - Theme.DROPDOWN_OPTION_SELECTED_HUE, - width - ) - { - X = 2, - Tag = i, - IsSelected = combobox.SelectedIndex == i ? true : false - }; - - label.Y = i * label.Height + 5; - - label.MouseUp += LabelOnMouseUp; - - labels[i] = label; - } - - int totalHeight = Math.Min(maxHeight, labels.Max(o => o.Y + o.Height)); - int maxWidth = Math.Max(width, labels.Max(o => o.X + o.Width)); - - ScrollArea area = new ScrollArea - ( - 0, - 0, - maxWidth + 15, - totalHeight - ) - { AcceptMouseInput = true }; - - foreach (HoveredLabel label in labels) - { - area.Add(label); - } - - Add(area); - - cb.Width = maxWidth; - cb.Height = totalHeight; - Width = maxWidth; - Height = totalHeight; - } - - private void LabelOnMouseUp(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtonType.Left) - { - _combobox.SelectedIndex = (int)((HoveredLabel)sender).Tag; - Dispose(); - } - } - - private class HoveredLabel : Control - { - private readonly Color _overHue, _normalHue, _selectedHue; - - private readonly TextBox _label; - - public HoveredLabel - ( - string text, - Color hue, - Color overHue, - Color selectedHue, - int maxwidth = 0 - ) - { - _overHue = overHue; - _normalHue = hue; - _selectedHue = selectedHue; - AcceptMouseInput = true; - - _label = new TextBox(text, Theme.FONT, Theme.STANDARD_TEXT_SIZE, maxwidth > 0 ? maxwidth : null, Theme.TEXT_FONT_COLOR, strokeEffect: false) { AcceptMouseInput = true }; - Height = _label.MeasuredSize.Y; - Width = Math.Max(_label.MeasuredSize.X, maxwidth); - - IsVisible = !string.IsNullOrEmpty(text); - } - - public bool DrawBackgroundCurrentIndex = true; - public bool IsSelected, ForceHover; - - public Color Hue; - - public override void Update() - { - if (IsSelected) - { - if (Hue != _selectedHue) - { - Hue = _selectedHue; - _label.Fontcolor = Hue; - } - } - else if (MouseIsOver || ForceHover) - { - if (Hue != _overHue) - { - Hue = _overHue; - _label.Fontcolor = Hue; - } - } - else if (Hue != _normalHue) - { - Hue = _normalHue; - _label.Fontcolor = Hue; - } - base.Update(); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (DrawBackgroundCurrentIndex && MouseIsOver && !string.IsNullOrWhiteSpace(_label.Text)) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - batcher.Draw - ( - SolidColorTextureCache.GetTexture(Color.Gray), - new Rectangle - ( - x, - y + 2, - Width - 4, - Height - 4 - ), - hueVector - ); - } - - _label.Draw(batcher, x, y); - - return base.Draw(batcher, x, y); - } - } - } - } - } - - private class InputFieldWithLabel : Control, SearchableOption - { - private readonly InputField _inputField; - private readonly TextBox _label; - - public InputFieldWithLabel(string label, int inputWidth, string inputText, bool numbersonly = false, EventHandler onTextChange = null) - { - AcceptMouseInput = true; - CanMove = true; - - Add(_label = new TextBox(label, Theme.FONT, Theme.STANDARD_TEXT_SIZE, null, Theme.TEXT_FONT_COLOR, strokeEffect: false) { AcceptMouseInput = false }); - - Add(_inputField = new InputField(inputWidth, 40, 0, -1, inputText, numbersonly, onTextChange) { X = _label.Width + _label.X + 5 }); - - _label.Y = (_inputField.Height >> 1) - (_label.Height >> 1); - - Width = _label.Width + _inputField.Width + 5; - Height = Math.Max(_label.Height, _inputField.Height); - - ModernOptionsGump.SearchValueChanged += ModernOptionsGump_SearchValueChanged; - } - - private void ModernOptionsGump_SearchValueChanged(object sender, EventArgs e) - { - if (!string.IsNullOrEmpty(ModernOptionsGump.SearchText)) - { - if (Search(ModernOptionsGump.SearchText)) - { - OnSearchMatch(); - ModernOptionsGump.SetParentsForMatchingSearch(this, Page); - } - else - { - _label.Alpha = Theme.NO_MATCH_SEARCH; - } - } - else - { - _label.Alpha = 1f; - } - } - - public bool Search(string text) - { - if (_label.Text.ToLower().Contains(text.ToLower())) - { - return true; - } - - return false; - } - - public void OnSearchMatch() - { - _label.Alpha = 1f; - } - } - - private class InputField : Control - { - private readonly StbTextBox _textbox; - - public event EventHandler TextChanged { add { _textbox.TextChanged += value; } remove { _textbox.TextChanged -= value; } } - - public InputField - ( - int width, - int height, - int maxWidthText = 0, - int maxCharsCount = -1, - string text = "", - bool numbersOnly = false, - EventHandler onTextChanges = null - ) - { - WantUpdateSize = false; - - Width = width; - Height = height; - - _textbox = new StbTextBox - ( - maxCharsCount, - maxWidthText - ) - { - X = 4, - Width = width - 8, - }; - _textbox.Y = (height >> 1) - (_textbox.Height >> 1); - _textbox.Text = text; - _textbox.NumbersOnly = numbersOnly; - - Add(new AlphaBlendControl() { Width = Width, Height = Height }); - Add(_textbox); - if (onTextChanges != null) - { - TextChanged += onTextChanges; - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (batcher.ClipBegin(x, y, Width, Height)) - { - base.Draw(batcher, x, y); - - batcher.ClipEnd(); - } - - return true; - } - - - public string Text => _textbox.Text; - - public override bool AcceptKeyboardInput - { - get => _textbox.AcceptKeyboardInput; - set => _textbox.AcceptKeyboardInput = value; - } - - public bool NumbersOnly - { - get => _textbox.NumbersOnly; - set => _textbox.NumbersOnly = value; - } - - - public void SetText(string text) - { - _textbox.SetText(text); - } - - - internal class StbTextBox : Control, ITextEditHandler - { - protected static readonly Color SELECTION_COLOR = new Color() { PackedValue = 0x80a06020 }; - private const int FONT_SIZE = 20; - private readonly int _maxCharCount = -1; - - - public StbTextBox - ( - int max_char_count = -1, - int maxWidth = 0 - ) - { - AcceptKeyboardInput = true; - AcceptMouseInput = true; - CanMove = false; - IsEditable = true; - - _maxCharCount = max_char_count; - - Stb = new TextEdit(this); - Stb.SingleLine = true; - - _rendererText = new TextBox(string.Empty, Theme.FONT, FONT_SIZE, maxWidth > 0 ? maxWidth : null, Theme.TEXT_FONT_COLOR, strokeEffect: false, supportsCommands: false, ignoreColorCommands: true, calculateGlyphs: true); - _rendererCaret = new TextBox("_", Theme.FONT, FONT_SIZE, null, Theme.TEXT_FONT_COLOR, strokeEffect: false, supportsCommands: false, ignoreColorCommands: true); - - Height = _rendererCaret.Height; - LoseFocusOnEscapeKey = true; - } - - protected TextEdit Stb { get; } - - public override bool AcceptKeyboardInput => base.AcceptKeyboardInput && IsEditable; - - public bool AllowTAB { get; set; } - public bool NoSelection { get; set; } - - public bool LoseFocusOnEscapeKey { get; set; } - - public int CaretIndex - { - get => Stb.CursorIndex; - set - { - Stb.CursorIndex = value; - UpdateCaretScreenPosition(); - } - } - - public bool Multiline - { - get => !Stb.SingleLine; - set => Stb.SingleLine = !value; - } - - public bool NumbersOnly { get; set; } - - public int SelectionStart - { - get => Stb.SelectStart; - set - { - if (AllowSelection) - { - Stb.SelectStart = value; - } - } - } - - public int SelectionEnd - { - get => Stb.SelectEnd; - set - { - if (AllowSelection) - { - Stb.SelectEnd = value; - } - } - } - - public bool AllowSelection { get; set; } = true; - - internal int TotalHeight - { - get - { - return _rendererText.Height; - } - } - - public string Text - { - get => _rendererText.Text; - - set - { - if (_maxCharCount > 0) - { - if (value != null && value.Length > _maxCharCount) - { - value = value.Substring(0, _maxCharCount); - } - } - - _rendererText.Text = value; - - if (!_is_writing) - { - OnTextChanged(); - } - } - } - - public int Length => Text?.Length ?? 0; - - public float GetWidth(int index) - { - if (Text != null) - { - if (index < _rendererText.Text.Length) - { - var glyphRender = _rendererText.RTL.GetGlyphInfoByIndex(index); - if (glyphRender != null) - { - return glyphRender.Value.Bounds.Width; - } - } - } - return 0; - } - - public TextEditRow LayoutRow(int startIndex) - { - TextEditRow r = new TextEditRow() { num_chars = _rendererText.Text.Length }; - - int sx = ScreenCoordinateX; - int sy = ScreenCoordinateY; - - r.x0 += sx; - r.x1 += sx; - r.ymin += sy; - r.ymax += sy; - - return r; - } - - protected Point _caretScreenPosition; - protected bool _is_writing; - protected bool _leftWasDown, _fromServer; - protected TextBox _rendererText, _rendererCaret; - - public event EventHandler TextChanged; - - public void SelectAll() - { - if (AllowSelection) - { - Stb.SelectStart = 0; - Stb.SelectEnd = Length; - } - } - - protected void UpdateCaretScreenPosition() - { - _caretScreenPosition = GetCoordsForIndex(Stb.CursorIndex); - } - - protected Point GetCoordsForIndex(int index) - { - int x = 0, y = 0; - - if (Text != null) - { - if (index < Text.Length) - { - var glyphRender = _rendererText.RTL.GetGlyphInfoByIndex(index); - if (glyphRender != null) - { - x += glyphRender.Value.Bounds.Left; - y += glyphRender.Value.LineTop; - } - } - else if (_rendererText.RTL.Lines != null && _rendererText.RTL.Lines.Count > 0) - { - // After last glyph - var lastLine = _rendererText.RTL.Lines[_rendererText.RTL.Lines.Count - 1]; - if (lastLine.Count > 0) - { - var glyphRender = lastLine.GetGlyphInfoByIndex(lastLine.Count - 1); - - x += glyphRender.Value.Bounds.Right; - y += glyphRender.Value.LineTop; - } - else if (_rendererText.RTL.Lines.Count > 1) - { - var previousLine = _rendererText.RTL.Lines[_rendererText.RTL.Lines.Count - 2]; - if (previousLine.Count > 0) - { - var glyphRender = previousLine.GetGlyphInfoByIndex(0); - y += glyphRender.Value.LineTop + lastLine.Size.Y + _rendererText.RTL.VerticalSpacing; - } - } - } - } - - return new Point(x, y); - } - - protected int GetIndexFromCoords(Point coords) - { - if (Text != null) - { - var line = _rendererText.RTL.GetLineByY(coords.Y); - if (line != null) - { - int? index = line.GetGlyphIndexByX(coords.X); - if (index != null) - { - return (int)index; - } - } - } - return 0; - } - - protected Point GetCoordsForClick(Point clicked) - { - if (Text != null) - { - var line = _rendererText.RTL.GetLineByY(clicked.Y); - if (line != null) - { - int? index = line.GetGlyphIndexByX(clicked.X); - if (index != null) - { - return GetCoordsForIndex((int)index); - } - } - } - return Point.Zero; - } - - private ControlKeys ApplyShiftIfNecessary(ControlKeys k) - { - if (Keyboard.Shift && !NoSelection) - { - k |= ControlKeys.Shift; - } - - return k; - } - - private bool IsMaxCharReached(int count) - { - return _maxCharCount >= 0 && Length + count >= _maxCharCount; - } - - protected virtual void OnTextChanged() - { - TextChanged?.Raise(this); - - UpdateCaretScreenPosition(); - } - - internal override void OnFocusEnter() - { - base.OnFocusEnter(); - CaretIndex = Text?.Length ?? 0; - } - - internal override void OnFocusLost() - { - if (Stb != null) - { - Stb.SelectStart = Stb.SelectEnd = 0; - } - - base.OnFocusLost(); - } - - protected override void OnKeyDown(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - ControlKeys? stb_key = null; - bool update_caret = false; - - switch (key) - { - case SDL.SDL_Keycode.SDLK_TAB: - if (AllowTAB) - { - // UO does not support '\t' char in its fonts - OnTextInput(" "); - } - else - { - Parent?.KeyboardTabToNextFocus(this); - } - - break; - - case SDL.SDL_Keycode.SDLK_a when Keyboard.Ctrl && !NoSelection: - SelectAll(); - - break; - - case SDL.SDL_Keycode.SDLK_ESCAPE: - if (LoseFocusOnEscapeKey && SelectionStart == SelectionEnd) - { - UIManager.KeyboardFocusControl = null; - } - SelectionStart = 0; - SelectionEnd = 0; - break; - - case SDL.SDL_Keycode.SDLK_INSERT when IsEditable: - stb_key = ControlKeys.InsertMode; - - break; - - case SDL.SDL_Keycode.SDLK_c when Keyboard.Ctrl && !NoSelection: - int selectStart = Math.Min(Stb.SelectStart, Stb.SelectEnd); - int selectEnd = Math.Max(Stb.SelectStart, Stb.SelectEnd); - - if (selectStart < selectEnd && selectStart >= 0 && selectEnd - selectStart <= Text.Length) - { - SDL.SDL_SetClipboardText(Text.Substring(selectStart, selectEnd - selectStart)); - } - - break; - - case SDL.SDL_Keycode.SDLK_x when Keyboard.Ctrl && !NoSelection: - selectStart = Math.Min(Stb.SelectStart, Stb.SelectEnd); - selectEnd = Math.Max(Stb.SelectStart, Stb.SelectEnd); - - if (selectStart < selectEnd && selectStart >= 0 && selectEnd - selectStart <= Text.Length) - { - SDL.SDL_SetClipboardText(Text.Substring(selectStart, selectEnd - selectStart)); - - if (IsEditable) - { - Stb.Cut(); - } - } - - break; - - case SDL.SDL_Keycode.SDLK_v when Keyboard.Ctrl && IsEditable: - OnTextInput(StringHelper.GetClipboardText(Multiline)); - - break; - - case SDL.SDL_Keycode.SDLK_z when Keyboard.Ctrl && IsEditable: - stb_key = ControlKeys.Undo; - - break; - - case SDL.SDL_Keycode.SDLK_y when Keyboard.Ctrl && IsEditable: - stb_key = ControlKeys.Redo; - - break; - - case SDL.SDL_Keycode.SDLK_LEFT: - if (Keyboard.Ctrl && Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.WordLeft; - } - } - else if (Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.Left; - } - } - else if (Keyboard.Ctrl) - { - stb_key = ControlKeys.WordLeft; - } - else - { - stb_key = ControlKeys.Left; - } - - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_RIGHT: - if (Keyboard.Ctrl && Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.WordRight; - } - } - else if (Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.Right; - } - } - else if (Keyboard.Ctrl) - { - stb_key = ControlKeys.WordRight; - } - else - { - stb_key = ControlKeys.Right; - } - - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_UP: - stb_key = ApplyShiftIfNecessary(ControlKeys.Up); - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_DOWN: - stb_key = ApplyShiftIfNecessary(ControlKeys.Down); - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_BACKSPACE when IsEditable: - stb_key = ApplyShiftIfNecessary(ControlKeys.BackSpace); - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_DELETE when IsEditable: - stb_key = ApplyShiftIfNecessary(ControlKeys.Delete); - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_HOME: - if (Keyboard.Ctrl && Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.TextStart; - } - } - else if (Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.LineStart; - } - } - else if (Keyboard.Ctrl) - { - stb_key = ControlKeys.TextStart; - } - else - { - stb_key = ControlKeys.LineStart; - } - - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_END: - if (Keyboard.Ctrl && Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.TextEnd; - } - } - else if (Keyboard.Shift) - { - if (!NoSelection) - { - stb_key = ControlKeys.Shift | ControlKeys.LineEnd; - } - } - else if (Keyboard.Ctrl) - { - stb_key = ControlKeys.TextEnd; - } - else - { - stb_key = ControlKeys.LineEnd; - } - - update_caret = true; - - break; - - case SDL.SDL_Keycode.SDLK_KP_ENTER: - case SDL.SDL_Keycode.SDLK_RETURN: - if (IsEditable) - { - if (Multiline) - { - if (!_fromServer && !IsMaxCharReached(0)) - { - OnTextInput("\n"); - } - } - else - { - Parent?.OnKeyboardReturn(0, Text); - - if (UIManager.SystemChat != null && UIManager.SystemChat.TextBoxControl != null && IsFocused) - { - if (!IsFromServer || !UIManager.SystemChat.TextBoxControl.IsVisible) - { - OnFocusLost(); - OnFocusEnter(); - } - else if (UIManager.KeyboardFocusControl == null || UIManager.KeyboardFocusControl != UIManager.SystemChat.TextBoxControl) - { - UIManager.SystemChat.TextBoxControl.SetKeyboardFocus(); - } - } - } - } - - break; - } - - if (stb_key != null) - { - Stb.Key(stb_key.Value); - } - - if (update_caret) - { - UpdateCaretScreenPosition(); - } - - base.OnKeyDown(key, mod); - } - - public void SetText(string text) - { - if (string.IsNullOrEmpty(text)) - { - ClearText(); - } - else - { - if (_maxCharCount > 0) - { - if (text.Length > _maxCharCount) - { - text = text.Substring(0, _maxCharCount); - } - } - - Stb.ClearState(!Multiline); - Text = text; - - Stb.CursorIndex = Length; - - if (!_is_writing) - { - OnTextChanged(); - } - } - } - - public void ClearText() - { - if (Length != 0) - { - SelectionStart = 0; - SelectionEnd = 0; - Stb.Delete(0, Length); - - if (!_is_writing) - { - OnTextChanged(); - } - } - } - - public void AppendText(string text) - { - Stb.Paste(text); - } - - protected override void OnTextInput(string c) - { - if (c == null || !IsEditable) - { - return; - } - - _is_writing = true; - - if (SelectionStart != SelectionEnd) - { - Stb.DeleteSelection(); - } - - int count; - - if (_maxCharCount > 0) - { - int remains = _maxCharCount - Length; - - if (remains <= 0) - { - _is_writing = false; - - return; - } - - count = Math.Min(remains, c.Length); - - if (remains < c.Length && count > 0) - { - c = c.Substring(0, count); - } - } - else - { - count = c.Length; - } - - if (count > 0) - { - if (NumbersOnly) - { - for (int i = 0; i < count; i++) - { - if (!char.IsNumber(c[i])) - { - _is_writing = false; - - return; - } - } - - if (_maxCharCount > 0 && int.TryParse(Stb.text + c, out int val)) - { - if (val > _maxCharCount) - { - _is_writing = false; - SetText(_maxCharCount.ToString()); - - return; - } - } - } - - - if (count > 1) - { - Stb.Paste(c); - OnTextChanged(); - } - else - { - Stb.InputChar(c[0]); - OnTextChanged(); - } - } - - _is_writing = false; - } - - private int GetXOffset() - { - if (_caretScreenPosition.X > Width) - { - return _caretScreenPosition.X - Width + 5; - } - - return 0; - } - - public void Click(Point pos) - { - pos = new Point((pos.X - ScreenCoordinateX), pos.Y - ScreenCoordinateY); - CaretIndex = GetIndexFromCoords(pos); - SelectionStart = 0; - SelectionEnd = 0; - Stb.HasPreferredX = false; - } - - public void Drag(Point pos) - { - pos = new Point((pos.X - ScreenCoordinateX), pos.Y - ScreenCoordinateY); - int p = 0; - - if (SelectionStart == SelectionEnd) - { - SelectionStart = CaretIndex; - } - - CaretIndex = SelectionEnd = GetIndexFromCoords(pos); - } - - private protected void DrawSelection(UltimaBatcher2D batcher, int x, int y) - { - if (!AllowSelection) - { - return; - } - - int selectStart = Math.Min(SelectionStart, SelectionEnd); - int selectEnd = Math.Max(SelectionStart, SelectionEnd); - - if (selectStart < selectEnd) - { //Show selection - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0, false, 0.5f); - - Point start = GetCoordsForIndex(selectStart); - Point size = GetCoordsForIndex(selectEnd); - size = new Point(size.X - start.X, _rendererText.Height); - - batcher.Draw - ( - SolidColorTextureCache.GetTexture(SELECTION_COLOR), - new Rectangle - ( - x + start.X, - y + start.Y, - size.X, - size.Y - ), - hueVector - ); - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - int slideX = x - GetXOffset(); - - if (batcher.ClipBegin(x, y, Width, Height)) - { - base.Draw(batcher, x, y); - DrawSelection(batcher, slideX, y); - _rendererText.Draw(batcher, slideX, y); - DrawCaret(batcher, slideX, y); - batcher.ClipEnd(); - } - - return true; - } - - protected virtual void DrawCaret(UltimaBatcher2D batcher, int x, int y) - { - if (HasKeyboardFocus) - { - _rendererCaret.Draw(batcher, x + _caretScreenPosition.X, y + _caretScreenPosition.Y); - } - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left && IsEditable) - { - if (!NoSelection) - { - _leftWasDown = true; - } - - Click(new Point(x + ScreenCoordinateX + GetXOffset(), y + ScreenCoordinateY)); - } - - base.OnMouseDown(x, y, button); - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - _leftWasDown = false; - } - - base.OnMouseUp(x, y, button); - } - - protected override void OnMouseOver(int x, int y) - { - base.OnMouseOver(x, y); - - if (!_leftWasDown) - { - return; - } - - Drag(new Point(x + ScreenCoordinateX + GetXOffset(), y + ScreenCoordinateY)); - } - - public override void Dispose() - { - _rendererText?.Dispose(); - _rendererCaret?.Dispose(); - - base.Dispose(); - } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if (!NoSelection && CaretIndex < Text.Length && CaretIndex >= 0 && !char.IsWhiteSpace(Text[CaretIndex])) - { - int idx = CaretIndex; - - if (idx - 1 >= 0 && char.IsWhiteSpace(Text[idx - 1])) - { - ++idx; - } - - SelectionStart = Stb.MoveToPreviousWord(idx); - SelectionEnd = Stb.MoveToNextWord(idx); - - if (SelectionEnd < Text.Length) - { - --SelectionEnd; - } - - return true; - } - - return base.OnMouseDoubleClick(x, y, button); - } - } - } - - private class InfoBarBuilderControl : Control - { - private readonly InputField infoLabel; - private readonly ModernColorPickerWithLabel labelColor; - private readonly ComboBoxWithLabel varStat; - - public InfoBarBuilderControl(InfoBarItem item) - { - AcceptMouseInput = true; - infoLabel = new InputField(130, 40, text: item.label, onTextChanges: (s, e) => { item.label = ((InputField.StbTextBox)s).Text; UIManager.GetGump()?.ResetItems(); }) { X = 5 }; - - string[] dataVars = InfoBarManager.GetVars(); - - varStat = new ComboBoxWithLabel(string.Empty, 0, 170, dataVars, (int)item.var, onOptionSelected: (i, s) => { item.var = (InfoBarVars)i; UIManager.GetGump()?.ResetItems(); }) { X = 200, Y = 8 }; - - labelColor = new ModernColorPickerWithLabel(string.Empty, item.hue, (h) => { item.hue = h; UIManager.GetGump()?.ResetItems(); }) { X = 150, Y = 10 }; - - - ModernButton deleteButton = new ModernButton - ( - 390, - 8, - 60, - 25, - ButtonAction.Activate, - "Delete", - Theme.BUTTON_FONT_COLOR - ) - { ButtonParameter = 999 }; - - deleteButton.MouseUp += (sender, e) => - { - Dispose(); - if (Parent != null && Parent is DataBox db) - { - db.Remove(this); - db.ReArrangeChildren(); - db.ForceSizeUpdate(); - } - Client.Game.GetScene().InfoBars?.RemoveItem(item); - UIManager.GetGump()?.ResetItems(); - }; - - Add(infoLabel); - Add(varStat); - Add(labelColor); - Add(deleteButton); - - ForceSizeUpdate(); - } - - public override void Update() - { - if (IsDisposed) - { - return; - } - - if (Children.Count != 0) - { - int w = 0, h = 0; - - for (int i = 0; i < Children.Count; i++) - { - Control c = Children[i]; - - if (c.IsDisposed) - { - OnChildRemoved(); - Children.RemoveAt(i--); - - continue; - } - - c.Update(); - - - } - - } - - } - - public string LabelText => infoLabel.Text; - public InfoBarVars Var => (InfoBarVars)varStat.SelectedIndex; - public ushort Hue => labelColor.Hue; - } - - private class LeftSideMenuRightSideContent : Control - { - private ScrollArea left, right; - private int leftY, rightY = Theme.TOP_PADDING, leftX, rightX; - - public ScrollArea LeftArea => left; - public ScrollArea RightArea => right; - - public new int ActivePage - { - get => base.ActivePage; - set - { - base.ActivePage = value; - right.ActivePage = value; - } - } - - public LeftSideMenuRightSideContent(int width, int height, int leftWidth, int page = 0) - { - Width = width; - Height = height; - CanMove = true; - CanCloseWithRightClick = true; - AcceptMouseInput = true; - - Add(new AlphaBlendControl() { Width = leftWidth, Height = Height, CanMove = true }, page); - Add(left = new ScrollArea(0, 0, leftWidth, height) { CanMove = true, AcceptMouseInput = true }, page); - Add(right = new ScrollArea(leftWidth, 0, Width - leftWidth, height) { CanMove = true, AcceptMouseInput = true }, page); - - LeftWidth = leftWidth - Theme.SCROLL_BAR_WIDTH; - RightWidth = Width - leftWidth; - } - - public int LeftWidth { get; } - public int RightWidth { get; } - - public void AddToLeft(Control c, bool autoPosition = true, int page = 0) - { - if (autoPosition) - { - c.Y = leftY; - c.X = leftX; - leftY += c.Height; - } - - left.Add(c, page); - } - - public void AddToRight(Control c, bool autoPosition = true, int page = 0) - { - if (autoPosition) - { - c.Y = rightY; - c.X = rightX; - rightY += c.Height + Theme.TOP_PADDING; - } - - right.Add(c, page); - } - - public void BlankLine() - { - rightY += Theme.BLANK_LINE; - } - - public void Indent() - { - rightX += Theme.INDENT_SPACE; - } - - public void RemoveIndent() - { - rightX -= Theme.INDENT_SPACE; - if (rightX < 0) - { - rightX = 0; - } - } - - public void ResetRightSide() - { - rightY = Theme.TOP_PADDING; - rightX = 0; - } - - public void SetMatchingButton(int page) - { - foreach (Control c in left.Children) - { - if (c is ModernButton button && button.ButtonParameter == page) - { - ((SearchableOption)button).OnSearchMatch(); - int p = Parent == null ? Page : Parent.Page; - ModernOptionsGump.SetParentsForMatchingSearch(this, p); - } - } - } - } - - private class ModernButton : HitBox, SearchableOption - { - private readonly ButtonAction _action; - private readonly int _groupnumber; - private bool _isSelected; - - public bool DisplayBorder; - - public bool FullPageSwitch; - - public ModernButton - ( - int x, - int y, - int w, - int h, - ButtonAction action, - string text, - Color fontColor, - int groupnumber = 0, - FontStashSharp.RichText.TextHorizontalAlignment align = FontStashSharp.RichText.TextHorizontalAlignment.Center - ) : base(x, y, w, h) - { - _action = action; - - Add - ( - TextLabel = new TextBox(text, Theme.FONT, 20, w, fontColor, align, false) - ); - - TextLabel.Y = (h - TextLabel.Height) >> 1; - _groupnumber = groupnumber; - - ModernOptionsGump.SearchValueChanged += ModernOptionsGump_SearchValueChanged; - } - - private void ModernOptionsGump_SearchValueChanged(object sender, EventArgs e) - { - if (!string.IsNullOrEmpty(ModernOptionsGump.SearchText)) - { - if (Search(SearchText)) - { - OnSearchMatch(); - ModernOptionsGump.SetParentsForMatchingSearch(this, Page); - } - else - { - TextLabel.Alpha = Theme.NO_MATCH_SEARCH; - } - } - else - { - TextLabel.Alpha = 1f; - } - } - - internal TextBox TextLabel { get; } - - public int ButtonParameter { get; set; } - - public bool IsSelectable { get; set; } = true; - - public bool IsSelected - { - get => _isSelected && IsSelectable; - set - { - if (!IsSelectable) - { - return; - } - - _isSelected = value; - - if (value) - { - Control p = Parent; - - if (p == null) - { - return; - } - - IEnumerable list = p.FindControls(); - - foreach (ModernButton b in list) - { - if (b != this && b._groupnumber == _groupnumber) - { - b.IsSelected = false; - } - } - } - } - } - - internal static ModernButton GetSelected(Control p, int group) - { - IEnumerable list = p.FindControls(); - - foreach (ModernButton b in list) - { - if (b._groupnumber == group && b.IsSelected) - { - return b; - } - } - - return null; - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - IsSelected = true; - - if (_action == ButtonAction.SwitchPage) - { - if (!FullPageSwitch) - { - if (Parent != null) - { //Scroll area - Parent.ActivePage = ButtonParameter; - if (Parent.Parent != null && Parent.Parent is LeftSideMenuRightSideContent) - { //LeftSideMenuRightSideContent - ((LeftSideMenuRightSideContent)Parent.Parent).ActivePage = ButtonParameter; - } - } - } - else - { - ChangePage(ButtonParameter); - } - } - else - { - OnButtonClick(ButtonParameter); - } - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsSelected) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0, false, Alpha); - - batcher.Draw - ( - _texture, - new Vector2(x, y), - new Rectangle(0, 0, Width, Height), - hueVector - ); - } - - if (DisplayBorder) - { - batcher.DrawRectangle( - SolidColorTextureCache.GetTexture(Color.LightGray), - x, y, - Width, Height, - ShaderHueTranslator.GetHueVector(0, false, Alpha) - ); - } - - return base.Draw(batcher, x, y); - } - - public bool Search(string text) - { - return TextLabel.Text.ToLower().Contains(text.ToLower()); - } - - public void OnSearchMatch() - { - TextLabel.Alpha = 1f; - } - } - - private class ScrollArea : Control - { - private readonly ScrollBar _scrollBar; - - public ScrollArea - ( - int x, - int y, - int w, - int h, - int scroll_max_height = -1 - ) - { - X = x; - Y = y; - Width = w; - Height = h; - - _scrollBar = new ScrollBar(Width - Theme.SCROLL_BAR_WIDTH, 0, Height); - - ScrollMaxHeight = scroll_max_height; - - _scrollBar.MinValue = 0; - _scrollBar.MaxValue = scroll_max_height >= 0 ? scroll_max_height : Height; - _scrollBar.Parent = this; - _scrollBar.IsVisible = true; - - AcceptMouseInput = true; - WantUpdateSize = false; - CanMove = true; - } - - public int ScrollMaxHeight { get; set; } = -1; - public int ScrollValue => _scrollBar.Value; - public int ScrollMinValue => _scrollBar.MinValue; - public int ScrollMaxValue => _scrollBar.MaxValue; - - public Rectangle ScissorRectangle; - - public override void Update() - { - base.Update(); - - CalculateScrollBarMaxValue(); - } - - public void Scroll(bool isup) - { - if (isup) - { - _scrollBar.Value -= _scrollBar.ScrollStep; - } - else - { - _scrollBar.Value += _scrollBar.ScrollStep; - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - _scrollBar.Draw(batcher, x + _scrollBar.X, y + _scrollBar.Y); - - if (batcher.ClipBegin(x + ScissorRectangle.X, y + ScissorRectangle.Y, Width - _scrollBar.Width + ScissorRectangle.Width, Height + ScissorRectangle.Height)) - { - for (int i = 1; i < Children.Count; i++) - { - Control child = Children[i]; - - if (!child.IsVisible || (child.Page != ActivePage && child.Page != 0)) - { - continue; - } - - int finalY = y + child.Y - _scrollBar.Value + ScissorRectangle.Y; - - child.Draw(batcher, x + child.X, finalY); - } - - batcher.ClipEnd(); - } - - return true; - } - - protected override void OnMouseEnter(int x, int y) - { - base.OnMouseEnter(x, y); - if (UIManager.KeyboardFocusControl == UIManager.SystemChat.TextBoxControl || UIManager.KeyboardFocusControl == null) - { - UIManager.KeyboardFocusControl = this; //Dirty fix for mouse wheel macros - } - } - - protected override void OnMouseWheel(MouseEventType delta) - { - switch (delta) - { - case MouseEventType.WheelScrollUp: - _scrollBar.Value -= _scrollBar.ScrollStep; - - break; - - case MouseEventType.WheelScrollDown: - _scrollBar.Value += _scrollBar.ScrollStep; - - break; - } - } - - public override void Clear() - { - for (int i = 1; i < Children.Count; i++) - { - Children[i].Dispose(); - } - } - - private void CalculateScrollBarMaxValue() - { - _scrollBar.Height = ScrollMaxHeight >= 0 ? ScrollMaxHeight : Height; - bool maxValue = _scrollBar.Value == _scrollBar.MaxValue && _scrollBar.MaxValue != 0; - - int startY = 0, endY = 0; - - for (int i = 1; i < Children.Count; i++) - { - Control c = Children[i]; - - if (c.IsVisible && !c.IsDisposed && (c.Page == 0 || c.Page == ActivePage)) - { - if (c.Y < startY) - { - startY = c.Y; - } - - if (c.Bounds.Bottom > endY) - { - endY = c.Bounds.Bottom; - } - } - } - - int height = Math.Abs(startY) + Math.Abs(endY) - _scrollBar.Height; - height = Math.Max(0, height - (-ScissorRectangle.Y + ScissorRectangle.Height)); - - if (height > 0) - { - _scrollBar.MaxValue = height; - - if (maxValue) - { - _scrollBar.Value = _scrollBar.MaxValue; - } - } - else - { - _scrollBar.Value = _scrollBar.MaxValue = 0; - } - - _scrollBar.UpdateOffset(0, Offset.Y); - - for (int i = 1; i < Children.Count; i++) - { - Children[i].UpdateOffset(0, -_scrollBar.Value + ScissorRectangle.Y); - } - } - - private class ScrollBar : ScrollBarBase - { - private Rectangle _rectSlider, - _emptySpace; - - private Vector3 hueVector = ShaderHueTranslator.GetHueVector(Theme.BACKGROUND, false, 0.75f); - private Vector3 hueVectorForeground = ShaderHueTranslator.GetHueVector(Theme.BLACK, false, 0.75f); - private Texture2D whiteTexture = SolidColorTextureCache.GetTexture(Color.White); - - public ScrollBar(int x, int y, int height) - { - Height = height; - Location = new Point(x, y); - AcceptMouseInput = true; - - Width = Theme.SCROLL_BAR_WIDTH; - - _rectSlider = new Rectangle( - 0, - _sliderPosition, - Width, - 20 - ); - - _emptySpace.X = 0; - _emptySpace.Y = 0; - _emptySpace.Width = Width; - _emptySpace.Height = Height; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (Height <= 0 || !IsVisible) - { - return false; - } - - // draw scrollbar background - batcher.Draw( - whiteTexture, - new Rectangle(x, y, Width, Height), - hueVector - ); - - - // draw slider - if (MaxValue > MinValue) - { - batcher.Draw( - whiteTexture, - new Rectangle(x, y + _sliderPosition, Width, 20), - hueVectorForeground - ); - } - - return base.Draw(batcher, x, y); - } - - protected override int GetScrollableArea() - { - return Height - _rectSlider.Height; - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - base.OnMouseDown(x, y, button); - - if (_btnSliderClicked && _emptySpace.Contains(x, y)) - { - CalculateByPosition(x, y); - } - } - - protected override void CalculateByPosition(int x, int y) - { - if (y != _clickPosition.Y) - { - y -= _emptySpace.Y + (_rectSlider.Height >> 1); - - if (y < 0) - { - y = 0; - } - - int scrollableArea = GetScrollableArea(); - - if (y > scrollableArea) - { - y = scrollableArea; - } - - _sliderPosition = y; - _clickPosition.X = x; - _clickPosition.Y = y; - - if ( - y == 0 - && _clickPosition.Y < (_rectSlider.Height >> 1) - ) - { - _clickPosition.Y = _rectSlider.Height >> 1; - } - else if ( - y == scrollableArea - && _clickPosition.Y - > Height - (_rectSlider.Height >> 1) - ) - { - _clickPosition.Y = - Height - (_rectSlider.Height >> 1); - } - - _value = (int) - Math.Round(y / (float)scrollableArea * (MaxValue - MinValue) + MinValue); - } - } - - public override bool Contains(int x, int y) - { - return x >= 0 && x <= Width && y >= 0 && y <= Height; - } - } - } - - private class MacroControl : Control - { - private static readonly string[] _allHotkeysNames = Enum.GetNames(typeof(MacroType)); - private static readonly string[] _allSubHotkeysNames = Enum.GetNames(typeof(MacroSubType)); - private readonly DataBox _databox; - private readonly HotkeyBox _hotkeyBox; - - private enum buttonsOption - { - AddBtn, - RemoveBtn, - CreateNewMacro, - OpenMacroOptions, - OpenButtonEditor - } - - public MacroControl(string name) - { - CanMove = true; - TextBox _keyBinding; - Add(_keyBinding = new TextBox("Hotkey", Theme.FONT, Theme.STANDARD_TEXT_SIZE, null, Theme.TEXT_FONT_COLOR, strokeEffect: false)); - - _hotkeyBox = new HotkeyBox(); - _hotkeyBox.HotkeyChanged += BoxOnHotkeyChanged; - _hotkeyBox.HotkeyCancelled += BoxOnHotkeyCancelled; - _hotkeyBox.X = _keyBinding.X + _keyBinding.Width + 5; - - - Add(_hotkeyBox); - - Control c; - Add(c = new ModernButton(0, _hotkeyBox.Height + 3, 200, 40, ButtonAction.Activate, ResGumps.CreateMacroButton, Theme.BUTTON_FONT_COLOR) { ButtonParameter = (int)buttonsOption.CreateNewMacro, IsSelectable = true, IsSelected = true }); - Add(c = new ModernButton(c.Width + c.X + 10, c.Y, 200, 40, ButtonAction.Activate, ResGumps.MacroButtonEditor, Theme.BUTTON_FONT_COLOR) { ButtonParameter = (int)buttonsOption.OpenButtonEditor, IsSelectable = true, IsSelected = true }); - - Add(c = new Line(0, c.Y + c.Height + 5, 325, 1, Color.Gray.PackedValue)); - - Add(c = new ModernButton(0, c.Y + 5, 75, 40, ButtonAction.Activate, ResGumps.Add, Theme.BUTTON_FONT_COLOR) { ButtonParameter = (int)buttonsOption.AddBtn, IsSelectable = false }); - - Add(_databox = new DataBox(0, c.Y + c.Height + 5, 280, 280)); - - Macro = Client.Game.GetScene().Macros.FindMacro(name) ?? Macro.CreateEmptyMacro(name); - - SetupKeyByDefault(); - SetupMacroUI(); - } - - public Macro Macro { get; } - - private void AddEmptyMacro() - { - MacroObject ob = (MacroObject)Macro.Items; - - if (ob == null || ob.Code == MacroType.None) - { - return; - } - - while (ob.Next != null) - { - MacroObject next = (MacroObject)ob.Next; - - if (next.Code == MacroType.None) - { - return; - } - - ob = next; - } - - MacroObject obj = Macro.Create(MacroType.None); - - Macro.PushToBack(obj); - - _databox.Add(new MacroEntry(this, obj, _allHotkeysNames)); - _databox.ReArrangeChildren(); - _databox.ForceSizeUpdate(); - ForceSizeUpdate(); - } - - private void RemoveLastCommand() - { - if (_databox.Children.Count != 0) - { - LinkedObject last = Macro.GetLast(); - - Macro.Remove(last); - - _databox.Children[_databox.Children.Count - 1].Dispose(); - - SetupMacroUI(); - } - - if (_databox.Children.Count == 0) - { - AddEmptyMacro(); - } - } - - private void SetupMacroUI() - { - if (Macro == null) - { - return; - } - - _databox.Clear(); - _databox.Children.Clear(); - - if (Macro.Items == null) - { - Macro.Items = Macro.Create(MacroType.None); - } - - MacroObject obj = (MacroObject)Macro.Items; - while (obj != null) - { - _databox.Add(new MacroEntry(this, obj, _allHotkeysNames)); - - if (obj.Next != null && obj.Code == MacroType.None) - { - break; - } - obj = (MacroObject)obj.Next; - } - - _databox.ReArrangeChildren(); - _databox.ForceSizeUpdate(); - } - - private void SetupKeyByDefault() - { - if (Macro == null || _hotkeyBox == null) - { - return; - } - - if (Macro.ControllerButtons != null && Macro.ControllerButtons.Length > 0) - { - _hotkeyBox.SetButtons(Macro.ControllerButtons); - } - - SDL.SDL_Keymod mod = SDL.SDL_Keymod.KMOD_NONE; - - if (Macro.Alt) - { - mod |= SDL.SDL_Keymod.KMOD_ALT; - } - - if (Macro.Shift) - { - mod |= SDL.SDL_Keymod.KMOD_SHIFT; - } - - if (Macro.Ctrl) - { - mod |= SDL.SDL_Keymod.KMOD_CTRL; - } - - if (Macro.Key != SDL.SDL_Keycode.SDLK_UNKNOWN) - { - _hotkeyBox.SetKey(Macro.Key, mod); - } - else if (Macro.MouseButton != MouseButtonType.None) - { - _hotkeyBox.SetMouseButton(Macro.MouseButton, mod); - } - else if (Macro.WheelScroll == true) - { - _hotkeyBox.SetMouseWheel(Macro.WheelUp, mod); - } - } - - private void BoxOnHotkeyChanged(object sender, EventArgs e) - { - bool shift = (_hotkeyBox.Mod & SDL.SDL_Keymod.KMOD_SHIFT) != SDL.SDL_Keymod.KMOD_NONE; - bool alt = (_hotkeyBox.Mod & SDL.SDL_Keymod.KMOD_ALT) != SDL.SDL_Keymod.KMOD_NONE; - bool ctrl = (_hotkeyBox.Mod & SDL.SDL_Keymod.KMOD_CTRL) != SDL.SDL_Keymod.KMOD_NONE; - - if (_hotkeyBox.Key != SDL.SDL_Keycode.SDLK_UNKNOWN) - { - Macro macro = Client.Game.GetScene().Macros.FindMacro(_hotkeyBox.Key, alt, ctrl, shift); - - if (macro != null) - { - if (Macro == macro) - { - return; - } - - SetupKeyByDefault(); - UIManager.Add(new MessageBoxGump(250, 150, string.Format(ResGumps.ThisKeyCombinationAlreadyExists, macro.Name), null)); - - return; - } - } - else if (_hotkeyBox.MouseButton != MouseButtonType.None) - { - Macro macro = Client.Game.GetScene().Macros.FindMacro(_hotkeyBox.MouseButton, alt, ctrl, shift); - - if (macro != null) - { - if (Macro == macro) - { - return; - } - - SetupKeyByDefault(); - UIManager.Add(new MessageBoxGump(250, 150, string.Format(ResGumps.ThisKeyCombinationAlreadyExists, macro.Name), null)); - - return; - } - } - else if (_hotkeyBox.WheelScroll == true) - { - Macro macro = Client.Game.GetScene().Macros.FindMacro(_hotkeyBox.WheelUp, alt, ctrl, shift); - - if (macro != null) - { - if (Macro == macro) - { - return; - } - - SetupKeyByDefault(); - UIManager.Add(new MessageBoxGump(250, 150, string.Format(ResGumps.ThisKeyCombinationAlreadyExists, macro.Name), null)); - - return; - } - } - else if (_hotkeyBox.Buttons != null && _hotkeyBox.Buttons.Length > 0) - { - - } - else - { - return; - } - - Macro m = Macro; - if (_hotkeyBox.Buttons != null && _hotkeyBox.Buttons.Length > 0) - { - m.ControllerButtons = _hotkeyBox.Buttons; - } - m.Key = _hotkeyBox.Key; - m.MouseButton = _hotkeyBox.MouseButton; - m.WheelScroll = _hotkeyBox.WheelScroll; - m.WheelUp = _hotkeyBox.WheelUp; - m.Shift = shift; - m.Alt = alt; - m.Ctrl = ctrl; - } - - private void BoxOnHotkeyCancelled(object sender, EventArgs e) - { - Macro m = Macro; - m.Alt = m.Ctrl = m.Shift = false; - m.Key = SDL.SDL_Keycode.SDLK_UNKNOWN; - m.MouseButton = MouseButtonType.None; - m.WheelScroll = false; - } - - public override void OnButtonClick(int buttonID) - { - switch (buttonID) - { - case (int)buttonsOption.AddBtn: - AddEmptyMacro(); - break; - case (int)buttonsOption.RemoveBtn: - RemoveLastCommand(); - break; - case (int)buttonsOption.CreateNewMacro: - UIManager.Gumps.OfType().FirstOrDefault(s => s.TheMacro == Macro)?.Dispose(); - - MacroButtonGump macroButtonGump = new MacroButtonGump(Macro, Mouse.Position.X, Mouse.Position.Y); - UIManager.Add(macroButtonGump); - break; - case (int)buttonsOption.OpenMacroOptions: - UIManager.Gumps.OfType().FirstOrDefault()?.Dispose(); - - GameActions.OpenSettings(4); - break; - case (int)buttonsOption.OpenButtonEditor: - UIManager.Gumps.OfType().FirstOrDefault()?.Dispose(); - OpenMacroButtonEditor(Macro, null); - break; - } - } - - private void OpenMacroButtonEditor(Macro macro, Vector2? position = null) - { - MacroButtonEditorGump btnEditorGump = UIManager.GetGump(); - - if (btnEditorGump == null) - { - var posX = (Client.Game.Window.ClientBounds.Width >> 1) - 300; - var posY = (Client.Game.Window.ClientBounds.Height >> 1) - 250; - Gump opt = UIManager.GetGump(); - if (opt != null) - { - posX = opt.X + opt.Width + 5; - posY = opt.Y; - } - if (position.HasValue) - { - posX = (int)position.Value.X; - posY = (int)position.Value.Y; - } - btnEditorGump = new MacroButtonEditorGump(macro, posX, posY); - UIManager.Add(btnEditorGump); - } - btnEditorGump.SetInScreen(); - btnEditorGump.BringOnTop(); - } - - private class MacroEntry : Control - { - private readonly MacroControl _control; - private readonly MacroObject _obj; - private readonly string[] _items; - public event EventHandler OnDelete; - ComboBoxWithLabel mainBox; - - public MacroEntry(MacroControl control, MacroObject obj, string[] items) - { - _control = control; - _items = items; - _obj = obj; - - mainBox = new ComboBoxWithLabel(string.Empty, 0, 200, _items, (int)obj.Code, BoxOnOnOptionSelected) { Tag = obj }; - - Add(mainBox); - - Control c; - Add(c = new ModernButton(mainBox.Width + 10, 0, 75, 40, ButtonAction.Activate, ResGumps.Remove, Theme.BUTTON_FONT_COLOR) { ButtonParameter = (int)buttonsOption.RemoveBtn, IsSelectable = false }); - - mainBox.Y = (c.Height >> 1) - (mainBox.Height >> 1); - - Height = c.Height; - - AddSubMacro(obj); - - ForceSizeUpdate(); - } - - - private void AddSubMacro(MacroObject obj) - { - if (obj == null || obj.Code == 0) - { - return; - } - - switch (obj.SubMenuType) - { - case 1: - int count = 0; - int offset = 0; - Macro.GetBoundByCode(obj.Code, ref count, ref offset); - - string[] names = new string[count]; - - for (int i = 0; i < count; i++) - { - names[i] = _allSubHotkeysNames[i + offset]; - } - - ComboBoxWithLabel sub = new ComboBoxWithLabel(string.Empty, 0, 200, names, (int)obj.SubCode - offset, (i, s) => - { - Macro.GetBoundByCode(obj.Code, ref count, ref offset); - MacroSubType subType = (MacroSubType)(offset + i); - obj.SubCode = subType; - }) - { Tag = obj, X = 20, Y = Height }; - - Add(sub); - - //Height += sub.Height; - break; - - case 2: - InputField textbox = new InputField(400, 40, 0, 80, obj.HasString() ? ((MacroObjectString)obj).Text : string.Empty, false, (s, e) => - { - if (obj.HasString()) - { - ((MacroObjectString)obj).Text = ((InputField.StbTextBox)s).Text; - } - }) - { - X = 20, - Y = Height - }; - - textbox.SetText(obj.HasString() ? ((MacroObjectString)obj).Text : string.Empty); - - Add(textbox); - - break; - } - ForceSizeUpdate(); - _control._databox.ReArrangeChildren(); - _control._databox.ForceSizeUpdate(); - _control.ForceSizeUpdate(); - } - - public override void OnButtonClick(int buttonID) - { - switch (buttonID) - { - case (int)buttonsOption.RemoveBtn: - - _control.Macro.Remove(_obj); - Dispose(); - _control._databox.ReArrangeChildren(); - _control._databox.ForceSizeUpdate(); - _control.ForceSizeUpdate(); - //_control.SetupMacroUI(); - OnDelete?.Invoke(this, _obj); - break; - } - } - - private void BoxOnOnOptionSelected(int selected, string val) - { - WantUpdateSize = true; - - MacroObject currentMacroObj = _obj; - - if (selected == 0) - { - _control.Macro.Remove(currentMacroObj); - - mainBox.Tag = null; - - Dispose(); - - _control.SetupMacroUI(); - } - else - { - MacroObject newMacroObj = Macro.Create((MacroType)selected); - - _control.Macro.Insert(currentMacroObj, newMacroObj); - _control.Macro.Remove(currentMacroObj); - - mainBox.Tag = newMacroObj; - - - for (int i = 2; i < Children.Count; i++) - { - Children[i]?.Dispose(); - } - AddSubMacro(newMacroObj); - } - } - } - } - - private class HotkeyBox : Control - { - private bool _actived; - private readonly ModernButton _buttonOK, _buttonCancel; - private readonly TextBox _label; - - public HotkeyBox() - { - CanMove = false; - AcceptMouseInput = true; - AcceptKeyboardInput = true; - - Width = 300; - Height = 40; - - AlphaBlendControl bg = new AlphaBlendControl() { Width = 150, Height = 40, AcceptMouseInput = true }; - Add(bg); - bg.MouseUp += LabelOnMouseUp; - - Add(_label = new TextBox("None", Theme.FONT, Theme.STANDARD_TEXT_SIZE, 150, Theme.TEXT_FONT_COLOR, align: FontStashSharp.RichText.TextHorizontalAlignment.Center, strokeEffect: false)); - _label.Y = (bg.Height >> 1) - (_label.Height >> 1); - - _label.MouseUp += LabelOnMouseUp; - - Add(_buttonOK = new ModernButton(152, 0, 75, 40, ButtonAction.Activate, "Save", Theme.BUTTON_FONT_COLOR) { ButtonParameter = (int)ButtonState.Ok }); - - Add(_buttonCancel = new ModernButton(_buttonOK.Bounds.Right + 5, 0, 75, 40, ButtonAction.Activate, "Cancel", Theme.BUTTON_FONT_COLOR) { ButtonParameter = (int)ButtonState.Cancel }); - - WantUpdateSize = false; - IsActive = false; - } - - public SDL.SDL_Keycode Key { get; private set; } - public SDL.SDL_GameControllerButton[] Buttons { get; private set; } - public MouseButtonType MouseButton { get; private set; } - public bool WheelScroll { get; private set; } - public bool WheelUp { get; private set; } - public SDL.SDL_Keymod Mod { get; private set; } - - public bool IsActive - { - get => _actived; - set - { - _actived = value; - - if (value) - { - _buttonOK.IsVisible = _buttonCancel.IsVisible = true; - _buttonOK.IsEnabled = _buttonCancel.IsEnabled = true; - } - else - { - _buttonOK.IsVisible = _buttonCancel.IsVisible = false; - _buttonOK.IsEnabled = _buttonCancel.IsEnabled = false; - } - } - } - - public event EventHandler HotkeyChanged, HotkeyCancelled; - - protected override void OnControllerButtonDown(SDL.SDL_GameControllerButton button) - { - if (IsActive) - { - SetButtons(Controller.PressedButtons()); - } - } - - protected override void OnKeyDown(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - if (IsActive) - { - SetKey(key, mod); - } - } - - public void SetButtons(SDL.SDL_GameControllerButton[] buttons) - { - ResetBinding(); - Buttons = buttons; - _label.Text = Controller.GetButtonNames(buttons); - } - - public void SetKey(SDL.SDL_Keycode key, SDL.SDL_Keymod mod) - { - if (key == SDL.SDL_Keycode.SDLK_UNKNOWN && mod == SDL.SDL_Keymod.KMOD_NONE) - { - ResetBinding(); - - Key = key; - Mod = mod; - } - else - { - string newvalue = KeysTranslator.TryGetKey(key, mod); - - if (!string.IsNullOrEmpty(newvalue) && key != SDL.SDL_Keycode.SDLK_UNKNOWN) - { - ResetBinding(); - - Key = key; - Mod = mod; - _label.Text = newvalue; - } - } - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Middle || button == MouseButtonType.XButton1 || button == MouseButtonType.XButton2) - { - SDL.SDL_Keymod mod = SDL.SDL_Keymod.KMOD_NONE; - - if (Keyboard.Alt) - { - mod |= SDL.SDL_Keymod.KMOD_ALT; - } - - if (Keyboard.Shift) - { - mod |= SDL.SDL_Keymod.KMOD_SHIFT; - } - - if (Keyboard.Ctrl) - { - mod |= SDL.SDL_Keymod.KMOD_CTRL; - } - - SetMouseButton(button, mod); - } - } - - public void SetMouseButton(MouseButtonType button, SDL.SDL_Keymod mod) - { - string newvalue = KeysTranslator.GetMouseButton(button, mod); - - if (!string.IsNullOrEmpty(newvalue) && button != MouseButtonType.None) - { - ResetBinding(); - - MouseButton = button; - Mod = mod; - _label.Text = newvalue; - } - } - - protected override void OnMouseWheel(MouseEventType delta) - { - SDL.SDL_Keymod mod = SDL.SDL_Keymod.KMOD_NONE; - - if (Keyboard.Alt) - { - mod |= SDL.SDL_Keymod.KMOD_ALT; - } - - if (Keyboard.Shift) - { - mod |= SDL.SDL_Keymod.KMOD_SHIFT; - } - - if (Keyboard.Ctrl) - { - mod |= SDL.SDL_Keymod.KMOD_CTRL; - } - - if (delta == MouseEventType.WheelScrollUp) - { - SetMouseWheel(true, mod); - } - else if (delta == MouseEventType.WheelScrollDown) - { - SetMouseWheel(false, mod); - } - } - - public void SetMouseWheel(bool wheelUp, SDL.SDL_Keymod mod) - { - string newvalue = KeysTranslator.GetMouseWheel(wheelUp, mod); - - if (!string.IsNullOrEmpty(newvalue)) - { - ResetBinding(); - - WheelScroll = true; - WheelUp = wheelUp; - Mod = mod; - _label.Text = newvalue; - } - } - - private void ResetBinding() - { - Key = 0; - MouseButton = MouseButtonType.None; - WheelScroll = false; - Mod = 0; - _label.Text = "None"; - Buttons = null; - } - - private void LabelOnMouseUp(object sender, MouseEventArgs e) - { - IsActive = true; - SetKeyboardFocus(); - } - - public override void OnButtonClick(int buttonID) - { - switch ((ButtonState)buttonID) - { - case ButtonState.Ok: - HotkeyChanged.Raise(this); - - break; - - case ButtonState.Cancel: - _label.Text = "None"; - - HotkeyCancelled.Raise(this); - - Key = SDL.SDL_Keycode.SDLK_UNKNOWN; - Mod = SDL.SDL_Keymod.KMOD_NONE; - - break; - } - - IsActive = false; - } - - private enum ButtonState - { - Ok, - Cancel - } - } - - private class NameOverheadAssignControl : Control - { - private readonly HotkeyBox _hotkeyBox; - private readonly Dictionary checkboxDict = new(); - - private enum ButtonType - { - CheckAll, - UncheckAll, - } - - public NameOverheadAssignControl(NameOverheadOption option) - { - Option = option; - - CanMove = true; - - Control c; - c = AddLabel("Set hotkey:"); - - _hotkeyBox = new HotkeyBox - { - X = c.Bounds.Right + 5 - }; - - _hotkeyBox.HotkeyChanged += BoxOnHotkeyChanged; - _hotkeyBox.HotkeyCancelled += BoxOnHotkeyCancelled; - - Add(_hotkeyBox); - - Add(c = new ModernButton(0, _hotkeyBox.Height + 3, 100, 40, ButtonAction.Activate, "Uncheck all", Theme.BUTTON_FONT_COLOR) { ButtonParameter = (int)ButtonType.UncheckAll, IsSelectable = false }); - - Add(new ModernButton(c.Bounds.Right + 5, _hotkeyBox.Height + 3, 100, 40, ButtonAction.Activate, "Check all", Theme.BUTTON_FONT_COLOR) { ButtonParameter = (int)ButtonType.CheckAll, IsSelectable = false }); - - SetupOptionCheckboxes(); - - UpdateCheckboxesByCurrentOptionFlags(); - UpdateValueInHotkeyBox(); - } - - private void SetupOptionCheckboxes() - { - int rightPosX = 200; - Control c; - PositionHelper.Reset(); - - PositionHelper.Y = 100; - - c = AddLabel("Items"); - PositionHelper.PositionControl(c); - - c = AddCheckbox("Containers", NameOverheadOptions.Containers); - PositionHelper.PositionControl(c); - - c = AddCheckbox("Gold", NameOverheadOptions.Gold); - PositionHelper.PositionExact(c, rightPosX, PositionHelper.LAST_Y); - - PositionHelper.PositionControl(AddCheckbox("Stackable", NameOverheadOptions.Stackable)); - PositionHelper.PositionExact(AddCheckbox("Locked down", NameOverheadOptions.LockedDown), rightPosX, PositionHelper.LAST_Y); - - PositionHelper.PositionControl(AddCheckbox("Other items", NameOverheadOptions.Other)); - - - - PositionHelper.BlankLine(); - PositionHelper.PositionControl(AddLabel("Corpses")); - - PositionHelper.PositionControl(AddCheckbox("Monster corpses", NameOverheadOptions.MonsterCorpses)); - PositionHelper.PositionExact(AddCheckbox("Humanoid corpses", NameOverheadOptions.HumanoidCorpses), rightPosX, PositionHelper.LAST_Y); - //AddCheckbox("Own corpses", NameOverheadOptions.OwnCorpses, 0, y); - - - - PositionHelper.BlankLine(); - PositionHelper.PositionControl(AddLabel("Mobiles by type")); - - PositionHelper.PositionControl(AddCheckbox("Humanoid", NameOverheadOptions.Humanoid)); - PositionHelper.PositionExact(AddCheckbox("Monster", NameOverheadOptions.Monster), rightPosX, PositionHelper.LAST_Y); - - PositionHelper.PositionControl(AddCheckbox("Your Followers", NameOverheadOptions.OwnFollowers)); - PositionHelper.PositionExact(AddCheckbox("Yourself", NameOverheadOptions.Self), rightPosX, PositionHelper.LAST_Y); - - PositionHelper.PositionControl(AddCheckbox("Exclude yourself", NameOverheadOptions.ExcludeSelf)); - - - - PositionHelper.BlankLine(); - PositionHelper.PositionControl(AddLabel("Mobiles by notoriety")); - - CheckboxWithLabel cb; - PositionHelper.PositionControl(cb = AddCheckbox("Innocent", NameOverheadOptions.Innocent)); - cb.TextLabel.Hue = ProfileManager.CurrentProfile.InnocentHue; - PositionHelper.PositionExact(cb = AddCheckbox("Allied", NameOverheadOptions.Ally), rightPosX, PositionHelper.LAST_Y); - cb.TextLabel.Hue = ProfileManager.CurrentProfile.FriendHue; - - PositionHelper.PositionControl(cb = AddCheckbox("Attackable", NameOverheadOptions.Gray)); - cb.TextLabel.Hue = ProfileManager.CurrentProfile.CanAttackHue; - PositionHelper.PositionExact(cb = AddCheckbox("Criminal", NameOverheadOptions.Criminal), rightPosX, PositionHelper.LAST_Y); - cb.TextLabel.Hue = ProfileManager.CurrentProfile.CriminalHue; - - PositionHelper.PositionControl(cb = AddCheckbox("Enemy", NameOverheadOptions.Enemy)); - cb.TextLabel.Hue = ProfileManager.CurrentProfile.EnemyHue; - PositionHelper.PositionExact(cb = AddCheckbox("Murderer", NameOverheadOptions.Murderer), rightPosX, PositionHelper.LAST_Y); - cb.TextLabel.Hue = ProfileManager.CurrentProfile.MurdererHue; - - PositionHelper.PositionControl(cb = AddCheckbox("Invulnerable", NameOverheadOptions.Invulnerable)); - cb.TextLabel.Hue = ProfileManager.CurrentProfile.InvulnerableHue; - } - - private TextBox AddLabel(string name) - { - var label = new TextBox(name, Theme.FONT, Theme.STANDARD_TEXT_SIZE, null, Theme.TEXT_FONT_COLOR, strokeEffect: false); - - Add(label); - - return label; - } - - private CheckboxWithLabel AddCheckbox(string checkboxName, NameOverheadOptions optionFlag) - { - var checkbox = new CheckboxWithLabel(checkboxName, 0, true, (b) => - { - if (b) - Option.NameOverheadOptionFlags |= (int)optionFlag; - else - Option.NameOverheadOptionFlags &= ~(int)optionFlag; - - if (NameOverHeadManager.LastActiveNameOverheadOption == Option.Name) - NameOverHeadManager.ActiveOverheadOptions = (NameOverheadOptions)Option.NameOverheadOptionFlags; - }); - - checkboxDict.Add(optionFlag, checkbox); - - Add(checkbox); - - return checkbox; - } - - public NameOverheadOption Option { get; } - - private void UpdateValueInHotkeyBox() - { - if (Option == null || _hotkeyBox == null) - { - return; - } - - if (Option.Key != SDL.SDL_Keycode.SDLK_UNKNOWN) - { - SDL.SDL_Keymod mod = SDL.SDL_Keymod.KMOD_NONE; - - if (Option.Alt) - { - mod |= SDL.SDL_Keymod.KMOD_ALT; - } - - if (Option.Shift) - { - mod |= SDL.SDL_Keymod.KMOD_SHIFT; - } - - if (Option.Ctrl) - { - mod |= SDL.SDL_Keymod.KMOD_CTRL; - } - - _hotkeyBox.SetKey(Option.Key, mod); - } - } - - private void BoxOnHotkeyChanged(object sender, EventArgs e) - { - bool shift = (_hotkeyBox.Mod & SDL.SDL_Keymod.KMOD_SHIFT) != SDL.SDL_Keymod.KMOD_NONE; - bool alt = (_hotkeyBox.Mod & SDL.SDL_Keymod.KMOD_ALT) != SDL.SDL_Keymod.KMOD_NONE; - bool ctrl = (_hotkeyBox.Mod & SDL.SDL_Keymod.KMOD_CTRL) != SDL.SDL_Keymod.KMOD_NONE; - - if (_hotkeyBox.Key == SDL.SDL_Keycode.SDLK_UNKNOWN) - return; - - NameOverheadOption option = NameOverHeadManager.FindOptionByHotkey(_hotkeyBox.Key, alt, ctrl, shift); - - if (option == null) - { - Option.Key = _hotkeyBox.Key; - Option.Shift = shift; - Option.Alt = alt; - Option.Ctrl = ctrl; - - return; - } - - if (Option == option) - return; - - UpdateValueInHotkeyBox(); - UIManager.Add(new MessageBoxGump(250, 150, string.Format(ResGumps.ThisKeyCombinationAlreadyExists, option.Name), null)); - } - - private void BoxOnHotkeyCancelled(object sender, EventArgs e) - { - Option.Alt = Option.Ctrl = Option.Shift = false; - Option.Key = SDL.SDL_Keycode.SDLK_UNKNOWN; - } - - public override void OnButtonClick(int buttonID) - { - switch ((ButtonType)buttonID) - { - case ButtonType.CheckAll: - Option.NameOverheadOptionFlags = int.MaxValue; - UpdateCheckboxesByCurrentOptionFlags(); - - break; - - case ButtonType.UncheckAll: - Option.NameOverheadOptionFlags = 0x0; - UpdateCheckboxesByCurrentOptionFlags(); - - break; - } - } - - private void UpdateCheckboxesByCurrentOptionFlags() - { - foreach (var kvp in checkboxDict) - { - var flag = kvp.Key; - var checkbox = kvp.Value; - - checkbox.IsChecked = ((NameOverheadOptions)Option.NameOverheadOptionFlags).HasFlag(flag); - } - } - } - #endregion - - private class ProfileLocationData - { - public readonly DirectoryInfo Server; - public readonly DirectoryInfo Username; - public readonly DirectoryInfo Character; - - public ProfileLocationData(string server, string username, string character) - { - this.Server = new DirectoryInfo(server); - this.Username = new DirectoryInfo(username); - this.Character = new DirectoryInfo(character); - } - - public override string ToString() - { - return Character.ToString(); - } - } - - private class SettingsOption - { - public SettingsOption(string optionLabel, Control control, int maxTotalWidth, PAGE optionsPage, int x = 0, int y = 0) - { - OptionLabel = optionLabel; - OptionControl = control; - OptionsPage = optionsPage; - FullControl = new Area(false) { AcceptMouseInput = true, CanMove = true, CanCloseWithRightClick = true }; - - if (!string.IsNullOrEmpty(OptionLabel)) - { - Control labelTextBox = new TextBox(OptionLabel, Theme.FONT, 20, null, Theme.TEXT_FONT_COLOR, strokeEffect: false) { AcceptMouseInput = false }; - FullControl.Add(labelTextBox, (int)optionsPage); - - if (labelTextBox.Width > maxTotalWidth) - { - labelTextBox.Width = maxTotalWidth; - } - - if (OptionControl != null) - { - if (labelTextBox.Width + OptionControl.Width + 5 > maxTotalWidth) - { - OptionControl.Y = labelTextBox.Height + 5; - OptionControl.X = 15; - } - else - { - OptionControl.X = labelTextBox.Width + 5; - } - } - - FullControl.Width += labelTextBox.Width + 5; - FullControl.Height = labelTextBox.Height; - } - - if (OptionControl != null) - { - FullControl.Add(OptionControl, (int)optionsPage); - FullControl.Width += OptionControl.Width; - FullControl.ActivePage = (int)optionsPage; - - if (OptionControl.Height > FullControl.Height) - { - FullControl.Height = OptionControl.Height; - } - } - - FullControl.X = x; - FullControl.Y = y; - } - - public string OptionLabel { get; } - public Control OptionControl { get; } - public PAGE OptionsPage { get; } - public Area FullControl { get; } - } - - private static class Theme - { - public const int SLIDER_WIDTH = 150; - public const int COMBO_BOX_WIDTH = 225; - public const int SCROLL_BAR_WIDTH = 15; - public const int INPUT_WIDTH = 200; - public const int TOP_PADDING = 5; - public const int INDENT_SPACE = 40; - public const int BLANK_LINE = 20; - public const int HORIZONTAL_SPACING_CONTROLS = 20; - - public const int STANDARD_TEXT_SIZE = 20; - - public const float NO_MATCH_SEARCH = 0.5f; - - public const ushort BACKGROUND = 897; - public const ushort SEARCH_BACKGROUND = 899; - public const ushort BLACK = 0; - - public static Color DROPDOWN_OPTION_NORMAL_HUE = Color.White; - public static Color DROPDOWN_OPTION_HOVER_HUE = Color.AntiqueWhite; - public static Color DROPDOWN_OPTION_SELECTED_HUE = Color.CadetBlue; - - public static Color BUTTON_FONT_COLOR = Color.White; - public static Color TEXT_FONT_COLOR = Color.White; - - public static string FONT = TrueTypeLoader.EMBEDDED_FONT; - } - - private static class PositionHelper - { - public static int X, Y = Theme.TOP_PADDING, LAST_Y = Theme.TOP_PADDING; - - public static void BlankLine() - { - LAST_Y = Y; - Y += Theme.BLANK_LINE; - } - - public static void Indent() - { - X += Theme.INDENT_SPACE; - } - - public static void RemoveIndent() - { - X -= Theme.INDENT_SPACE; - } - - public static void PositionControl(Control c) - { - c.X = X; - c.Y = Y; - - LAST_Y = Y; - Y += c.Height + Theme.TOP_PADDING; - } - - public static void PositionExact(Control c, int x, int y) - { - c.X = x; - c.Y = y; - } - - public static void Reset() - { - X = 0; - Y = Theme.TOP_PADDING; - LAST_Y = Y; - } - } - - private enum PAGE - { - None, - General, - Sound, - Video, - Macros, - Tooltip, - Speech, - CombatSpells, - Counters, - InfoBar, - Containers, - Experimental, - IgnoreList, - NameplateOptions, - TUOCooldowns, - TUOOptions - } - - private interface SearchableOption - { - public bool Search(string text); - - public void OnSearchMatch(); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/ModernPaperdoll.cs b/src/ClassicUO.Client/Game/UI/Gumps/ModernPaperdoll.cs deleted file mode 100644 index 6904f398e..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/ModernPaperdoll.cs +++ /dev/null @@ -1,840 +0,0 @@ -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Network; -using ClassicUO.Renderer; -using ClassicUO.Renderer.Animations; -using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using System.Xml; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class ModernPaperdoll : AnchorableGump - { - #region CONST - private const int WIDTH = 250, HEIGHT = 380; - private const int CELL_SPACING = 2, TOP_SPACING = 40; - #endregion - - #region VARS - private readonly Dictionary itemLayerSlots; - private Label titleLabel; - private static int lastX = 100, lastY = 100; - private GumpPic backgroundImage; - #endregion - - public override GumpType GumpType => GumpType.PaperDoll; - - public ModernPaperdoll(uint localSerial) : base(localSerial, 0) - { - UIManager.GetGump()?.Dispose(); - #region ASSIGN FIELDS - AcceptMouseInput = true; - CanMove = true; - CanCloseWithRightClick = true; - #endregion - #region SET VARS - Width = WIDTH; - Height = HEIGHT; - GroupMatrixHeight = Height; - GroupMatrixWidth = Width; - if (ProfileManager.CurrentProfile != null) - { - lastX = ProfileManager.CurrentProfile.ModernPaperdollPosition.X; - lastY = ProfileManager.CurrentProfile.ModernPaperdollPosition.Y; - IsLocked = ProfileManager.CurrentProfile.PaperdollLocked; - } - X = lastX; - Y = lastY; - - itemLayerSlots = new Dictionary(); - #endregion - - Add(backgroundImage = new GumpPic(0, 0, 40312, ProfileManager.CurrentProfile.ModernPaperDollHue)); - - HitBox _menuHit = new HitBox(Width - 26, 1, 25, 16, alpha: 0f); - Add(_menuHit); - _menuHit.SetTooltip("Open paperdoll menu"); - _menuHit.MouseUp += (sender, e) => - { - if (e.Button == MouseButtonType.Left) - { - UIManager.GetGump()?.Dispose(); - UIManager.Add(new MenuGump(Mouse.Position.X - 145, Mouse.Position.Y - 5, localSerial)); - } - }; - - #region SET UP ITEM SLOTS - ItemSlot _; - - _ = new ItemSlot(35, 35, new Layer[] { Layer.Earrings }) { X = 100 - 35 - CELL_SPACING, Y = TOP_SPACING + 15 }; - itemLayerSlots.Add(_.layers, _); //Earrings - - _ = new ItemSlot(50, 50, new Layer[] { Layer.Helmet }) { X = 100, Y = TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //Head - - _ = new ItemSlot(35, 35, new Layer[] { Layer.Necklace }) { X = 150 + CELL_SPACING, Y = TOP_SPACING + 15 }; - itemLayerSlots.Add(_.layers, _); //Amulet - - - _ = new ItemSlot(50, 75, new Layer[] { Layer.OneHanded }) { X = 50 - CELL_SPACING, Y = 50 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //L Wep - - _ = new ItemSlot(50, 75, new Layer[] { Layer.Torso }) { X = 100, Y = 50 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //Chest - - _ = new ItemSlot(50, 75, new Layer[] { Layer.TwoHanded }) { X = 150 + CELL_SPACING, Y = 50 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //R Wep - - - _ = new ItemSlot(50, 50, new Layer[] { Layer.Arms }) { X = 50 - CELL_SPACING, Y = 125 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //Arms - - _ = new ItemSlot(50, 50, new Layer[] { Layer.Robe }) { X = 100, Y = 125 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //Robe - - _ = new ItemSlot(50, 50, new Layer[] { Layer.Cloak }) { X = 150 + CELL_SPACING, Y = 125 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //Cloak - - - _ = new ItemSlot(35, 35, new Layer[] { Layer.Ring }) { X = 50 - CELL_SPACING, Y = 175 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //Ring - - _ = new ItemSlot(80, 35, new Layer[] { Layer.Waist }) { X = 85, Y = 175 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //Belt - - _ = new ItemSlot(35, 35, new Layer[] { Layer.Bracelet }) { X = 165 + CELL_SPACING, Y = 175 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //Bracelet - - - _ = new ItemSlot(50, 50, new Layer[] { Layer.Gloves }) { X = 50 - CELL_SPACING, Y = 210 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //Gloves - - _ = new ItemSlot(50, 50, new Layer[] { Layer.Pants }) { X = 100, Y = 210 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //Legs - - _ = new ItemSlot(50, 50, new Layer[] { Layer.Shoes }) { X = 150 + CELL_SPACING, Y = 210 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //Boots - - - - _ = new ItemSlot(33, 34, new Layer[] { Layer.Talisman }) { X = 3, Y = 225 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //Talisman - - _ = new ItemSlot(33, 34, new Layer[] { Layer.Backpack }) { X = Width - 36, Y = 225 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); //Backpack - - - _ = new ItemSlot(24, 24, new Layer[] { Layer.Tunic }) { X = 8, Y = 163 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); - - _ = new ItemSlot(24, 24, new Layer[] { Layer.Shirt }) { X = 8, Y = 193 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); - - - _ = new ItemSlot(24, 24, new Layer[] { Layer.Skirt }) { X = Width - 32, Y = 163 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); - - _ = new ItemSlot(24, 24, new Layer[] { Layer.Legs }) { X = Width - 32, Y = 193 + CELL_SPACING + TOP_SPACING }; - itemLayerSlots.Add(_.layers, _); - #endregion - - BuildLayerSlots(); - - HitBox _virtueHitBox = new HitBox((WIDTH / 2) - 16, 1, 32, 32, "Virtues menu", 0f); - _virtueHitBox.MouseDoubleClick += (s, e) => - { - GameActions.ReplyGump - ( - World.Player, - 0x000001CD, - 0x00000001, - new[] - { - LocalSerial - }, - new Tuple[0] - ); - }; - Add(_virtueHitBox); - - Add(titleLabel = new Label("", true, 0xffff, maxwidth: WIDTH - 30, align: TEXT_ALIGN_TYPE.TS_CENTER) { X = 15, Y = 273 + CELL_SPACING + TOP_SPACING, AcceptMouseInput = false }); - - HitBox _minHit = new HitBox(1, 1, 14, 18, alpha: 0f); - _minHit.SetTooltip("Minimize paperdoll"); - _minHit.MouseUp += (s, e) => - { - Dispose(); - UIManager.Add(new MinimizedPaperdoll(LocalSerial) { X = X, Y = Y }); - }; - Add(_minHit); - - RequestUpdateContents(); - } - - public void UpdateTitle(string text) - { - titleLabel.Text = text; - } - - private void BuildLayerSlots() - { - foreach (var layerSlot in itemLayerSlots) - { - Add(layerSlot.Value); - } - } - - protected override void UpdateContents() - { - base.UpdateContents(); - if (World.Player == null) - return; - - foreach (var layerSlot in itemLayerSlots) - { - layerSlot.Value.ClearItems(); - - foreach (Layer layer in layerSlot.Key) - { - Item i = World.Player.FindItemByLayer(layer); - if (i != null && i.IsLootable) - { - layerSlot.Value.AddItem(i); - } - } - } - - UIManager.GetGump()?.PaperDollPreview.RequestUpdate(); - - Mobile m = World.Mobiles.Get(LocalSerial); - if (m != null) - UpdateTitle(m.Title); - } - - public void UpdateOptions() - { - backgroundImage.Hue = ProfileManager.CurrentProfile.ModernPaperDollHue; - foreach (var layerSlot in itemLayerSlots) - { - layerSlot.Value.UpdateOptions(); - } - } - - public static void UpdateAllOptions() - { - foreach (ModernPaperdoll p in UIManager.Gumps.OfType()) - { - p.UpdateOptions(); - } - } - - public override void Update() - { - base.Update(); - - if (X != lastX || Y != lastY) - { - lastX = X; - lastY = Y; - if (ProfileManager.CurrentProfile != null) - ProfileManager.CurrentProfile.ModernPaperdollPosition = new Point(X, Y); - } - } - - public override void Dispose() - { - if (ProfileManager.CurrentProfile != null) - ProfileManager.CurrentProfile.ModernPaperdollPosition = new Point(X, Y); - lastX = X; - lastY = Y; - - base.Dispose(); - //World.OPL.OPLOnReceive -= OPL_OnOPLReceive; - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - if (ProfileManager.CurrentProfile != null) - { - X = lastX = ProfileManager.CurrentProfile.ModernPaperdollPosition.X; - Y = lastY = ProfileManager.CurrentProfile.ModernPaperdollPosition.Y; - } - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - base.OnMouseUp(x, y, button); - - if (Client.Game.GameCursor.ItemHold.Enabled) - { - if (LocalSerial == World.Player.Serial) - { - if (SelectedObject.Object is Item item && (item.Layer == Layer.Backpack || item.ItemData.IsContainer)) - { - GameActions.DropItem - ( - Client.Game.GameCursor.ItemHold.Serial, - 0xFFFF, - 0xFFFF, - 0, - item.Serial - ); - - Mouse.CancelDoubleClick = true; - } - else - { - if (Client.Game.GameCursor.ItemHold.ItemData.IsWearable) - { - Item equipment = World.Player.FindItemByLayer((Layer)Client.Game.GameCursor.ItemHold.ItemData.Layer); - - if (equipment == null) - { - GameActions.Equip(World.Player); - Mouse.CancelDoubleClick = true; - } - } - } - } - } - else if (TargetManager.IsTargeting) - { - if (SelectedObject.Object is Item item) - TargetManager.Target(item.Serial); - } - } - - private class ItemSlot : Control - { - public readonly Layer[] layers; - private Area itemArea; - - private AlphaBlendControl durablityBar; - - public ItemSlot(int width, int height, Layer[] layers) - { - #region ASSIGN FIELDS - AcceptMouseInput = true; - CanMove = true; - CanCloseWithRightClick = false; - #endregion - #region SET VARS - Width = width; - Height = height; - #endregion - - Add(itemArea = new Area(false) { Width = Width, Height = Height, AcceptMouseInput = true, CanMove = true }); - itemArea.SetTooltip(layers[0].ToString()); - - Add(durablityBar = new AlphaBlendControl(0.75f) { Width = 7, Height = Height, Hue = ProfileManager.CurrentProfile.ModernPaperDollDurabilityHue, IsVisible = false }); - - this.layers = layers; - } - - public void UpdateOptions() - { - durablityBar.Hue = ProfileManager.CurrentProfile.ModernPaperDollDurabilityHue; - } - - public void AddItem(Item item) - { - itemArea.Add(new ItemGumpFixed(item, Width, Height) { HighlightOnMouseOver = false }); - UpdateDurability(item); - } - - private void UpdateDurability(Item item) - { - if (IsDisposed || durablityBar.IsDisposed || item == null) - { - return; - } - - durablityBar.Hue = ProfileManager.CurrentProfile.ModernPaperDollDurabilityHue; - - if (World.DurabilityManager.TryGetDurability(item.Serial, out DurabiltyProp durabilty)) - { - if (durabilty.Percentage > (float)ProfileManager.CurrentProfile.ModernPaperDoll_DurabilityPercent / (float)100) - { - durablityBar.IsVisible = false; - return; - } - durablityBar.Height = (int)(Height * durabilty.Percentage); - durablityBar.Y = Height - durablityBar.Height; - durablityBar.IsVisible = true; - } - else - { - durablityBar.IsVisible = false; - } - } - - public void ClearItems() - { - itemArea.Children.Clear(); - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - base.OnMouseUp(x, y, button); - Parent?.InvokeMouseUp(new Point(x, y), button); - } - } - - private class ItemGumpFixed : ItemGump - { - public readonly Item item; - - public ItemGumpFixed(Item item, int w, int h) : base - ( - item.Serial, - item.DisplayedGraphic, - item.Hue, - item.X, - item.Y - ) - { - if ((Layer)item.ItemData.Layer == Layer.Backpack && item.Container == World.Player.Serial) - CanPickUp = false; - Width = w; - Height = h; - WantUpdateSize = false; - - this.item = item; - } - - private static ushort GetAnimID(ushort graphic, ushort animID, bool isfemale) - { - int offset = isfemale ? Constants.FEMALE_GUMP_OFFSET : Constants.MALE_GUMP_OFFSET; - - if (Client.Version >= Utility.ClientVersion.CV_7000 && animID == 0x03CA // graphic for dead shroud - && (graphic == 0x02B7 || graphic == 0x02B6)) // dead gargoyle graphics - { - animID = 0x0223; - } - - Client.Game.Animations.ConvertBodyIfNeeded(ref graphic); - - if (AnimationsLoader.Instance.EquipConversions.TryGetValue(graphic, out Dictionary dict)) - { - if (dict.TryGetValue(animID, out EquipConvData data)) - { - if (data.Gump > Constants.MALE_GUMP_OFFSET) - { - animID = (ushort)(data.Gump >= Constants.FEMALE_GUMP_OFFSET ? data.Gump - Constants.FEMALE_GUMP_OFFSET : data.Gump - Constants.MALE_GUMP_OFFSET); - } - else - { - animID = data.Gump; - } - } - } - - if (animID + offset > GumpsLoader.MAX_GUMP_DATA_INDEX_COUNT || Client.Game.Gumps.GetGump((ushort)(animID + offset)).Texture == null) - { - // inverse - offset = isfemale ? Constants.MALE_GUMP_OFFSET : Constants.FEMALE_GUMP_OFFSET; - } - - return (ushort)(animID + offset); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (item == null) - { - Dispose(); - } - - if (IsDisposed) - { - return false; - } - - Vector3 hueVector = ShaderHueTranslator.GetHueVector - ( - MouseIsOver && HighlightOnMouseOver ? 0x0035 : item.Hue, - item.ItemData.IsPartialHue, - 1, - true - ); - - ref readonly var texture = ref Client.Game.Arts.GetArt((uint)item.DisplayedGraphic); - Rectangle _rect = Client.Game.Arts.GetRealArtBounds((uint)item.DisplayedGraphic); - - - Point _originalSize = new Point(Width, Height); - Point _point = new Point((Width >> 1) - (_originalSize.X >> 1), (Height >> 1) - (_originalSize.Y >> 1)); - - if (_rect.Width < Width) - { - _originalSize.X = _rect.Width; - _point.X = (Width >> 1) - (_originalSize.X >> 1); - } - - if (_rect.Height < Height) - { - _originalSize.Y = _rect.Height; - _point.Y = (Height >> 1) - (_originalSize.Y >> 1); - } - - if (_rect.Width > Width) - { - _originalSize.X = Width; - _point.X = 0; - } - - if (_rect.Height > Height) - { - _originalSize.Y = Height; - _point.Y = 0; - } - - if (texture.Texture != null) - { - batcher.Draw - ( - texture.Texture, - new Rectangle - ( - x + _point.X, - y + _point.Y, - _originalSize.X, - _originalSize.Y - ), - new Rectangle - ( - texture.UV.X + _rect.X, - texture.UV.Y + _rect.Y, - _rect.Width, - _rect.Height - ), - hueVector - ); - - return true; - } - - return false; - } - - public override bool Contains(int x, int y) - { - return true; - } - } - - private class MenuButton : Control - { - public MenuButton(int width, uint hue, float alpha, string tooltip = "") - { - Width = width; - Height = 16; - AcceptMouseInput = true; - Area _ = new Area() { Width = Width, Height = Height, AcceptMouseInput = false }; - - Add(_); - Add(new Line(2, 2, Width - 4, 2, hue) { Alpha = alpha, AcceptMouseInput = false }); - Add(new Line(2, 7, Width - 4, 2, hue) { Alpha = alpha, AcceptMouseInput = false }); - Add(new Line(2, 12, Width - 4, 2, hue) { Alpha = alpha, AcceptMouseInput = false }); - SetTooltip(tooltip); - //_.SetTooltip(tooltip); - } - - public override bool Contains(int x, int y) - { - return true; - } - } - - private class MenuGump : Gump - { - public MenuGump(int x, int y, uint localSerial) : base(localSerial, 0) - { - X = x; - Y = y; - Width = 150; - Height = 281; - AcceptMouseInput = true; - - Add(new AlphaBlendControl(0.85f) { Width = Width, Height = Height, AcceptMouseInput = false }); - - var i = 1; - - NiceButton preview = new NiceButton(1, 1, Width - 2, 20, ButtonAction.Activate, "Preview"); - preview.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - UIManager.GetGump()?.Dispose(); - UIManager.Add(new CharacterPreview(localSerial) { X = 100, Y = 100 }); - } - }; - Add(preview); - - NiceButton help = new NiceButton(1, 1 + 20 * i++, Width - 2, 20, ButtonAction.Activate, "Help"); - help.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - GameActions.RequestHelp(); - } - }; - Add(help); - - NiceButton options = new NiceButton(1, 1 + 20 * i++, Width - 2, 20, ButtonAction.Activate, "Options"); - options.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - GameActions.OpenSettings(); - } - }; - Add(options); - - NiceButton logout = new NiceButton(1, 1 + 20 * i++, Width - 2, 20, ButtonAction.Activate, "Log Out"); - logout.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - Client.Game.GetScene()?.RequestQuitGame(); - } - }; - Add(logout); - - NiceButton quests = new NiceButton(1, 1 + 20 * i++, Width - 2, 20, ButtonAction.Activate, "Quests"); - quests.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - GameActions.RequestQuestMenu(); - } - }; - Add(quests); - - NiceButton skills = new NiceButton(1, 1 + 20 * i++, Width - 2, 20, ButtonAction.Activate, "Skills"); - skills.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - GameActions.OpenSkills(); - } - }; - Add(skills); - - NiceButton guild = new NiceButton(1, 1 + 20 * i++, Width - 2, 20, ButtonAction.Activate, "Guild"); - guild.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - GameActions.OpenGuildGump(); - } - }; - Add(guild); - - NiceButton peace = new NiceButton(1, 1 + 20 * i++, Width - 2, 20, ButtonAction.Activate, "Peace/War"); - peace.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - GameActions.ToggleWarMode(); - } - }; - Add(peace); - - NiceButton durability = new NiceButton(1, 1 + 20 * i++, Width - 2, 20, ButtonAction.Activate, "Durability Tracker"); - durability.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - UIManager.GetGump()?.Dispose(); - UIManager.Add(new DurabilitysGump()); - } - }; - Add(durability); - - NiceButton status = new NiceButton(1, 1 + 20 * i++, Width - 2, 20, ButtonAction.Activate, "Status"); - status.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - if (LocalSerial == World.Player) - { - UIManager.GetGump(LocalSerial)?.Dispose(); - - StatusGumpBase status = StatusGumpBase.GetStatusGump(); - - if (status == null) - { - UIManager.Add(StatusGumpBase.AddStatusGump(ProfileManager.CurrentProfile.StatusGumpPosition.X, ProfileManager.CurrentProfile.StatusGumpPosition.Y)); - } - else - { - status.BringOnTop(); - } - } - else - { - if (UIManager.GetGump(LocalSerial) != null) - { - return; - } - - if (ProfileManager.CurrentProfile.CustomBarsToggled) - { - Rectangle bounds = new Rectangle(0, 0, HealthBarGumpCustom.HPB_WIDTH, HealthBarGumpCustom.HPB_HEIGHT_SINGLELINE); - - UIManager.Add - ( - new HealthBarGumpCustom(LocalSerial) - { - X = Mouse.Position.X - (bounds.Width >> 1), - Y = Mouse.Position.Y - 5 - } - ); - } - else - { - Rectangle bounds = Client.Game.Gumps.GetGump(0x0804).UV; - - UIManager.Add - ( - new HealthBarGump(LocalSerial) - { - X = Mouse.Position.X - (bounds.Width >> 1), - Y = Mouse.Position.Y - 5 - } - ); - } - } - } - }; - Add(status); - - NiceButton party = new NiceButton(1, 1 + 20 * i++, Width - 2, 20, ButtonAction.Activate, "Party"); - party.MouseUp += (s, e) => - { - PartyGump party = UIManager.GetGump(); - - if (party == null) - { - int x = Client.Game.Window.ClientBounds.Width / 2 - 272; - int y = Client.Game.Window.ClientBounds.Height / 2 - 240; - UIManager.Add(new PartyGump(x, y, World.Party.CanLoot)); - } - else - { - party.BringOnTop(); - } - }; - Add(party); - - NiceButton profileEditor = new NiceButton(1, 1 + 20 * i++, Width - 2, 20, ButtonAction.Activate, "Profile"); - profileEditor.MouseUp += (s, e) => - { - GameActions.RequestProfile(LocalSerial); - }; - Add(profileEditor); - - NiceButton abilities = new NiceButton(1, 1 + 20 * i++, Width - 2, 20, ButtonAction.Activate, "Abilities"); - abilities.MouseUp += (s, e) => - { - if (UIManager.GetGump() == null) - { - UIManager.Add(new RacialAbilitiesBookGump(100, 100)); - } - }; - Add(abilities); - - NiceButton weaponAbilities = new NiceButton(1, 1 + 20 * i++, Width - 2, 20, ButtonAction.Activate, "Weapon abilities"); - weaponAbilities.MouseUp += (s, e) => - { - GameActions.OpenAbilitiesBook(); - }; - Add(weaponAbilities); - - Add(new SimpleBorder() { Width = Width, Height = Height }); - } - - protected override void OnMouseExit(int x, int y) - { - base.OnMouseExit(x, y); - Dispose(); - } - } - - private class CharacterPreview : Gump - { - public readonly PaperDollInteractable PaperDollPreview; - public CharacterPreview(uint localSerial) : base(localSerial, 0) - { - Width = 190; - Height = 250; - CanCloseWithRightClick = true; - CanMove = true; - AcceptMouseInput = true; - Add(new AlphaBlendControl(0.75f) { CanCloseWithRightClick = true, CanMove = true, Width = Width, Height = Height }); - - Add(PaperDollPreview = new PaperDollInteractable(0, 0, LocalSerial, null) { AcceptMouseInput = false }); - - Add(new SimpleBorder() { Width = Width - 1, Height = Height - 1, Alpha = 0.85f }); - - } - } - - private class MinimizedPaperdoll : Gump - { - public MinimizedPaperdoll(uint localSerial) : base(localSerial, 0) - { - Width = 86; - Height = 23; - AcceptMouseInput = true; - CanMove = true; - CanCloseWithRightClick = true; - - Add(new GumpPic(0, 0, 0x7EE, 0)); - - Checkbox _; - - Add(_ = new Checkbox(0x00D2, 0x00D3) { X = 66, Y = 2 }); - _.IsChecked = ProfileManager.CurrentProfile.OpenModernPaperdollAtMinimizeLoc; - _.SetTooltip("Open paperdoll at this location"); - _.MouseUp += (s, e) => - { - ProfileManager.CurrentProfile.OpenModernPaperdollAtMinimizeLoc = _.IsChecked; - }; - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - base.OnMouseUp(x, y, button); - if (button == MouseButtonType.Left) - { - Dispose(); - UIManager.GetGump()?.Dispose(); - - ModernPaperdoll pd = new ModernPaperdoll(LocalSerial); - - if (ProfileManager.CurrentProfile.OpenModernPaperdollAtMinimizeLoc) - { - pd.X = X; - pd.Y = Y; - } - - UIManager.Add(pd); - } - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/ModernShopGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/ModernShopGump.cs deleted file mode 100644 index 3bc19c639..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/ModernShopGump.cs +++ /dev/null @@ -1,522 +0,0 @@ -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Network; -using ClassicUO.Renderer; -using ClassicUO.Renderer.Animations; -using ClassicUO.Resources; -using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Xml.Linq; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class ModernShopGump : Gump - { - private int WIDTH = 450; - - const int ITEM_DESCPTION_WIDTH = 300; - private readonly bool isPurchaseGump; - private ScrollArea scrollArea; - private StbTextBox searchBox; - private AlphaBlendControl background; - private SimpleBorder border; - - private HitBox resizeDrag; - private bool dragging = false; - private int dragStartH = 0; - - private List shopItems = new List(); - - private int itemY = 0; - - public ModernShopGump(uint serial, bool isPurchaseGump) : base(serial, 0) - { - #region VARS - X = 200; - Y = 200; - Width = WIDTH; - Height = ProfileManager.CurrentProfile.VendorGumpHeight; - if (Height < 200) - Height = 200; - - AcceptMouseInput = true; - CanCloseWithRightClick = true; - CanMove = true; - - this.isPurchaseGump = isPurchaseGump; - #endregion - - scrollArea = new ScrollArea(1, 75, Width - 2, Height - 77, true) { ScrollbarBehaviour = ScrollbarBehaviour.ShowAlways }; - - Add(background = new AlphaBlendControl(0.75f) { Width = Width, Height = Height, Hue = 997 }); - - Add(new AlphaBlendControl(0.65f) { Width = Width, Height = 75, Hue = 997 }); - - TextBox _; - Add(_ = new TextBox(isPurchaseGump ? "Shop Inventory" : "Your Inventory", TrueTypeLoader.EMBEDDED_FONT, 30, Width, Color.LightBlue, FontStashSharp.RichText.TextHorizontalAlignment.Center, false) { AcceptMouseInput = false }); - _.Y = (50 - _.MeasuredSize.Y) / 2; - - Add(_ = new TextBox("Item", TrueTypeLoader.EMBEDDED_FONT, 20, 75, Color.White, strokeEffect: false) { X = 5, AcceptMouseInput = false }); - _.Y = 55 - _.Height; - - Add(_ = new TextBox("/c[white]Avail.\n/cdPrice per item", TrueTypeLoader.EMBEDDED_FONT, 20, 150, Color.Gold, FontStashSharp.RichText.TextHorizontalAlignment.Right, false) { AcceptMouseInput = false }); - _.Y = 55 - _.Height; - _.X = Width - 1 - _.Width - 5; - - searchBox = new StbTextBox(0xFF, 20, 150, true, FontStyle.None, 0x0481) - { - X = 1, - Y = 55, - Multiline = false, - Width = Width - 1, - Height = 20 - }; - searchBox.TextChanged += (s, e) => - { - SearchContents(searchBox.Text); - }; - searchBox.Add(new AlphaBlendControl(0.5f) - { - Hue = 0x0481, - Width = searchBox.Width, - Height = searchBox.Height - }); - - Add(searchBox); - - Add(scrollArea); - - Add(resizeDrag = new HitBox(Width / 2 - 10, Height - 10, 20, 10, "Drag to resize", 0.50f)); - resizeDrag.Add(new AlphaBlendControl(0.5f) { Width = 20, Height = 10, Hue = 997 }); - resizeDrag.MouseDown += ResizeDrag_MouseDown; - resizeDrag.MouseUp += ResizeDrag_MouseUp; - - Add(border = new SimpleBorder() { Width = Width, Height = Height, Hue = 0, Alpha = 0.3f }); - } - - private void ResizeDrag_MouseUp(object sender, Input.MouseEventArgs e) - { - dragging = false; - } - - private void ResizeDrag_MouseDown(object sender, Input.MouseEventArgs e) - { - dragStartH = Height; - dragging = true; - } - - public override void Update() - { - base.Update(); - - int steps = Mouse.LDragOffset.Y; - - if (dragging && steps != 0) - { - Height = dragStartH + steps; - if (Height < 200) - Height = 200; - ProfileManager.CurrentProfile.VendorGumpHeight = Height; - - background.Height = Height; - scrollArea.Height = Height - 77; - resizeDrag.Y = Height - 10; - border.Height = Height; - } - } - - public void SetNameTo(Item item, string name) - { - if (!string.IsNullOrEmpty(name)) - { - for (int i = 0; i < shopItems.Count; i++) - { - if (shopItems[i].Serial == item.Serial) - { - shopItems[i].SetName(name); - break; - } - } - } - } - - public void AddItem - ( - uint serial, - ushort graphic, - ushort hue, - ushort amount, - uint price, - string name, - bool fromcliloc - ) - { - if (IsDisposed) - return; - ShopItem _ = new ShopItem(serial, graphic, hue, amount, price, name, scrollArea.Width - scrollArea.ScrollBarWidth(), 50, isPurchaseGump, LocalSerial); - _.Y = itemY; - scrollArea.Add(_); - shopItems.Add(_); - itemY += _.Height; - } - - private void SearchContents(string text) - { - text = text.ToLower(); - - List remove = new List(); - foreach (ShopItem i in scrollArea.Children.OfType()) //Remove current shop items - remove.Add(i); - foreach (ShopItem i in remove) - scrollArea.Children.Remove(i); //Actually remove them since we can't modify enumerators - - itemY = 0; //Reset positioning - - foreach (ShopItem i in shopItems) - { - if (i.MatchSearch(text)) - { - i.Y = itemY; - scrollArea.Add(i); - itemY += i.Height; - } - } - } - - private class ShopItem : Control - { - AlphaBlendControl backgound; - Area itemInfo, purchaseSell; - BuySellButton buySellButton; - private readonly bool isPurchase; - private readonly uint gumpSerial; - TextBox textBoxName; - - public ShopItem(uint serial, ushort graphic, ushort hue, int count, uint price, string name, int width, int height, bool isPurchase, uint gumpSerial) - { - Serial = serial; - Graphic = graphic; - Hue = hue; - Count = count; - Price = price; - Name = name; - this.isPurchase = isPurchase; - this.gumpSerial = gumpSerial; - Width = width; - Height = height; - - CanMove = true; - CanCloseWithRightClick = true; - AcceptMouseInput = true; - - SetTooltip(serial); - - Add(backgound = new AlphaBlendControl(0.01f) { Width = Width, Height = Height }); - - itemInfo = new Area(false) { Width = Width - Height, Height = Height, X = Height, AcceptMouseInput = false }; - purchaseSell = new Area(false) { Width = Width - Height, Height = Height, X = Height, AcceptMouseInput = false, IsVisible = false }; - - #region ITEM INFO - TextBox _; - itemInfo.Add(textBoxName = new TextBox(Name, TrueTypeLoader.EMBEDDED_FONT, 25, ITEM_DESCPTION_WIDTH - Height, Color.White, strokeEffect: false) { AcceptMouseInput = false }); - textBoxName.Y = (itemInfo.Height - textBoxName.MeasuredSize.Y) / 2; - - TextBox countTB; - itemInfo.Add(countTB = new TextBox($"x{count}", TrueTypeLoader.EMBEDDED_FONT, 20, ITEM_DESCPTION_WIDTH - Height, Color.WhiteSmoke, FontStashSharp.RichText.TextHorizontalAlignment.Right, false) { Y = 3, AcceptMouseInput = false }); - countTB.X = itemInfo.Width - countTB.Width - 3; - - itemInfo.Add(_ = new TextBox($"{price}gp", TrueTypeLoader.EMBEDDED_FONT, 25, ITEM_DESCPTION_WIDTH - Height, Color.Gold, FontStashSharp.RichText.TextHorizontalAlignment.Right, false) { AcceptMouseInput = false }); - _.Y = itemInfo.Height - _.Height - 3; - _.X = itemInfo.Width - _.Width - 3; - #endregion - - #region PURCHASE OR SELL - purchaseSell.Add(new TextBox($"How many would you like to {(isPurchase ? "buy" : "sell")} at /c[gold]{price}gp /cdeach?", TrueTypeLoader.EMBEDDED_FONT, 18, purchaseSell.Width - 76, Color.White, strokeEffect: false) { AcceptMouseInput = false }); - - AlphaBlendControl sliderBG; - purchaseSell.Add(sliderBG = new AlphaBlendControl(0.5f) { Width = purchaseSell.Width - 78, Height = 5, Hue = 148, BaseColor = Color.White }); - - HSliderBar quantity; - purchaseSell.Add(quantity = new HSliderBar(3, 0, purchaseSell.Width - 78, 1, Count, 1, HSliderBarStyle.BlueWidgetNoBar)); - quantity.Y = purchaseSell.Height - quantity.Height; - sliderBG.Y = quantity.Y + (quantity.Height / 2) - 2; - - quantity.ValueChanged += (sender, e) => - { - buySellButton.UpdateQuantity(quantity.Value, (int)price); - }; - - - purchaseSell.Add(buySellButton = new BuySellButton(isPurchase, 1, (int)price) { X = purchaseSell.Width - 75 }); - - buySellButton.MouseUp += (sender, e) => - { - Dictionary theItem = new Dictionary - { - { serial, (ushort)quantity.Value } - }; - - Tuple[] item = theItem.Select(t => new Tuple(t.Key, (ushort)t.Value)).ToArray(); - - if (isPurchase) - { - NetClient.Socket.Send_BuyRequest(gumpSerial, item); - count -= quantity.Value; - } - else - { - NetClient.Socket.Send_SellRequest(gumpSerial, item); - count -= quantity.Value; - } - - if (count < 1) - Dispose(); - else - { - quantity.MaxValue = count; - quantity.Value = 1; - countTB.Text = $"x{count}"; - - itemInfo.IsVisible ^= true; - purchaseSell.IsVisible ^= true; - } - }; - - #endregion - - Add(itemInfo); - Add(purchaseSell); - - Add(new SimpleBorder() { Width = Width, Height = Height, Hue = 0, Alpha = 0.2f }); - } - - public void SetName(string s) - { - Name = s; - textBoxName.Text = Name; - } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - base.OnMouseDoubleClick(x, y, button); - - if (button == MouseButtonType.Left) - { - if (Keyboard.Shift) - { - Dictionary theItem = new Dictionary - { - { Serial, (ushort)Count } - }; - - Tuple[] item = theItem.Select(t => new Tuple(t.Key, (ushort)t.Value)).ToArray(); - - if (isPurchase) - { - NetClient.Socket.Send_BuyRequest(gumpSerial, item); - } - else - { - NetClient.Socket.Send_SellRequest(gumpSerial, item); - } - Dispose(); - } - else - { - itemInfo.IsVisible ^= true; - purchaseSell.IsVisible ^= true; - } - } - - return true; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (MouseIsOver) - backgound.Alpha = 0.6f; - else - backgound.Alpha = 0.01f; - - base.Draw(batcher, x, y); - - Vector3 hueVector; - - if (isPurchase && SerialHelper.IsMobile(Serial)) - { - ushort graphic = Graphic; - - if (graphic >= 2048) - { - graphic = 0; - } - - byte group = GetAnimGroup(graphic); - var frames = Client.Game.Animations.GetAnimationFrames(graphic, group, 1, out var hue2, out _, true); - - if (frames.Length != 0) - { - hueVector = ShaderHueTranslator.GetHueVector(hue2, TileDataLoader.Instance.StaticData[Graphic].IsPartialHue, 1f); - - ref var spriteInfo = ref frames[0]; - - if (spriteInfo.Texture != null) - { - batcher.Draw - ( - spriteInfo.Texture, - new Rectangle - ( - x, - y, - Math.Min(spriteInfo.UV.Width, Height), - Math.Min(spriteInfo.UV.Height, Height) - ), - spriteInfo.UV, - hueVector - ); - } - } - } - else - { - ref readonly var texture = ref Client.Game.Arts.GetArt((uint)Graphic); - - hueVector = ShaderHueTranslator.GetHueVector(Hue, TileDataLoader.Instance.StaticData[Graphic].IsPartialHue, 1f); - - var rect = Client.Game.Arts.GetRealArtBounds(Graphic); - - Point originalSize = new Point(Height, Height); - Point point = new Point(); - - if (rect.Width < Height) - { - originalSize.X = rect.Width; - point.X = (Height >> 1) - (originalSize.X >> 1); - } - - if (rect.Height < Height) - { - originalSize.Y = rect.Height; - point.Y = (Height >> 1) - (originalSize.Y >> 1); - } - - batcher.Draw - ( - texture.Texture, - new Rectangle - ( - x + point.X, - y + point.Y, - originalSize.X, - originalSize.Y - ), - new Rectangle - ( - texture.UV.X + rect.X, - texture.UV.Y + rect.Y, - rect.Width, - rect.Height - ), - hueVector - ); - } - - return true; - } - - private static byte GetAnimGroup(ushort graphic) - { - var groupType = Client.Game.Animations.GetAnimType(graphic); - switch (AnimationsLoader.Instance.GetGroupIndex(graphic, groupType)) - { - case AnimationGroups.Low: - return (byte)LowAnimationGroup.Stand; - - case AnimationGroups.High: - return (byte)HighAnimationGroup.Stand; - - case AnimationGroups.People: - return (byte)PeopleAnimationGroup.Stand; - } - - return 0; - } - - public bool MatchSearch(string text) - { - if (Name.ToLower().Contains(text)) - return true; - if (World.OPL.TryGetNameAndData(Serial, out string name, out string data)) - { - if (data.ToLower().Contains(text)) - return true; - } - return false; - } - - private class BuySellButton : Control - { - private readonly bool isPurchase; - private TextBox text; - - public BuySellButton(bool isPurchase, int quantity, int price) - { - Width = 75; - Height = 50; - AcceptMouseInput = true; - CanCloseWithRightClick = true; - this.isPurchase = isPurchase; - - Add(new AlphaBlendControl() { Width = Width, Height = Height }); - - UpdateQuantity(quantity, price); - - Add(new SimpleBorder() { Width = Width, Height = Height, Hue = 997, Alpha = 0.2f }); - - } - - public void UpdateQuantity(int quantity, int price) - { - if (text == null) - { - text = new TextBox($"{(isPurchase ? "Buy" : "Sell")}\n{quantity}\n/c[Gold]{price * quantity}", TrueTypeLoader.EMBEDDED_FONT, 17, Width, Color.White, FontStashSharp.RichText.TextHorizontalAlignment.Center, true) { AcceptMouseInput = false }; - Add(text); - } - else - { - text.Text = $"{(isPurchase ? "Buy" : "Sell")}\n{quantity}\n/c[Gold]{price * quantity}"; - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - if (MouseIsOver) - { - batcher.Draw( - SolidColorTextureCache.GetTexture(Color.White), - new Rectangle(x, y, Width, Height), - new Vector3(0, 0, 0.2f) - ); - } - - return true; - } - } - - public uint Serial { get; } - public ushort Graphic { get; } - public ushort Hue { get; } - public int Count { get; set; } - public uint Price { get; } - public string Name { get; set; } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/MultiItemMoveGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/MultiItemMoveGump.cs deleted file mode 100644 index 8eeb9c3ba..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/MultiItemMoveGump.cs +++ /dev/null @@ -1,197 +0,0 @@ -using ClassicUO.Configuration; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using System.Collections.Concurrent; -using System.Threading; -using System.Threading.Tasks; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class MultiItemMoveGump : Gump - { - private Label label; - - public static ConcurrentQueue MoveItems = new ConcurrentQueue(); - - public static int ObjDelay = 1000; - - public MultiItemMoveGump(int x, int y) : base(0, 0) - { - Width = 200; - Height = 100; - - X = x < 0 ? 0 : x; - Y = y < 0 ? 0 : y; - SetInScreen(); - - CanMove = true; - CanCloseWithRightClick = false; - AcceptMouseInput = true; - - ObjDelay = ProfileManager.CurrentProfile.MoveMultiObjectDelay; - - Add(new AlphaBlendControl(0.75f) { Width = Width, Height = Height }); - - Add(label = new Label($"Moving {MoveItems.Count} items.", true, 0xff, Width, align: Assets.TEXT_ALIGN_TYPE.TS_CENTER)); - - Add(new Label($"Object delay:", true, 0xff, 150) { Y = label.Height + 5 }); - StbTextBox delay; - Add(delay = new StbTextBox(0xFF, 3000, 50, true, FontStyle.None, 0x048) - { - X = 150, - Y = label.Height + 5, - Width = 50, - Height = 20, - Multiline = false, - NumbersOnly = true, - }); - delay.SetText(ObjDelay.ToString()); - delay.Add(new AlphaBlendControl(0.5f) - { - Hue = 0x0481, - Width = delay.Width, - Height = delay.Height - }); - delay.TextChanged += (s, e) => - { - if (int.TryParse(delay.Text, out int newDelay)) - { - ObjDelay = newDelay; - ProfileManager.CurrentProfile.MoveMultiObjectDelay = newDelay; - } - }; - - - NiceButton cancel; - Add(cancel = new NiceButton(0, Height - 20, 100, 20, ButtonAction.Default, "Cancel", align: Assets.TEXT_ALIGN_TYPE.TS_CENTER)); - cancel.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - MoveItems = new ConcurrentQueue(); - cancel.Dispose(); - } - }; - - NiceButton move; - Add(move = new NiceButton(100, Height - 20, 100, 20, ButtonAction.Default, "Move to", align: Assets.TEXT_ALIGN_TYPE.TS_CENTER)); - move.SetTooltip("Select a container or a ground tile to move these items to."); - move.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - GameActions.Print("Where should we move these items?"); - TargetManager.SetTargeting(CursorTarget.MoveItemContainer, CursorType.Target, TargetType.Neutral); - delay.IsEditable = false; - } - }; - - NiceButton moveToBackpack; - Add(moveToBackpack = new NiceButton(0, Height - 40, Width, 20, ButtonAction.Default, "Move to backpack", align: Assets.TEXT_ALIGN_TYPE.TS_CENTER)); - moveToBackpack.SetTooltip("Move selected items to your backpack."); - moveToBackpack.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - delay.IsEditable = false; - processItemMoves(World.Player.FindItemByLayer(Data.Layer.Backpack)); - } - }; - - Add(new SimpleBorder() { Width = Width, Height = Height, Alpha = 0.75f }); - } - - public static void OnContainerTarget(uint serial) - { - if (SerialHelper.IsItem(serial)) - { - Item moveToContainer = World.Items.Get(serial); - if (!moveToContainer.ItemData.IsContainer) - { - GameActions.Print("That does not appear to be a container..."); - return; - } - GameActions.Print("Moving items to the selected container.."); - processItemMoves(moveToContainer); - } - } - public static void OnContainerTarget(int x, int y, int z) - { - processItemMoves(x, y, z); - } - - public static void OnTradeWindowTarget(uint tradeID) - { - processItemMoves(tradeID); - } - - public static void AddMultiItemMoveGumpToUI(int x, int y) - { - if (MoveItems.Count > 0) - { - Gump moveItemGump = UIManager.GetGump(); - if (moveItemGump == null) - UIManager.Add(new MultiItemMoveGump(x, y)); - } - } - - private static void processItemMoves(Item container) - { - Task.Factory.StartNew(() => - { - if (container != null) - { - while (MoveItems.TryDequeue(out Item moveItem)) - { - if (GameActions.PickUp(moveItem.Serial, 0, 0, moveItem.Amount)) - GameActions.DropItem(moveItem.Serial, 0xFFFF, 0xFFFF, 0, container); - Task.Delay(ObjDelay).Wait(); - } - - } - }); - } - - private static void processItemMoves(int x, int y, int z) - { - Task.Factory.StartNew(() => - { - while (MoveItems.TryDequeue(out Item moveItem)) - { - Assets.StaticTiles itemData = Assets.TileDataLoader.Instance.StaticData[moveItem.Graphic]; - if (GameActions.PickUp(moveItem.Serial, 0, 0, moveItem.Amount)) - GameActions.DropItem(moveItem.Serial, x, y, z + (sbyte)(itemData.Height == 0xFF ? 0 : itemData.Height), 0); - Task.Delay(ObjDelay).Wait(); - } - }); - } - - private static void processItemMoves(uint tradeID) - { - Task.Factory.StartNew(() => - { - while (MoveItems.TryDequeue(out Item moveItem)) - { - if (GameActions.PickUp(moveItem.Serial, 0, 0, moveItem.Amount)) - GameActions.DropItem(moveItem.Serial, RandomHelper.GetValue(0, 20), RandomHelper.GetValue(0, 20), 0, tradeID); - Task.Delay(ObjDelay).Wait(); - } - }); - } - - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (MoveItems.Count < 1) - Dispose(); - - label.Text = $"Moving {MoveItems.Count} items."; - - return base.Draw(batcher, x, y); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/MultipleToolTipGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/MultipleToolTipGump.cs deleted file mode 100644 index 342eb02dc..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/MultipleToolTipGump.cs +++ /dev/null @@ -1,118 +0,0 @@ -using ClassicUO.Game.UI.Controls; -using ClassicUO.Renderer; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class MultipleToolTipGump : Gump - { - private readonly CustomToolTip[] toolTips; - private readonly Control hoverReference; - - public static bool SSIsEnabled = false; - - public static int SSX, SSY; - public static int SSWidth, SSHeight; - - public MultipleToolTipGump(int x, int y, CustomToolTip[] toolTips, Controls.Control hoverReference) : base(0, 0) - { - this.toolTips = toolTips; - this.hoverReference = hoverReference; - BuildGump(); - WantUpdateSize = true; - - X = x; - Y = y; - - SSIsEnabled = true; - } - - private void BuildGump() - { - for (int i = 0; i < toolTips.Length; i++) - { - if (toolTips[i] == null) - continue; - toolTips[i].OnOPLLoaded += () => { RepositionTooltips(); }; - Add(toolTips[i]); - } - RepositionTooltips(); - } - - private void RepositionTooltips() - { - int x = 0, totalWidth = 0, totalHeight = 0; - for (int i = 0; i < toolTips.Length; i++) - { - if (toolTips[i] == null) - continue; - toolTips[i].X = x; - toolTips[i].Y = 0; - toolTips[i].RemoveHoverReference(); - totalWidth += toolTips[i].Width; - - x += toolTips[i].Width + 14; - - if (totalHeight < toolTips[i].Height) - totalHeight = toolTips[i].Height; - } - ForceSizeUpdate(); - SSWidth = Width + 9; - SSHeight = Height + 9; - } - - private int updateTickCount = 0; - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (!hoverReference.MouseIsOver) - Dispose(); - - if(Height == 0) - { - foreach(Control c in Children) - if (Height < c.Height) - Height = c.Height; - } - - //updateTickCount++; - //if(updateTickCount > 5) - //{ - // RepositionTooltips(); - // updateTickCount = 0; - //} - - int z_width = Width + 24; - int z_height = Height + 8; - - if (x < 0) - { - x = 0; - } - else if (x > Client.Game.Window.ClientBounds.Width - z_width) - { - x = Client.Game.Window.ClientBounds.Width - z_width; - } - - if (y < 0) - { - y = 0; - } - else if (y > Client.Game.Window.ClientBounds.Height - z_height) - { - y = Client.Game.Window.ClientBounds.Height - z_height; - } - - SSX = x - 4; - SSY = y - 2; - - return base.Draw(batcher, x, y); - - } - - public override void Dispose() - { - base.Dispose(); - SSIsEnabled = false; - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/NameOverHeadHandlerGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/NameOverHeadHandlerGump.cs deleted file mode 100644 index 696c4f60d..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/NameOverHeadHandlerGump.cs +++ /dev/null @@ -1,232 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using ClassicUO.Configuration; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Resources; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class NameOverHeadHandlerGump : Gump - { - public static Point? LastPosition; - - public override GumpType GumpType => GumpType.NameOverHeadHandler; - - private readonly List _overheadButtons = new List(); - private Control _alpha; - private readonly Checkbox _keepOpenCheckbox; - private StbTextBox searchBox; - - public NameOverHeadHandlerGump() : base(0, 0) - { - CanMove = true; - AcceptMouseInput = true; - CanCloseWithRightClick = true; - - if (LastPosition == null) - { - X = 100; - Y = 100; - } - else - { - X = LastPosition.Value.X; - Y = LastPosition.Value.Y; - } - - WantUpdateSize = false; - - LayerOrder = UILayer.Over; - - Checkbox stayActive; - Add - ( - _alpha = new AlphaBlendControl(0.7f) - { - Hue = 34 - } - ); - - Add - ( - stayActive = new Checkbox - ( - 0x00D2, - 0x00D3, - "Stay active", - color: 0xFFFF - ) - { - IsChecked = NameOverHeadManager.IsPermaToggled, - } - ); - stayActive.ValueChanged += (sender, e) => { NameOverHeadManager.SetOverheadToggled(stayActive.IsChecked); CanCloseWithRightClick = stayActive.IsChecked; }; - - - Checkbox hideFullHp; - Add - ( - hideFullHp = new Checkbox - ( - 0x00D2, - 0x00D3, - color: 0xFFFF - ) - { - IsChecked = ProfileManager.CurrentProfile.NamePlateHideAtFullHealth, - X = stayActive.Width + stayActive.X + 5 - } - ); - hideFullHp.SetTooltip("Hide nameplates above 100% health."); - hideFullHp.ValueChanged += (sender, e) => { ProfileManager.CurrentProfile.NamePlateHideAtFullHealth = hideFullHp.IsChecked; }; - - - Checkbox hideInWarmode; - Add - ( - hideInWarmode = new Checkbox - ( - 0x00D2, - 0x00D3, - color: 0xFFFF - ) - { - IsChecked = ProfileManager.CurrentProfile.NamePlateHideAtFullHealthInWarmode, - X = hideFullHp.Width + hideFullHp.X + 5 - } - ); - hideInWarmode.SetTooltip("Only hide 100% hp nameplates in warmode."); - hideInWarmode.ValueChanged += (sender, e) => { ProfileManager.CurrentProfile.NamePlateHideAtFullHealthInWarmode = hideInWarmode.IsChecked; }; - - - - Add(new AlphaBlendControl() { Y = stayActive.Height + stayActive.Y, Width = 150, Height = 20, Hue = 0x0481 }); - Add(searchBox = new StbTextBox(0, -1, 150, hue: 0xFFFF) { Y = stayActive.Height + stayActive.Y, Width = 150, Height = 20 }); - searchBox.Text = NameOverHeadManager.Search; - searchBox.TextChanged += (s, e) => { NameOverHeadManager.Search = searchBox.Text; }; - - DrawChoiceButtons(); - } - - public void UpdateCheckboxes() - { - foreach (var button in _overheadButtons) - { - button.IsChecked = NameOverHeadManager.LastActiveNameOverheadOption == button.Text; - } - if (_keepOpenCheckbox != null) - { - _keepOpenCheckbox.IsChecked = NameOverHeadManager.IsPermaToggled; - } - } - - public void RedrawOverheadOptions() - { - foreach (var button in _overheadButtons) - Remove(button); - - DrawChoiceButtons(); - } - - private void DrawChoiceButtons() - { - int biggestWidth = 100; - var options = NameOverHeadManager.GetAllOptions(); - - for (int i = 0; i < options.Count; i++) - { - biggestWidth = Math.Max(biggestWidth, AddOverheadOptionButton(options[i], i).Width); - } - - _alpha.Width = biggestWidth; - _alpha.Height = Math.Max(30, options.Count * 20) + 44; - - Width = _alpha.Width; - Height = _alpha.Height; - } - - private RadioButton AddOverheadOptionButton(NameOverheadOption option, int index) - { - RadioButton button; - - Add - ( - button = new RadioButton - ( - 0, 0x00D0, 0x00D1, option.Name, - color: 0xFFFF - ) - { - Y = 20 * index + 44, - IsChecked = NameOverHeadManager.LastActiveNameOverheadOption == option.Name, - } - ); - - if (button.IsChecked) - { - NameOverHeadManager.SetActiveOption(option); - } - - button.ValueChanged += (sender, e) => - { - if (button.IsChecked) - { - NameOverHeadManager.SetActiveOption(option); - } - }; - - _overheadButtons.Add(button); - - return button; - } - - public override void Dispose() - { - NameOverHeadManager.Search = ""; - base.Dispose(); - } - - protected override void OnDragEnd(int x, int y) - { - LastPosition = new Point(ScreenCoordinateX, ScreenCoordinateY); - - SetInScreen(); - - base.OnDragEnd(x, y); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/NameOverheadGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/NameOverheadGump.cs deleted file mode 100644 index 654e7dd4b..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/NameOverheadGump.cs +++ /dev/null @@ -1,788 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using System; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class NameOverheadGump : Gump - { - private AlphaBlendControl _background; - private Point _lockedPosition, - _lastLeftMousePositionDown; - private bool _positionLocked, - _leftMouseIsDown; - private readonly RenderedText _renderedText; - private Texture2D _borderColor = SolidColorTextureCache.GetTexture(Color.Black); - - public NameOverheadGump(uint serial) : base(serial, 0) - { - CanMove = false; - AcceptMouseInput = true; - CanCloseWithRightClick = true; - - Entity entity = World.Get(serial); - - if (entity == null) - { - Dispose(); - - return; - } - - _renderedText = RenderedText.Create( - string.Empty, - entity is Mobile m ? Notoriety.GetHue(m.NotorietyFlag) : (ushort)0x0481, - 0xFF, - true, - FontStyle.BlackBorder, - TEXT_ALIGN_TYPE.TS_CENTER, - 100, - 30, - true - ); - - SetTooltip(entity); - - BuildGump(); - } - - public bool SetName() - { - Entity entity = World.Get(LocalSerial); - - if (entity == null) - { - return false; - } - - if (entity is Item item) - { - if (!World.OPL.TryGetNameAndData(item, out string t, out _)) - { - if (!item.IsCorpse && item.Amount > 1) - { - t = item.Amount.ToString() + ' '; - } - - if (string.IsNullOrEmpty(item.ItemData.Name)) - { - t += ClilocLoader.Instance.GetString(1020000 + item.Graphic, true, t); - } - else - { - t += StringHelper.CapitalizeAllWords( - StringHelper.GetPluralAdjustedString( - item.ItemData.Name, - item.Amount > 1 - ) - ); - } - } - - if (string.IsNullOrEmpty(t)) - { - return false; - } - - FontsLoader.Instance.SetUseHTML(true); - FontsLoader.Instance.RecalculateWidthByInfo = true; - - int width = FontsLoader.Instance.GetWidthUnicode(_renderedText.Font, t); - - if (width > Constants.OBJECT_HANDLES_GUMP_WIDTH) - { - t = FontsLoader.Instance.GetTextByWidthUnicode( - _renderedText.Font, - t.AsSpan(), - Constants.OBJECT_HANDLES_GUMP_WIDTH, - true, - TEXT_ALIGN_TYPE.TS_CENTER, - (ushort)FontStyle.BlackBorder - ); - - width = Constants.OBJECT_HANDLES_GUMP_WIDTH; - } - - _renderedText.MaxWidth = width; - _renderedText.Text = t; - - FontsLoader.Instance.RecalculateWidthByInfo = false; - FontsLoader.Instance.SetUseHTML(false); - - Width = _background.Width = Math.Max(60, _renderedText.Width) + 4; - Height = _background.Height = Constants.OBJECT_HANDLES_GUMP_HEIGHT + 4; - - WantUpdateSize = false; - - return true; - } - - if (!string.IsNullOrEmpty(entity.Name)) - { - string t = entity.Name; - - int width = FontsLoader.Instance.GetWidthUnicode(_renderedText.Font, t); - - if (width > Constants.OBJECT_HANDLES_GUMP_WIDTH) - { - t = FontsLoader.Instance.GetTextByWidthUnicode( - _renderedText.Font, - t.AsSpan(), - Constants.OBJECT_HANDLES_GUMP_WIDTH, - true, - TEXT_ALIGN_TYPE.TS_CENTER, - (ushort)FontStyle.BlackBorder - ); - - width = Constants.OBJECT_HANDLES_GUMP_WIDTH; - } - - _renderedText.MaxWidth = width; - - _renderedText.Text = t; - - Width = _background.Width = Math.Max(60, _renderedText.Width) + 4; - Height = _background.Height = Constants.OBJECT_HANDLES_GUMP_HEIGHT + 4; - - WantUpdateSize = false; - - return true; - } - - return false; - } - - private void BuildGump() - { - Entity entity = World.Get(LocalSerial); - - if (entity == null) - { - Dispose(); - - return; - } - - Add - ( - _background = new AlphaBlendControl(ProfileManager.CurrentProfile.NamePlateOpacity / 100f) - { - WantUpdateSize = false, - Hue = entity is Mobile m ? Notoriety.GetHue(m.NotorietyFlag) : (ushort)0x0481 - } - ); - } - - protected override void CloseWithRightClick() - { - Entity entity = World.Get(LocalSerial); - - if (entity != null) - { - entity.ObjectHandlesStatus = ObjectHandlesStatus.CLOSED; - } - - base.CloseWithRightClick(); - } - - private void DoDrag() - { - var delta = Mouse.Position - _lastLeftMousePositionDown; - - if ( - Math.Abs(delta.X) <= Constants.MIN_GUMP_DRAG_DISTANCE - && Math.Abs(delta.Y) <= Constants.MIN_GUMP_DRAG_DISTANCE - ) - { - return; - } - - _leftMouseIsDown = false; - _positionLocked = false; - - Entity entity = World.Get(LocalSerial); - - if (entity is Mobile || entity is Item it && it.IsDamageable) - { - if (UIManager.IsDragging) - { - return; - } - - BaseHealthBarGump gump = UIManager.GetGump(LocalSerial); - gump?.Dispose(); - - if (ProfileManager.CurrentProfile.CustomBarsToggled) - { - Rectangle rect = new Rectangle( - 0, - 0, - HealthBarGumpCustom.HPB_WIDTH, - HealthBarGumpCustom.HPB_HEIGHT_SINGLELINE - ); - - UIManager.Add( - gump = new HealthBarGumpCustom(entity) - { - X = Mouse.Position.X - (rect.Width >> 1), - Y = Mouse.Position.Y - (rect.Height >> 1) - } - ); - } - else - { - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(0x0804); - - UIManager.Add( - gump = new HealthBarGump(entity) - { - X = Mouse.LClickPosition.X - (gumpInfo.UV.Width >> 1), - Y = Mouse.LClickPosition.Y - (gumpInfo.UV.Height >> 1) - } - ); - } - - UIManager.AttemptDragControl(gump, true); - } - else if (entity != null) - { - GameActions.PickUp(LocalSerial, 0, 0); - - //if (entity.Texture != null) - // GameActions.PickUp(LocalSerial, entity.Texture.Width >> 1, entity.Texture.Height >> 1); - //else - // GameActions.PickUp(LocalSerial, 0, 0); - } - } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - if (SerialHelper.IsMobile(LocalSerial)) - { - if (World.Player.InWarMode) - { - GameActions.Attack(LocalSerial); - } - else - { - GameActions.DoubleClick(LocalSerial); - } - } - else - { - if (!GameActions.OpenCorpse(LocalSerial)) - { - GameActions.DoubleClick(LocalSerial); - } - } - - return true; - } - - return false; - } - - protected override void OnMouseDown(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - _lastLeftMousePositionDown = Mouse.Position; - _leftMouseIsDown = true; - } - - base.OnMouseDown(x, y, button); - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - _leftMouseIsDown = false; - - if (!Client.Game.GameCursor.ItemHold.Enabled) - { - if ( - UIManager.IsDragging - || Math.Max(Math.Abs(Mouse.LDragOffset.X), Math.Abs(Mouse.LDragOffset.Y)) - >= 1 - ) - { - _positionLocked = false; - - return; - } - } - - if (TargetManager.IsTargeting) - { - switch (TargetManager.TargetingState) - { - case CursorTarget.Internal: - case CursorTarget.Position: - case CursorTarget.Object: - case CursorTarget.Grab: - case CursorTarget.SetGrabBag: - TargetManager.Target(LocalSerial); - Mouse.LastLeftButtonClickTime = 0; - - break; - - case CursorTarget.SetTargetClientSide: - TargetManager.Target(LocalSerial); - Mouse.LastLeftButtonClickTime = 0; - UIManager.Add(new InspectorGump(World.Get(LocalSerial))); - - break; - - case CursorTarget.HueCommandTarget: - CommandManager.OnHueTarget(World.Get(LocalSerial)); - - break; - } - } - else - { - if ( - Client.Game.GameCursor.ItemHold.Enabled - && !Client.Game.GameCursor.ItemHold.IsFixedPosition - ) - { - uint drop_container = 0xFFFF_FFFF; - bool can_drop = false; - ushort dropX = 0; - ushort dropY = 0; - sbyte dropZ = 0; - - Entity obj = World.Get(LocalSerial); - - if (obj != null) - { - can_drop = obj.Distance <= Constants.DRAG_ITEMS_DISTANCE; - - if (can_drop) - { - if (obj is Item it && it.ItemData.IsContainer || obj is Mobile) - { - dropX = 0xFFFF; - dropY = 0xFFFF; - dropZ = 0; - drop_container = obj.Serial; - } - else if ( - obj is Item it2 - && ( - it2.ItemData.IsSurface - || it2.ItemData.IsStackable - && it2.DisplayedGraphic - == Client.Game.GameCursor.ItemHold.DisplayedGraphic - ) - ) - { - dropX = obj.X; - dropY = obj.Y; - dropZ = obj.Z; - - if (it2.ItemData.IsSurface) - { - dropZ += (sbyte)( - it2.ItemData.Height == 0xFF ? 0 : it2.ItemData.Height - ); - } - else - { - drop_container = obj.Serial; - } - } - } - else - { - Client.Game.Audio.PlaySound(0x0051); - } - - if (can_drop) - { - if (drop_container == 0xFFFF_FFFF && dropX == 0 && dropY == 0) - { - can_drop = false; - } - - if (can_drop) - { - GameActions.DropItem( - Client.Game.GameCursor.ItemHold.Serial, - dropX, - dropY, - dropZ, - drop_container - ); - } - } - } - } - else if (!DelayedObjectClickManager.IsEnabled) - { - DelayedObjectClickManager.Set( - LocalSerial, - Mouse.Position.X, - Mouse.Position.Y, - Time.Ticks + Mouse.MOUSE_DELAY_DOUBLE_CLICK - ); - } - } - } - - base.OnMouseUp(x, y, button); - } - - protected override void OnMouseOver(int x, int y) - { - if (_leftMouseIsDown) - { - DoDrag(); - } - - if (!_positionLocked && SerialHelper.IsMobile(LocalSerial)) - { - Mobile m = World.Mobiles.Get(LocalSerial); - - if (m == null) - { - Dispose(); - - return; - } - - _positionLocked = true; - - Client.Game.Animations.GetAnimationDimensions( - m.AnimIndex, - m.GetGraphicForAnimation(), - /*(byte) m.GetDirectionForAnimation()*/ - 0, - /*Mobile.GetGroupForAnimation(m, isParent:true)*/ - 0, - m.IsMounted, - /*(byte) m.AnimIndex*/ - 0, - out int centerX, - out int centerY, - out int width, - out int height - ); - - _lockedPosition.X = (int)(m.RealScreenPosition.X + m.Offset.X + 22 + 5); - - _lockedPosition.Y = (int)( - m.RealScreenPosition.Y - + (m.Offset.Y - m.Offset.Z) - - (height + centerY + 15) - + ( - m.IsGargoyle && m.IsFlying - ? -22 - : !m.IsMounted - ? 22 - : 0 - ) - ); - } - - base.OnMouseOver(x, y); - } - - protected override void OnMouseExit(int x, int y) - { - _positionLocked = false; - base.OnMouseExit(x, y); - } - - public override void Update() - { - base.Update(); - - Entity entity = World.Get(LocalSerial); - - if ( - entity == null - || entity.IsDestroyed - || entity.ObjectHandlesStatus == ObjectHandlesStatus.NONE - || entity.ObjectHandlesStatus == ObjectHandlesStatus.CLOSED - ) - { - Dispose(); - } - else - { - if (entity == TargetManager.LastTargetInfo.Serial) - { - _borderColor = SolidColorTextureCache.GetTexture(Color.Red); - _background.Hue = _renderedText.Hue = entity is Mobile m - ? Notoriety.GetHue(m.NotorietyFlag) - : (ushort)0x0481; - } - else - { - _borderColor = SolidColorTextureCache.GetTexture(Color.Black); - _background.Hue = _renderedText.Hue = entity is Mobile m - ? Notoriety.GetHue(m.NotorietyFlag) - : (ushort)0x0481; - _background.Alpha = ProfileManager.CurrentProfile.NamePlateOpacity / 100f; - } - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (IsDisposed || !SetName()) - { - return false; - } - - bool _isMobile = false; - double _hpPercent = 1; - IsVisible = true; - if (SerialHelper.IsMobile(LocalSerial)) - { - Mobile m = World.Mobiles.Get(LocalSerial); - - if (m == null) - { - Dispose(); - - return false; - } - - if (!string.IsNullOrEmpty(NameOverHeadManager.Search)) - { - string sText = NameOverHeadManager.Search.ToLower(); - if (m.Name == null || !m.Name.ToLower().Contains(sText)) - { - if (World.OPL.TryGetNameAndData(m.Serial, out string name, out string data)) - { - if (/*(data != null && !data.ToLower().Contains(sText)) && */(name != null && !name.ToLower().Contains(sText))) - { - IsVisible = false; - return true; - } - } - else - { - IsVisible = false; - return true; - } - } - } - - _isMobile = true; - _hpPercent = (double)m.Hits / (double)m.HitsMax; - - IsVisible = true; - if (ProfileManager.CurrentProfile.NamePlateHideAtFullHealth && _hpPercent >= 1) - { - if (ProfileManager.CurrentProfile.NamePlateHideAtFullHealthInWarmode) - { - if (World.Player.InWarMode) - { - IsVisible = false; - return false; - } - - } - else - { - IsVisible = false; - return false; - } - - } - - if (_positionLocked) - { - x = _lockedPosition.X; - y = _lockedPosition.Y; - } - else - { - Client.Game.Animations.GetAnimationDimensions( - m.AnimIndex, - m.GetGraphicForAnimation(), - /*(byte) m.GetDirectionForAnimation()*/ - 0, - /*Mobile.GetGroupForAnimation(m, isParent:true)*/ - 0, - m.IsMounted, - /*(byte) m.AnimIndex*/ - 0, - out int centerX, - out int centerY, - out int width, - out int height - ); - - x = (int)(m.RealScreenPosition.X + m.Offset.X + 22 + 5); - y = (int)( - m.RealScreenPosition.Y - + (m.Offset.Y - m.Offset.Z) - - (height + centerY + 15) - + ( - m.IsGargoyle && m.IsFlying - ? -22 - : !m.IsMounted - ? 22 - : 0 - ) - ); - } - } - else if (SerialHelper.IsItem(LocalSerial)) - { - Item item = World.Items.Get(LocalSerial); - - if (item == null) - { - Dispose(); - return false; - } - - if (!string.IsNullOrEmpty(NameOverHeadManager.Search)) - { - string sText = NameOverHeadManager.Search.ToLower(); - if (item.Name == null || !item.Name.ToLower().Contains(sText))// && (!item.ItemData.Name?.ToLower().Contains(sText))) - { - if (World.OPL.TryGetNameAndData(item.Serial, out string name, out string data)) - { - if ((data != null && !data.ToLower().Contains(sText)) && (name != null && !name.ToLower().Contains(sText))) - { - IsVisible = false; - return true; - } - } - else - { - IsVisible = false; - return true; - } - } - } - - var bounds = Client.Game.Arts.GetRealArtBounds(item.Graphic); - - x = item.RealScreenPosition.X + (int)item.Offset.X + 22 + 5; - y = - item.RealScreenPosition.Y - + (int)(item.Offset.Y - item.Offset.Z) - + (bounds.Height >> 1); - } - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - Point p = Client.Game.Scene.Camera.WorldToScreen(new Point(x, y)); - x = p.X - (Width >> 1); - y = p.Y - (Height >> 1); - - var camera = Client.Game.Scene.Camera; - x += camera.Bounds.X; - y += camera.Bounds.Y; - - if (x < camera.Bounds.X || x + Width > camera.Bounds.Right) - { - return false; - } - - if (y < camera.Bounds.Y || y + Height > camera.Bounds.Bottom) - { - return false; - } - - X = x; - Y = y; - - hueVector.Z = ProfileManager.CurrentProfile.NamePlateBorderOpacity / 100f; - - batcher.DrawRectangle - ( - _borderColor, - x - 1, - y - 1, - Width + 1, - Height + 1, - hueVector - ); - - base.Draw(batcher, x, y); - - if (ProfileManager.CurrentProfile.NamePlateHealthBar && _isMobile) - { - batcher.Draw - ( - SolidColorTextureCache.GetTexture(Color.White), - new Vector2(x, y), - new Rectangle(x, y, Math.Min((int)(Width * _hpPercent), Width), Height), - ShaderHueTranslator.GetHueVector(_background.Hue, false, ProfileManager.CurrentProfile.NamePlateHealthBarOpacity / 100f) - ); - } - - int renderedTextOffset = Math.Max(0, Width - _renderedText.Width - 4) >> 1; - - return _renderedText.Draw( - batcher, - Width, - Height, - x + 2 + renderedTextOffset, - y + 2, - Width, - Height, - 0, - 0 - ); - } - - public override void Dispose() - { - _renderedText?.Destroy(); - base.Dispose(); - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/NetworkStatsGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/NetworkStatsGump.cs deleted file mode 100644 index 4da81a229..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/NetworkStatsGump.cs +++ /dev/null @@ -1,210 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Text; -using System.Xml; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Network; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class NetworkStatsGump : Gump - { - private static Point _last_position = new Point(-1, -1); - - private uint _ping, _deltaBytesReceived, _deltaBytesSent; - private uint _time_to_update; - private readonly AlphaBlendControl _trans; - private string _cacheText = string.Empty; - - - public NetworkStatsGump(int x, int y) : base(0, 0) - { - CanMove = true; - CanCloseWithEsc = false; - CanCloseWithRightClick = true; - AcceptMouseInput = true; - AcceptKeyboardInput = false; - - _ping = _deltaBytesReceived = _deltaBytesSent = 0; - - X = _last_position.X <= 0 ? x : _last_position.X; - Y = _last_position.Y <= 0 ? y : _last_position.Y; - Width = 100; - Height = 30; - - Add - ( - _trans = new AlphaBlendControl(.7f) - { - Width = Width, - Height = Height - } - ); - - - LayerOrder = UILayer.Over; - - WantUpdateSize = false; - } - - public override GumpType GumpType => GumpType.NetStats; - - public bool IsMinimized { get; set; } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - IsMinimized = !IsMinimized; - - return true; - } - - return false; - } - - public override void Update() - { - base.Update(); - - if (Time.Ticks > _time_to_update) - { - _time_to_update = Time.Ticks + 100; - - if (NetClient.Socket.IsConnected) - { - _ping = NetClient.Socket.Statistics.Ping; - _deltaBytesReceived = NetClient.Socket.Statistics.DeltaBytesReceived; - _deltaBytesSent = NetClient.Socket.Statistics.DeltaBytesSent; - } - - Span span = stackalloc char[128]; - ValueStringBuilder sb = new ValueStringBuilder(span); - - if (IsMinimized) - { - sb.Append($"Ping: {_ping} ms"); - } - else - { - sb.Append($"Ping: {_ping} ms\n{"In:"} {NetStatistics.GetSizeAdaptive(_deltaBytesReceived),-6} {"Out:"} {NetStatistics.GetSizeAdaptive(_deltaBytesSent),-6}"); - } - - _cacheText = sb.ToString(); - - sb.Dispose(); - - Vector2 size = Fonts.Bold.MeasureString(_cacheText); - - _trans.Width = Width = (int) (size.X + 20); - _trans.Height = Height = (int) (size.Y + 20); - WantUpdateSize = true; - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (!base.Draw(batcher, x, y)) - { - return false; - } - - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - if (_ping < 150) - { - hueVector.X = 0x44; // green - } - else if (_ping < 200) - { - hueVector.X = 0x34; // yellow - } - else if (_ping < 300) - { - hueVector.X = 0x31; // orange - } - else - { - hueVector.X = 0x20; // red - } - - hueVector.Y = 1; - - batcher.DrawString - ( - Fonts.Bold, - _cacheText, - x + 10, - y + 10, - hueVector - ); - - return true; - } - - public override void Save(XmlTextWriter writer) - { - base.Save(writer); - - writer.WriteAttributeString("minimized", IsMinimized.ToString()); - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - - bool.TryParse(xml.GetAttribute("minimized"), out bool b); - IsMinimized = b; - } - - protected override void OnDragEnd(int x, int y) - { - base.OnDragEnd(x, y); - _last_position.X = ScreenCoordinateX; - _last_position.Y = ScreenCoordinateY; - } - - protected override void OnMove(int x, int y) - { - base.OnMove(x, y); - - _last_position.X = ScreenCoordinateX; - _last_position.Y = ScreenCoordinateY; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/OptionsGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/OptionsGump.cs deleted file mode 100644 index 6d38771d5..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/OptionsGump.cs +++ /dev/null @@ -1,6350 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Network; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using System.Threading.Tasks; -using System.Net.Http; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class OptionsGump : Gump - { - private const byte FONT = 0xFF; - private const ushort HUE_FONT = 0xFFFF; - private const int WIDTH = 700; - private const int HEIGHT = 500; - private const int TEXTBOX_HEIGHT = 25; - - private static Texture2D _logoTexture2D; - private Combobox _auraType; - private Combobox _autoOpenCorpseOptions; - private InputField _autoOpenCorpseRange; - - //experimental - private Checkbox _autoOpenDoors, _autoOpenCorpse, _skipEmptyCorpse, _disableTabBtn, _disableCtrlQWBtn, _disableDefaultHotkeys, _disableArrowBtn, _disableAutoMove, _overrideContainerLocation, _smoothDoors, _showTargetRangeIndicator, _customBars, _customBarsBBG, _saveHealthbars; - private HSliderBar _cellSize; - private Checkbox _containerScaleItems, _containerDoubleClickToLoot, _relativeDragAnDropItems, _useLargeContianersGumps, _highlightContainersWhenMouseIsOver, _useGridLayoutContainerGumps; - - - // containers - private HSliderBar _containersScale; - private ModernColorPicker.HueDisplay _altGridContainerBackgroundHue, _gridBorderHue; - private Combobox _cotType; - private DataBox _databox; - private HSliderBar _delay_before_display_tooltip, _tooltip_zoom, _tooltip_background_opacity; - private Combobox _dragSelectModifierKey, _backpackStyle, _gridContainerSearchAlternative, _gridBorderStyle, _dragSelectPlayersModifier, _dragSelectMonsertModifier, _dragSelectNameplateModifier; - private Checkbox _hueContainerGumps, _gridContainerItemScale, _gridContainerPreview, _gridContainerAnchorable, _gridOverrideWithContainerHue; - private HSliderBar _containerOpacity, _gridBorderOpacity, _gridContainerScale; - private InputField _gridDefaultColumns, _gridDefaultRows; - - //counters - private Checkbox _enableCounters, _highlightOnUse, _highlightOnAmount, _enableAbbreviatedAmount; - private Checkbox _enableDragSelect, _dragSelectHumanoidsOnly; - - // sounds - private Checkbox _enableSounds, _enableMusic, _footStepsSound, _combatMusic, _musicInBackground, _loginMusic; - - // fonts - private FontSelector _fontSelectorChat; - private Checkbox _forceUnicodeJournal; - private InputField _gameWindowHeight; - - private Checkbox _gameWindowLock, _gameWindowFullsize; - // GameWindowPosition - private InputField _gameWindowPositionX; - private InputField _gameWindowPositionY; - - // GameWindowSize - private InputField _gameWindowWidth; - private Combobox _gridLoot; - private Checkbox _hideScreenshotStoredInMessage; - private Checkbox _highlightObjects, /*_smoothMovements,*/ - _enablePathfind, - _useShiftPathfind, - _pathFindSingleClick, - _alwaysRun, - _alwaysRunUnlessHidden, - _showHpMobile, - _highlightByPoisoned, - _highlightByParalyzed, - _highlightByInvul, - _drawRoofs, - _treeToStumps, - _hideVegetation, - _noColorOutOfRangeObjects, - _useCircleOfTransparency, - _enableTopbar, - _holdDownKeyTab, - _holdDownKeyAlt, - _closeAllAnchoredGumpsWithRClick, - _chatAfterEnter, - _chatAdditionalButtonsCheckbox, - _chatShiftEnterCheckbox, - _enableCaveBorder; - private Checkbox _holdShiftForContext, _holdShiftToSplitStack, _reduceFPSWhenInactive, _sallosEasyGrab, _partyInviteGump, _objectsFading, _textFading, _holdAltToMoveGumps; - private Combobox _hpComboBox, _healtbarType, _fieldsType, _hpComboBoxShowWhen; - - // infobar - private List _infoBarBuilderControls; - private Combobox _infoBarHighlightType; - - // combat & spells - private ClickableColorBox _innocentColorPickerBox, _friendColorPickerBox, _crimialColorPickerBox, _canAttackColorPickerBox, _enemyColorPickerBox, _murdererColorPickerBox, _neutralColorPickerBox, _beneficColorPickerBox, _harmfulColorPickerBox, _improvedBuffBarHue, - _damageHueSelf, _damageHuePet, _damageHueAlly, _damageHueLastAttack, _damageHueOther; - private HSliderBar _lightBar; - private Checkbox _buffBarTime, _uiButtonsSingleClick, _queryBeforAttackCheckbox, _queryBeforeBeneficialCheckbox, _spellColoringCheckbox, _spellFormatCheckbox, _enableFastSpellsAssign, _enableImprovedBuffGump; - - // macro - private MacroControl _macroControl; - private Checkbox _overrideAllFonts; - private Combobox _overrideAllFontsIsUnicodeCheckbox; - private Combobox _overrideContainerLocationSetting; - private ClickableColorBox _poisonColorPickerBox, _paralyzedColorPickerBox, _invulnerableColorPickerBox; - private NiceButton _randomizeColorsButton; - private Checkbox _restorezoomCheckbox, _zoomCheckbox; - private InputField _rows, _columns, _highlightAmount, _abbreviatedAmount; - - // speech - private Checkbox _scaleSpeechDelay, _saveJournalCheckBox; - private Checkbox _showHouseContent; - private Checkbox _showInfoBar; - private Checkbox _ignoreAllianceMessages; - private Checkbox _ignoreGuildMessages; - - // general - private HSliderBar _sliderFPS, _circleOfTranspRadius; - private HSliderBar _sliderSpeechDelay; - private HSliderBar _sliderZoom; - private HSliderBar _soundsVolume, _musicVolume, _loginMusicVolume; - private HSliderBar _hiddenBodyAlpha; - private ClickableColorBox _hiddenBodyHue; - private ClickableColorBox _speechColorPickerBox, _emoteColorPickerBox, _yellColorPickerBox, _whisperColorPickerBox, _partyMessageColorPickerBox, _guildMessageColorPickerBox, _allyMessageColorPickerBox, _chatMessageColorPickerBox, _partyAuraColorPickerBox; - private InputField _spellFormatBox, _autoFollowDistance, _modernPaperdollDurabilityPercent; - private ClickableColorBox _tooltip_font_hue; - private FontSelector _tooltip_font_selector; - private HSliderBar _dragSelectStartX, _dragSelectStartY; - private Checkbox _dragSelectAsAnchor, _namePlateHealthBar, _disableSystemChat, _namePlateShowAtFullHealth, _useModernPaperdoll; - private HSliderBar _journalOpacity, _namePlateOpacity, _namePlateHealthBarOpacity; - private ClickableColorBox _journalBackgroundColor; - private Combobox _journalStyle; - private ModernColorPicker.HueDisplay _paperDollHue, _durabilityBarHue; - - private NameOverheadAssignControl _nameOverheadControl; - - // video - private Checkbox _use_old_status_gump, _windowBorderless, _enableDeathScreen, _enableBlackWhiteEffect, _altLights, _enableLight, _enableShadows, _enableShadowsStatics, _auraMouse, _runMouseInSeparateThread, _useColoredLights, _darkNights, _partyAura, _hideChatGradient, _animatedWaterEffect; - private Combobox _lightLevelType; - private Checkbox _use_smooth_boat_movement; - private HSliderBar _terrainShadowLevel; - - private Checkbox _use_tooltip; - private Checkbox _useStandardSkillsGump, _showMobileNameIncoming, _showCorpseNameIncoming; - private Checkbox _showStatsMessage, _showSkillsMessage, _displayPartyChatOverhead; - private HSliderBar _showSkillsMessageDelta; - - private Checkbox _leftAlignToolTips, _namePlateHealthOnlyWarmode, _enableHealthIndicator, _spellIconDisplayHotkey, _enableAlphaScrollWheel, _useModernShop, _forceCenterAlignMobileTooltips, _openHealthBarForLastAttack; - private Checkbox _hideJournalBorder, _hideJournalTimestamp, _gridHideBorder, _skillProgressBarOnChange, _displaySpellIndicators, _uselastCooldownPosition, _closeHPBarWhenAnchored; - private InputField _healthIndicatorPercentage, _healthIndicatorWidth, _tooltipHeaderFormat, _skillProgressBarFormat; - private ModernColorPicker.HueDisplay _mainWindowHuePicker, _spellIconHotkeyHue, _tooltipBGHue; - private HSliderBar _spellIconScale, _journalFontSize, _tooltipFontSize, _gameWindowSideChatFontSize, _overheadFontSize, _overheadTextWidth, _textStrokeSize, _gridHightlightLineSize, _maxJournalEntries; - private HSliderBar _healthLineSizeMultiplier, _regularPlayerAlpha, _infoBarFontSize, _nameplateBorderOpacity; - private Combobox _journalFontSelection, _tooltipFontSelect, _gameWindowSideChatFont, _overheadFont, _infoBarFont; - - #region Cooldowns - private InputField _coolDownX, _coolDownY; - #endregion - - - private Profile _currentProfile = ProfileManager.CurrentProfile; - - public OptionsGump() : base(0, 0) - { - Add - ( - new AlphaBlendControl(0.95f) - { - X = 1, - Y = 1, - Width = WIDTH - 2, - Height = HEIGHT - 2, - Hue = 999 - } - ); - - - int i = 0; - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - ResGumps.General - ) - { IsSelected = true, ButtonParameter = 1 } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - ResGumps.Sound - ) - { ButtonParameter = 2 } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - ResGumps.Video - ) - { ButtonParameter = 3 } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - ResGumps.Macros - ) - { ButtonParameter = 4 } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - ResGumps.Tooltip - ) - { ButtonParameter = 5 } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - ResGumps.Fonts - ) - { ButtonParameter = 6 } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - ResGumps.Speech - ) - { ButtonParameter = 7 } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - ResGumps.CombatSpells - ) - { ButtonParameter = 8 } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - ResGumps.Counters - ) - { ButtonParameter = 9 } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - ResGumps.InfoBar - ) - { ButtonParameter = 10 } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - ResGumps.Containers - ) - { ButtonParameter = 11 } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - ResGumps.Experimental - ) - { ButtonParameter = 12 } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.Activate, - ResGumps.IgnoreListManager - ) - { - ButtonParameter = (int)Buttons.OpenIgnoreList - } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - "Nameplate Options" - ) - { - ButtonParameter = 13 - } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - "Cooldowns (TUO)" - ) - { - ButtonParameter = 8787 - } - ); - - Add - ( - new NiceButton - ( - 10, - 10 + 30 * i++, - 140, - 25, - ButtonAction.SwitchPage, - "TazUO" - ) - { - ButtonParameter = 8788 - } - ); - - Add - ( - new Line - ( - 160, - 5, - 1, - HEIGHT - 10, - Color.Gray.PackedValue - ) - ); - - int offsetX = 60; - int offsetY = 60; - - Add - ( - new Line - ( - 160, - 405 + 35 + 1, - WIDTH - 160, - 1, - Color.Gray.PackedValue - ) - ); - - Add - ( - new Button((int)Buttons.Cancel, 0x00F3, 0x00F1, 0x00F2) - { - X = 154 + offsetX, - Y = 405 + offsetY, - ButtonAction = ButtonAction.Activate - } - ); - - Add - ( - new Button((int)Buttons.Apply, 0x00EF, 0x00F0, 0x00EE) - { - X = 248 + offsetX, - Y = 405 + offsetY, - ButtonAction = ButtonAction.Activate - } - ); - - Add - ( - new Button((int)Buttons.Default, 0x00F6, 0x00F4, 0x00F5) - { - X = 346 + offsetX, - Y = 405 + offsetY, - ButtonAction = ButtonAction.Activate - } - ); - - Add - ( - new Button((int)Buttons.Ok, 0x00F9, 0x00F8, 0x00F7) - { - X = 443 + offsetX, - Y = 405 + offsetY, - ButtonAction = ButtonAction.Activate - } - ); - - AcceptMouseInput = true; - CanMove = true; - CanCloseWithRightClick = true; - - BuildGeneral(); - BuildSounds(); - BuildVideo(); - BuildCommands(); - BuildFonts(); - BuildSpeech(); - BuildCombat(); - BuildTooltip(); - BuildCounters(); - BuildInfoBar(); - BuildContainers(); - BuildExperimental(); - BuildNameOverhead(); - BuildCooldowns(); - BuildTazUO(); - - ChangePage(1); - } - - private static Texture2D LogoTexture - { - get - { - if (_logoTexture2D == null || _logoTexture2D.IsDisposed) - { - using var stream = new MemoryStream(Loader.GetCuoLogo().ToArray()); - _logoTexture2D = Texture2D.FromStream(Client.Game.GraphicsDevice, stream); - } - - return _logoTexture2D; - } - } - - private void BuildGeneral() - { - const int PAGE = 1; - - ScrollArea rightArea = new ScrollArea - ( - 190, - 20, - WIDTH - 210, - 420, - true - ); - - int startX = 5; - int startY = 5; - - - DataBox box = new DataBox(startX, startY, rightArea.Width - 15, 1); - box.WantUpdateSize = true; - rightArea.Add(box); - - - SettingsSection section = AddSettingsSection(box, "General"); - - - section.Add - ( - _highlightObjects = AddCheckBox - ( - null, - ResGumps.HighlightObjects, - _currentProfile.HighlightGameObjects, - startX, - startY - ) - ); - - section.Add - ( - _enablePathfind = AddCheckBox - ( - null, - ResGumps.EnablePathfinding, - _currentProfile.EnablePathfind, - startX, - startY - ) - ); - - section.AddRight - ( - _useShiftPathfind = AddCheckBox - ( - null, - ResGumps.ShiftPathfinding, - _currentProfile.UseShiftToPathfind, - startX, - startY - ) - ); - - section.AddRight - ( - _pathFindSingleClick = AddCheckBox - ( - null, - "Single click", - _currentProfile.PathfindSingleClick, - startX, - startY - ) - ); - - section.Add - ( - _alwaysRun = AddCheckBox - ( - null, - ResGumps.AlwaysRun, - _currentProfile.AlwaysRun, - startX, - startY - ) - ); - - section.AddRight - ( - _alwaysRunUnlessHidden = AddCheckBox - ( - null, - ResGumps.AlwaysRunHidden, - _currentProfile.AlwaysRunUnlessHidden, - startX, - startY - ) - ); - - section.Add - ( - _autoOpenDoors = AddCheckBox - ( - null, - ResGumps.AutoOpenDoors, - _currentProfile.AutoOpenDoors, - startX, - startY - ) - ); - - section.AddRight - ( - _smoothDoors = AddCheckBox - ( - null, - ResGumps.SmoothDoors, - _currentProfile.SmoothDoors, - startX, - startY - ) - ); - - section.Add - ( - _autoOpenCorpse = AddCheckBox - ( - null, - ResGumps.AutoOpenCorpses, - _currentProfile.AutoOpenCorpses, - startX, - startY - ) - ); - - section.PushIndent(); - section.Add(AddLabel(null, ResGumps.CorpseOpenRange, 0, 0)); - - section.AddRight - ( - _autoOpenCorpseRange = AddInputField - ( - null, - startX, - startY, - 50, - TEXTBOX_HEIGHT, - ResGumps.CorpseOpenRange, - 50, - false, - true, - 5 - ) - ); - - _autoOpenCorpseRange.SetText(_currentProfile.AutoOpenCorpseRange.ToString()); - - section.Add - ( - _skipEmptyCorpse = AddCheckBox - ( - null, - ResGumps.SkipEmptyCorpses, - _currentProfile.SkipEmptyCorpse, - startX, - startY - ) - ); - - section.Add(AddLabel(null, ResGumps.CorpseOpenOptions, startX, startY)); - - section.AddRight - ( - _autoOpenCorpseOptions = AddCombobox - ( - null, - new[] - { - ResGumps.CorpseOpt_None, ResGumps.CorpseOpt_NotTar, ResGumps.CorpseOpt_NotHid, - ResGumps.CorpseOpt_Both - }, - _currentProfile.CorpseOpenOptions, - startX, - startY, - 150 - ), - 2 - ); - - section.PopIndent(); - - section.Add - ( - _noColorOutOfRangeObjects = AddCheckBox - ( - rightArea, - ResGumps.OutOfRangeColor, - _currentProfile.NoColorObjectsOutOfRange, - startX, - startY - ) - ); - - section.Add - ( - _sallosEasyGrab = AddCheckBox - ( - null, - ResGumps.SallosEasyGrab, - _currentProfile.SallosEasyGrab, - startX, - startY - ) - ); - - section.Add - ( - _showHouseContent = AddCheckBox - ( - null, - ResGumps.ShowHousesContent, - _currentProfile.ShowHouseContent, - startX, - startY - ) - ); - - _showHouseContent.IsVisible = Client.Version >= ClientVersion.CV_70796; - - section.Add - ( - _use_smooth_boat_movement = AddCheckBox - ( - null, - ResGumps.SmoothBoat, - _currentProfile.UseSmoothBoatMovement, - startX, - startY - ) - ); - - _use_smooth_boat_movement.IsVisible = Client.Version >= ClientVersion.CV_7090; - - SettingsSection section2 = AddSettingsSection(box, "Mobiles"); - section2.Y = section.Bounds.Bottom + 40; - - section2.Add - ( - _showHpMobile = AddCheckBox - ( - null, - ResGumps.ShowHP, - _currentProfile.ShowMobilesHP, - startX, - startY - ) - ); - - int mode = _currentProfile.MobileHPType; - - if (mode < 0 || mode > 2) - { - mode = 0; - } - - section2.AddRight - ( - _hpComboBox = AddCombobox - ( - null, - new[] { ResGumps.HP_Percentage, ResGumps.HP_Line, ResGumps.HP_Both }, - mode, - startX, - startY, - 100 - ) - ); - - section2.AddRight(AddLabel(null, ResGumps.HP_Mode, startX, startY)); - - mode = _currentProfile.MobileHPShowWhen; - - if (mode != 0 && mode > 2) - { - mode = 0; - } - - section2.AddRight - ( - _hpComboBoxShowWhen = AddCombobox - ( - null, - new[] { ResGumps.HPShow_Always, ResGumps.HPShow_Less, ResGumps.HPShow_Smart }, - mode, - startX, - startY, - 100 - ), - 2 - ); - - section2.Add - ( - _highlightByPoisoned = AddCheckBox - ( - null, - ResGumps.HighlightPoisoned, - _currentProfile.HighlightMobilesByPoisoned, - startX, - startY - ) - ); - - section2.PushIndent(); - - section2.Add - ( - _poisonColorPickerBox = AddColorBox - ( - null, - startX, - startY, - _currentProfile.PoisonHue, - ResGumps.PoisonedColor - ) - ); - - section2.AddRight(AddLabel(null, ResGumps.PoisonedColor, 0, 0), 2); - section2.PopIndent(); - - section2.Add - ( - _highlightByParalyzed = AddCheckBox - ( - null, - ResGumps.HighlightParalyzed, - _currentProfile.HighlightMobilesByParalize, - startX, - startY - ) - ); - - section2.PushIndent(); - - section2.Add - ( - _paralyzedColorPickerBox = AddColorBox - ( - null, - startX, - startY, - _currentProfile.ParalyzedHue, - ResGumps.ParalyzedColor - ) - ); - - section2.AddRight(AddLabel(null, ResGumps.ParalyzedColor, 0, 0), 2); - - section2.PopIndent(); - - section2.Add - ( - _highlightByInvul = AddCheckBox - ( - null, - ResGumps.HighlightInvulnerable, - _currentProfile.HighlightMobilesByInvul, - startX, - startY - ) - ); - - section2.PushIndent(); - - section2.Add - ( - _invulnerableColorPickerBox = AddColorBox - ( - null, - startX, - startY, - _currentProfile.InvulnerableHue, - ResGumps.InvulColor - ) - ); - - section2.AddRight(AddLabel(null, ResGumps.InvulColor, 0, 0), 2); - section2.PopIndent(); - - section2.Add - ( - _showMobileNameIncoming = AddCheckBox - ( - null, - ResGumps.ShowIncMobiles, - _currentProfile.ShowNewMobileNameIncoming, - startX, - startY - ) - ); - - section2.Add - ( - _showCorpseNameIncoming = AddCheckBox - ( - null, - ResGumps.ShowIncCorpses, - _currentProfile.ShowNewCorpseNameIncoming, - startX, - startY - ) - ); - - section2.Add(AddLabel(null, ResGumps.AuraUnderFeet, startX, startY)); - - section2.AddRight - ( - _auraType = AddCombobox - ( - null, - new[] - { - ResGumps.AuraType_None, ResGumps.AuraType_Warmode, ResGumps.AuraType_CtrlShift, - ResGumps.AuraType_Always - }, - _currentProfile.AuraUnderFeetType, - startX, - startY, - 100 - ), - 2 - ); - - section2.PushIndent(); - - section2.Add - ( - _partyAura = AddCheckBox - ( - null, - ResGumps.CustomColorAuraForPartyMembers, - _currentProfile.PartyAura, - startX, - startY - ) - ); - - section2.PushIndent(); - - section2.Add - ( - _partyAuraColorPickerBox = AddColorBox - ( - null, - startX, - startY, - _currentProfile.PartyAuraHue, - ResGumps.PartyAuraColor - ) - ); - - section2.AddRight(AddLabel(null, ResGumps.PartyAuraColor, 0, 0)); - - section2.PopIndent(); - section2.PopIndent(); - - SettingsSection section3 = AddSettingsSection(box, "Gumps & Context"); - section3.Y = section2.Bounds.Bottom + 40; - - section3.Add - ( - _enableTopbar = AddCheckBox - ( - null, - ResGumps.DisableMenu, - _currentProfile.TopbarGumpIsDisabled, - 0, - 0 - ) - ); - - section3.Add - ( - _holdDownKeyAlt = AddCheckBox - ( - null, - ResGumps.AltCloseGumps, - _currentProfile.HoldDownKeyAltToCloseAnchored, - 0, - 0 - ) - ); - - section3.Add - ( - _holdAltToMoveGumps = AddCheckBox - ( - null, - ResGumps.AltMoveGumps, - _currentProfile.HoldAltToMoveGumps, - 0, - 0 - ) - ); - - section3.Add - ( - _closeAllAnchoredGumpsWithRClick = AddCheckBox - ( - null, - ResGumps.ClickCloseAllGumps, - _currentProfile.CloseAllAnchoredGumpsInGroupWithRightClick, - 0, - 0 - ) - ); - - section3.Add - ( - _useStandardSkillsGump = AddCheckBox - ( - null, - ResGumps.StandardSkillGump, - _currentProfile.StandardSkillsGump, - 0, - 0 - ) - ); - - section3.Add - ( - _use_old_status_gump = AddCheckBox - ( - null, - ResGumps.UseOldStatusGump, - _currentProfile.UseOldStatusGump, - startX, - startY - ) - ); - - _use_old_status_gump.IsVisible = !CUOEnviroment.IsOutlands; - - section3.Add - ( - _partyInviteGump = AddCheckBox - ( - null, - ResGumps.ShowGumpPartyInv, - _currentProfile.PartyInviteGump, - 0, - 0 - ) - ); - - section3.Add - ( - _customBars = AddCheckBox - ( - null, - ResGumps.UseCustomHPBars, - _currentProfile.CustomBarsToggled, - 0, - 0 - ) - ); - - section3.AddRight - ( - _customBarsBBG = AddCheckBox - ( - null, - ResGumps.UseBlackBackgr, - _currentProfile.CBBlackBGToggled, - 0, - 0 - ) - ); - - section3.Add - ( - _saveHealthbars = AddCheckBox - ( - null, - ResGumps.SaveHPBarsOnLogout, - _currentProfile.SaveHealthbars, - 0, - 0 - ) - ); - - section3.PushIndent(); - section3.Add(AddLabel(null, ResGumps.CloseHPGumpWhen, 0, 0)); - - mode = _currentProfile.CloseHealthBarType; - - if (mode < 0 || mode > 2) - { - mode = 0; - } - - _healtbarType = AddCombobox - ( - null, - new[] { ResGumps.HPType_None, ResGumps.HPType_MobileOOR, ResGumps.HPType_MobileDead }, - mode, - 0, - 0, - 150 - ); - - section3.AddRight(_healtbarType); - section3.PopIndent(); - section3.Add(AddLabel(null, ResGumps.GridLoot, startX, startY)); - - section3.AddRight - ( - _gridLoot = AddCombobox - ( - null, - new[] { ResGumps.GridLoot_None, ResGumps.GridLoot_GridOnly, ResGumps.GridLoot_Both }, - _currentProfile.GridLootType, - startX, - startY, - 120 - ), - 2 - ); - - section3.Add - ( - _holdShiftForContext = AddCheckBox - ( - null, - ResGumps.ShiftContext, - _currentProfile.HoldShiftForContext, - 0, - 0 - ) - ); - - section3.Add - ( - _holdShiftToSplitStack = AddCheckBox - ( - null, - ResGumps.ShiftStack, - _currentProfile.HoldShiftToSplitStack, - 0, - 0 - ) - ); - - - SettingsSection section4 = AddSettingsSection(box, "Miscellaneous"); - section4.Y = section3.Bounds.Bottom + 40; - - section4.Add - ( - _useCircleOfTransparency = AddCheckBox - ( - null, - ResGumps.EnableCircleTrans, - _currentProfile.UseCircleOfTransparency, - startX, - startY - ) - ); - - section4.AddRight - ( - _circleOfTranspRadius = AddHSlider - ( - null, - Constants.MIN_CIRCLE_OF_TRANSPARENCY_RADIUS, - Constants.MAX_CIRCLE_OF_TRANSPARENCY_RADIUS, - _currentProfile.CircleOfTransparencyRadius, - startX, - startY, - 200 - ) - ); - - section4.PushIndent(); - section4.Add(AddLabel(null, ResGumps.CircleTransType, startX, startY)); - int cottypeindex = _currentProfile.CircleOfTransparencyType; - string[] cotTypes = { ResGumps.CircleTransType_Full, ResGumps.CircleTransType_Gradient, "Modern" }; - - if (cottypeindex < 0 || cottypeindex > cotTypes.Length) - { - cottypeindex = 0; - } - - section4.AddRight - ( - _cotType = AddCombobox - ( - null, - cotTypes, - cottypeindex, - startX, - startY, - 150 - ), - 2 - ); - - section4.PopIndent(); - - section4.Add - ( - _hideScreenshotStoredInMessage = AddCheckBox - ( - null, - ResGumps.HideScreenshotStoredInMessage, - _currentProfile.HideScreenshotStoredInMessage, - 0, - 0 - ) - ); - - section4.Add - ( - _objectsFading = AddCheckBox - ( - null, - ResGumps.ObjAlphaFading, - _currentProfile.UseObjectsFading, - startX, - startY - ) - ); - - section4.Add - ( - _textFading = AddCheckBox - ( - null, - ResGumps.TextAlphaFading, - _currentProfile.TextFading, - startX, - startY - ) - ); - - section4.Add - ( - _showTargetRangeIndicator = AddCheckBox - ( - null, - ResGumps.ShowTarRangeIndic, - _currentProfile.ShowTargetRangeIndicator, - startX, - startY - ) - ); - - section4.Add - ( - _enableDragSelect = AddCheckBox - ( - null, - ResGumps.EnableDragHPBars, - _currentProfile.EnableDragSelect, - startX, - startY - ) - ); - - section4.PushIndent(); - section4.Add(AddLabel(null, ResGumps.DragKey, startX, startY)); - - section4.AddRight - ( - _dragSelectModifierKey = AddCombobox - ( - null, - new[] { ResGumps.KeyMod_None, ResGumps.KeyMod_Ctrl, ResGumps.KeyMod_Shift }, - _currentProfile.DragSelectModifierKey, - startX, - startY, - 100 - ) - ); - - section4.Add(AddLabel(null, "Select players key", 0, 0)); - section4.AddRight(_dragSelectPlayersModifier = AddCombobox( - null, new[] { "Disabled", "Ctrl", "Shift" }, - _currentProfile.DragSelect_PlayersModifier, - 0, 0, 100 - )); - - section4.Add(AddLabel(null, "Select monsters key", 0, 0)); - section4.AddRight(_dragSelectMonsertModifier = AddCombobox( - null, new[] { "Disabled", "Ctrl", "Shift" }, - _currentProfile.DragSelect_MonstersModifier, - 0, 0, 100 - )); - - section4.Add(AddLabel(null, "Select visible nameplates key", 0, 0)); - section4.AddRight(_dragSelectNameplateModifier = AddCombobox( - null, new[] { "Disabled", "Ctrl", "Shift" }, - _currentProfile.DragSelect_NameplateModifier, - 0, 0, 100 - )); - - //section4.Add - //( - // _dragSelectHumanoidsOnly = AddCheckBox - // ( - // null, - // ResGumps.DragHumanoidsOnly, - // _currentProfile.DragSelectHumanoidsOnly, - // startX, - // startY - // ) - //); - - section4.Add(new Label(ResGumps.DragSelectStartingPosX, true, HUE_FONT)); - section4.Add(_dragSelectStartX = new HSliderBar(startX, startY, 200, 0, Client.Game.Scene.Camera.Bounds.Width, _currentProfile.DragSelectStartX, HSliderBarStyle.MetalWidgetRecessedBar, true, 0, HUE_FONT)); - - section4.Add(new Label(ResGumps.DragSelectStartingPosY, true, HUE_FONT)); - section4.Add(_dragSelectStartY = new HSliderBar(startX, startY, 200, 0, Client.Game.Scene.Camera.Bounds.Height, _currentProfile.DragSelectStartY, HSliderBarStyle.MetalWidgetRecessedBar, true, 0, HUE_FONT)); - section4.Add - ( - _dragSelectAsAnchor = AddCheckBox - ( - null, ResGumps.DragSelectAnchoredHB, _currentProfile.DragSelectAsAnchor, startX, - startY - ) - ); - - section4.PopIndent(); - - section4.Add - ( - _showStatsMessage = AddCheckBox - ( - null, - ResGumps.ShowStatsChangedMessage, - _currentProfile.ShowStatsChangedMessage, - startX, - startY - ) - ); - - section4.Add - ( - _showSkillsMessage = AddCheckBox - ( - null, - ResGumps.ShowSkillsChangedMessageBy, - _currentProfile.ShowStatsChangedMessage, - startX, - startY - ) - ); - - section4.PushIndent(); - - section4.AddRight - ( - _showSkillsMessageDelta = AddHSlider - ( - null, - 0, - 100, - _currentProfile.ShowSkillsChangedDeltaValue, - startX, - startY, - 150 - ) - ); - - section4.PopIndent(); - - SettingsSection section5 = AddSettingsSection(box, "Terrain & Statics"); - section5.Y = section4.Bounds.Bottom + 40; - - section5.Add - ( - _drawRoofs = AddCheckBox - ( - null, - ResGumps.HideRoofTiles, - !_currentProfile.DrawRoofs, - startX, - startY - ) - ); - - section5.Add - ( - _treeToStumps = AddCheckBox - ( - null, - ResGumps.TreesStumps, - _currentProfile.TreeToStumps, - startX, - startY - ) - ); - - section5.Add - ( - _hideVegetation = AddCheckBox - ( - null, - ResGumps.HideVegetation, - _currentProfile.HideVegetation, - startX, - startY - ) - ); - - section5.Add - ( - _enableCaveBorder = AddCheckBox - ( - null, - ResGumps.MarkCaveTiles, - _currentProfile.EnableCaveBorder, - startX, - startY - ) - ); - - section5.Add(AddLabel(null, ResGumps.HPFields, startX, startY)); - mode = _currentProfile.FieldsType; - - if (mode < 0 || mode > 2) - { - mode = 0; - } - - section5.AddRight - ( - _fieldsType = AddCombobox - ( - null, - new[] { ResGumps.HPFields_Normal, ResGumps.HPFields_Static, ResGumps.HPFields_Tile }, - mode, - startX, - startY, - 150 - ) - ); - - - Add(rightArea, PAGE); - } - - private void BuildSounds() - { - const int PAGE = 2; - - ScrollArea rightArea = new ScrollArea - ( - 190, - 20, - WIDTH - 210, - 420, - true - ); - - int startX = 5; - int startY = 5; - - const int VOLUME_WIDTH = 200; - - _enableSounds = AddCheckBox - ( - rightArea, - ResGumps.Sounds, - _currentProfile.EnableSound, - startX, - startY - ); - - _enableMusic = AddCheckBox - ( - rightArea, - ResGumps.Music, - _currentProfile.EnableMusic, - startX, - startY + _enableSounds.Height + 2 - ); - - _loginMusic = AddCheckBox - ( - rightArea, - ResGumps.LoginMusic, - Settings.GlobalSettings.LoginMusic, - startX, - startY + _enableSounds.Height + 2 + _enableMusic.Height + 2 - ); - - startX = 120; - startY += 2; - - _soundsVolume = AddHSlider - ( - rightArea, - 0, - 100, - _currentProfile.SoundVolume, - startX, - startY, - VOLUME_WIDTH - ); - - _musicVolume = AddHSlider - ( - rightArea, - 0, - 100, - _currentProfile.MusicVolume, - startX, - startY + _enableSounds.Height + 2, - VOLUME_WIDTH - ); - - _loginMusicVolume = AddHSlider - ( - rightArea, - 0, - 100, - Settings.GlobalSettings.LoginMusicVolume, - startX, - startY + _enableSounds.Height + 2 + _enableMusic.Height + 2, - VOLUME_WIDTH - ); - - startX = 5; - startY += _loginMusic.Bounds.Bottom + 2; - - _footStepsSound = AddCheckBox - ( - rightArea, - ResGumps.PlayFootsteps, - _currentProfile.EnableFootstepsSound, - startX, - startY - ); - - startY += _footStepsSound.Height + 2; - - _combatMusic = AddCheckBox - ( - rightArea, - ResGumps.CombatMusic, - _currentProfile.EnableCombatMusic, - startX, - startY - ); - - startY += _combatMusic.Height + 2; - - _musicInBackground = AddCheckBox - ( - rightArea, - ResGumps.ReproduceSoundsAndMusic, - _currentProfile.ReproduceSoundsInBackground, - startX, - startY - ); - - startY += _musicInBackground.Height + 2; - - Add(rightArea, PAGE); - } - - private void BuildVideo() - { - const int PAGE = 3; - - ScrollArea rightArea = new ScrollArea - ( - 190, - 20, - WIDTH - 210, - 420, - true - ); - - int startX = 5; - int startY = 5; - - - Label text = AddLabel(rightArea, ResGumps.FPS, startX, startY); - startX += text.Bounds.Right + 5; - - _sliderFPS = AddHSlider - ( - rightArea, - Constants.MIN_FPS, - Constants.MAX_FPS, - Settings.GlobalSettings.FPS, - startX, - startY, - 250 - ); - - startY += text.Bounds.Bottom + 5; - - _reduceFPSWhenInactive = AddCheckBox - ( - rightArea, - ResGumps.FPSInactive, - _currentProfile.ReduceFPSWhenInactive, - startX, - startY - ); - - startY += _reduceFPSWhenInactive.Height + 2; - - startX = 5; - startY += 20; - - - DataBox box = new DataBox(startX, startY, rightArea.Width - 15, 1); - box.WantUpdateSize = true; - rightArea.Add(box); - - SettingsSection section = AddSettingsSection(box, "Game window"); - - section.Add - ( - _gameWindowFullsize = AddCheckBox - ( - null, - ResGumps.AlwaysUseFullsizeGameWindow, - _currentProfile.GameWindowFullSize, - startX, - startY - ) - ); - - section.Add - ( - _windowBorderless = AddCheckBox - ( - null, - ResGumps.BorderlessWindow, - _currentProfile.WindowBorderless, - startX, - startY - ) - ); - - section.Add - ( - _gameWindowLock = AddCheckBox - ( - null, - ResGumps.LockGameWindowMovingResizing, - _currentProfile.GameWindowLock, - startX, - startY - ) - ); - - section.Add(AddLabel(null, ResGumps.GamePlayWindowPosition, startX, startY)); - - section.AddRight - ( - _gameWindowPositionX = AddInputField - ( - null, - startX, - startY, - 50, - TEXTBOX_HEIGHT, - null, - 50, - false, - true - ), - 4 - ); - - var camera = Client.Game.Scene.Camera; - - _gameWindowPositionX.SetText(camera.Bounds.X.ToString()); - - section.AddRight - ( - _gameWindowPositionY = AddInputField - ( - null, - startX, - startY, - 50, - TEXTBOX_HEIGHT, - null, - 50, - false, - true - ) - ); - - _gameWindowPositionY.SetText(camera.Bounds.Y.ToString()); - - - section.Add(AddLabel(null, ResGumps.GamePlayWindowSize, startX, startY)); - - section.AddRight - ( - _gameWindowWidth = AddInputField - ( - null, - startX, - startY, - 50, - TEXTBOX_HEIGHT, - null, - 50, - false, - true - ) - ); - - _gameWindowWidth.SetText(camera.Bounds.Width.ToString()); - - section.AddRight - ( - _gameWindowHeight = AddInputField - ( - null, - startX, - startY, - 50, - TEXTBOX_HEIGHT, - null, - 50, - false, - true - ) - ); - - _gameWindowHeight.SetText(camera.Bounds.Height.ToString()); - - - SettingsSection section2 = AddSettingsSection(box, "Zoom"); - section2.Y = section.Bounds.Bottom + 40; - section2.Add(AddLabel(null, ResGumps.DefaultZoom, startX, startY)); - - var cameraZoomCount = (int)((camera.ZoomMax - camera.ZoomMin) / camera.ZoomStep); - var cameraZoomIndex = cameraZoomCount - (int)((camera.ZoomMax - camera.Zoom) / camera.ZoomStep); - - section2.AddRight - ( - _sliderZoom = AddHSlider - ( - null, - 0, - cameraZoomCount, - cameraZoomIndex, - startX, - startY, - 100 - ) - ); - - section2.Add - ( - _zoomCheckbox = AddCheckBox - ( - null, - ResGumps.EnableMouseWheelForZoom, - _currentProfile.EnableMousewheelScaleZoom, - startX, - startY - ) - ); - - section2.Add - ( - _restorezoomCheckbox = AddCheckBox - ( - null, - ResGumps.ReleasingCtrlRestoresScale, - _currentProfile.RestoreScaleAfterUnpressCtrl, - startX, - startY - ) - ); - - - SettingsSection section3 = AddSettingsSection(box, "Lights"); - section3.Y = section2.Bounds.Bottom + 40; - - section3.Add - ( - _altLights = AddCheckBox - ( - null, - ResGumps.AlternativeLights, - _currentProfile.UseAlternativeLights, - startX, - startY - ) - ); - - section3.Add - ( - _enableLight = AddCheckBox - ( - null, - ResGumps.LightLevel, - _currentProfile.UseCustomLightLevel, - startX, - startY - ) - ); - - section3.AddRight - ( - _lightBar = AddHSlider - ( - null, - 0, - 0x1E, - 0x1E - _currentProfile.LightLevel, - startX, - startY, - 250 - ) - ); - - section3.Add(AddLabel(null, ResGumps.LightLevelType, startX, startY)); - - section3.AddRight - ( - _lightLevelType = AddCombobox - ( - null, - new[] { ResGumps.LightLevelTypeAbsolute, ResGumps.LightLevelTypeMinimum }, - _currentProfile.LightLevelType, - startX, - startY, - 150 - ) - ); - - section3.Add - ( - _darkNights = AddCheckBox - ( - null, - ResGumps.DarkNights, - _currentProfile.UseDarkNights, - startX, - startY - ) - ); - - section3.Add - ( - _useColoredLights = AddCheckBox - ( - null, - ResGumps.UseColoredLights, - _currentProfile.UseColoredLights, - startX, - startY - ) - ); - - - SettingsSection section4 = AddSettingsSection(box, "Misc"); - section4.Y = section3.Bounds.Bottom + 40; - - section4.Add - ( - _enableDeathScreen = AddCheckBox - ( - null, - ResGumps.EnableDeathScreen, - _currentProfile.EnableDeathScreen, - startX, - startY - ) - ); - - section4.AddRight - ( - _enableBlackWhiteEffect = AddCheckBox - ( - null, - ResGumps.BlackWhiteModeForDeadPlayer, - _currentProfile.EnableBlackWhiteEffect, - startX, - startY - ) - ); - - section4.Add - ( - _runMouseInSeparateThread = AddCheckBox - ( - null, - ResGumps.RunMouseInASeparateThread, - Settings.GlobalSettings.RunMouseInASeparateThread, - startX, - startY - ) - ); - - section4.Add - ( - _auraMouse = AddCheckBox - ( - null, - ResGumps.AuraOnMouseTarget, - _currentProfile.AuraOnMouse, - startX, - startY - ) - ); - - section4.Add - ( - _animatedWaterEffect = AddCheckBox - ( - null, - ResGumps.AnimatedWaterEffect, - _currentProfile.AnimatedWaterEffect, - startX, - startY - ) - ); - - - SettingsSection section5 = AddSettingsSection(box, "Shadows"); - section5.Y = section4.Bounds.Bottom + 40; - - section5.Add - ( - _enableShadows = AddCheckBox - ( - null, - ResGumps.Shadows, - _currentProfile.ShadowsEnabled, - startX, - startY - ) - ); - - section5.PushIndent(); - - section5.Add - ( - _enableShadowsStatics = AddCheckBox - ( - null, - ResGumps.ShadowStatics, - _currentProfile.ShadowsStatics, - startX, - startY - ) - ); - - section5.PopIndent(); - - section5.Add(AddLabel(null, ResGumps.TerrainShadowsLevel, startX, startY)); - section5.AddRight(_terrainShadowLevel = AddHSlider(null, Constants.MIN_TERRAIN_SHADOWS_LEVEL, Constants.MAX_TERRAIN_SHADOWS_LEVEL, _currentProfile.TerrainShadowsLevel, startX, startY, 200)); - - Add(rightArea, PAGE); - } - - private void BuildCommands() - { - const int PAGE = 4; - - ScrollArea rightArea = new ScrollArea - ( - 190, - 52 + 25 + 4, - 150, - 360, - true - ); - - Add - ( - new Line - ( - 190, - 52 + 25 + 2, - 150, - 1, - Color.Gray.PackedValue - ), - PAGE - ); - - Add - ( - new Line - ( - 191 + 150, - 21, - 1, - 418, - Color.Gray.PackedValue - ), - PAGE - ); - - NiceButton addButton = new NiceButton - ( - 190, - 20, - 130, - 20, - ButtonAction.Activate, - ResGumps.NewMacro - ) - { IsSelectable = false, ButtonParameter = (int)Buttons.NewMacro }; - - Add(addButton, PAGE); - - NiceButton delButton = new NiceButton - ( - 190, - 52, - 130, - 20, - ButtonAction.Activate, - ResGumps.DeleteMacro - ) - { IsSelectable = false, ButtonParameter = (int)Buttons.DeleteMacro }; - - Add(delButton, PAGE); - - - int startX = 5; - int startY = 5; - - DataBox databox = new DataBox(startX, startY, 1, 1); - databox.WantUpdateSize = true; - rightArea.Add(databox); - - - addButton.MouseUp += (sender, e) => - { - EntryDialog dialog = new EntryDialog - ( - 250, - 150, - ResGumps.MacroName, - name => - { - if (string.IsNullOrWhiteSpace(name)) - { - return; - } - - MacroManager manager = Client.Game.GetScene().Macros; - - if (manager.FindMacro(name) != null) - { - return; - } - - NiceButton nb; - - databox.Add - ( - nb = new NiceButton - ( - 0, - 0, - 130, - 25, - ButtonAction.Activate, - name - ) - { - ButtonParameter = (int)Buttons.Last + 1 + rightArea.Children.Count, - CanMove = true - } - ); - - databox.ReArrangeChildren(); - - nb.IsSelected = true; - - _macroControl?.Dispose(); - - _macroControl = new MacroControl(name) - { - X = 350, - Y = 20 - }; - - manager.PushToBack(_macroControl.Macro); - - Add(_macroControl, PAGE); - - nb.DragBegin += (sss, eee) => - { - if (UIManager.DraggingControl != this || UIManager.MouseOverControl != sss) - { - return; - } - - UIManager.Gumps.OfType().FirstOrDefault(s => s.TheMacro == _macroControl.Macro)?.Dispose(); - - MacroButtonGump macroButtonGump = new MacroButtonGump(_macroControl.Macro, Mouse.Position.X, Mouse.Position.Y); - - macroButtonGump.X = Mouse.Position.X - (macroButtonGump.Width >> 1); - macroButtonGump.Y = Mouse.Position.Y - (macroButtonGump.Height >> 1); - - UIManager.Add(macroButtonGump); - - UIManager.AttemptDragControl(macroButtonGump, true); - }; - - nb.MouseUp += (sss, eee) => - { - _macroControl?.Dispose(); - - _macroControl = new MacroControl(name) - { - X = 350, - Y = 20 - }; - - Add(_macroControl, PAGE); - }; - } - ) - { - CanCloseWithRightClick = true - }; - - UIManager.Add(dialog); - }; - - delButton.MouseUp += (ss, ee) => - { - NiceButton nb = databox.FindControls().SingleOrDefault(a => a.IsSelected); - - if (nb != null) - { - QuestionGump dialog = new QuestionGump - ( - ResGumps.MacroDeleteConfirmation, - b => - { - if (!b) - { - return; - } - - if (_macroControl != null) - { - UIManager.Gumps.OfType().FirstOrDefault(s => s.TheMacro == _macroControl.Macro)?.Dispose(); - - Client.Game.GetScene().Macros.Remove(_macroControl.Macro); - - _macroControl.Dispose(); - } - - nb.Dispose(); - databox.ReArrangeChildren(); - } - ); - - UIManager.Add(dialog); - } - }; - - - MacroManager macroManager = Client.Game.GetScene().Macros; - - for (Macro macro = (Macro)macroManager.Items; macro != null; macro = (Macro)macro.Next) - { - NiceButton nb; - - databox.Add - ( - nb = new NiceButton - ( - 0, - 0, - 130, - 25, - ButtonAction.Activate, - macro.Name - ) - { - ButtonParameter = (int)Buttons.Last + 1 + rightArea.Children.Count, - Tag = macro, - CanMove = true - } - ); - - nb.IsSelected = true; - - nb.DragBegin += (sss, eee) => - { - NiceButton mupNiceButton = (NiceButton)sss; - - Macro m = mupNiceButton.Tag as Macro; - - if (m == null) - { - return; - } - - if (UIManager.DraggingControl != this || UIManager.MouseOverControl != sss) - { - return; - } - - UIManager.Gumps.OfType().FirstOrDefault(s => s.TheMacro == m)?.Dispose(); - - MacroButtonGump macroButtonGump = new MacroButtonGump(m, Mouse.Position.X, Mouse.Position.Y); - - macroButtonGump.X = Mouse.Position.X - (macroButtonGump.Width >> 1); - macroButtonGump.Y = Mouse.Position.Y - (macroButtonGump.Height >> 1); - - UIManager.Add(macroButtonGump); - - UIManager.AttemptDragControl(macroButtonGump, true); - }; - - nb.MouseUp += (sss, eee) => - { - NiceButton mupNiceButton = (NiceButton)sss; - - Macro m = mupNiceButton.Tag as Macro; - - if (m == null) - { - return; - } - - _macroControl?.Dispose(); - - _macroControl = new MacroControl(m.Name) - { - X = 350, - Y = 20 - }; - - Add(_macroControl, PAGE); - }; - } - - databox.ReArrangeChildren(); - - Add(rightArea, PAGE); - } - - private void BuildTooltip() - { - const int PAGE = 5; - - ScrollArea rightArea = new ScrollArea - ( - 190, - 20, - WIDTH - 210, - 420, - true - ); - - int startX = 5; - int startY = 5; - - _use_tooltip = AddCheckBox - ( - rightArea, - ResGumps.UseTooltip, - _currentProfile.UseTooltip, - startX, - startY - ); - - startY += _use_tooltip.Height + 2; - - startX += 40; - - Label text = AddLabel(rightArea, ResGumps.DelayBeforeDisplay, startX, startY); - startX += text.Width + 5; - - _delay_before_display_tooltip = AddHSlider - ( - rightArea, - 0, - 1000, - _currentProfile.TooltipDelayBeforeDisplay, - startX, - startY, - 200 - ); - - startX = 5 + 40; - startY += text.Height + 2; - - text = AddLabel(rightArea, ResGumps.TooltipZoom, startX, startY); - startX += text.Width + 5; - - _tooltip_zoom = AddHSlider - ( - rightArea, - 100, - 200, - _currentProfile.TooltipDisplayZoom, - startX, - startY, - 200 - ); - - startX = 5 + 40; - startY += text.Height + 2; - - text = AddLabel(rightArea, ResGumps.TooltipBackgroundOpacity, startX, startY); - startX += text.Width + 5; - - _tooltip_background_opacity = AddHSlider - ( - rightArea, - 0, - 100, - _currentProfile.TooltipBackgroundOpacity, - startX, - startY, - 200 - ); - - startX = 5 + 40; - startY += text.Height + 2; - - _tooltip_font_hue = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.TooltipTextHue, - ResGumps.TooltipFontHue - ); - - startY += _tooltip_font_hue.Height + 2; - - startY += 15; - - text = AddLabel(rightArea, ResGumps.TooltipFont, startX, startY); - startY += text.Height + 2; - startX += 40; - - _tooltip_font_selector = new FontSelector(7, _currentProfile.TooltipFont, ResGumps.TooltipFontSelect) - { - X = startX, - Y = startY - }; - - rightArea.Add(_tooltip_font_selector); - - Add(rightArea, PAGE); - } - - private void BuildFonts() - { - const int PAGE = 6; - - ScrollArea rightArea = new ScrollArea - ( - 190, - 20, - WIDTH - 210, - 420, - true - ); - - int startX = 5; - int startY = 5; - - _overrideAllFonts = AddCheckBox - ( - rightArea, - ResGumps.OverrideGameFont, - _currentProfile.OverrideAllFonts, - startX, - startY - ); - - startX += _overrideAllFonts.Width + 5; - - _overrideAllFontsIsUnicodeCheckbox = AddCombobox - ( - rightArea, - new[] - { - ResGumps.ASCII, ResGumps.Unicode - }, - _currentProfile.OverrideAllFontsIsUnicode ? 1 : 0, - startX, - startY, - 100 - ); - - startX = 5; - startY += _overrideAllFonts.Height + 2; - - _forceUnicodeJournal = AddCheckBox - ( - rightArea, - ResGumps.ForceUnicodeInJournal, - _currentProfile.ForceUnicodeJournal, - startX, - startY - ); - - startY += _forceUnicodeJournal.Height + 2; - - Label text = AddLabel(rightArea, ResGumps.SpeechFont, startX, startY); - startX += 40; - startY += text.Height + 2; - - _fontSelectorChat = new FontSelector(20, _currentProfile.ChatFont, ResGumps.ThatSClassicUO) - { - X = startX, - Y = startY - }; - - rightArea.Add(_fontSelectorChat); - - Add(rightArea, PAGE); - } - - private void BuildSpeech() - { - const int PAGE = 7; - - ScrollArea rightArea = new ScrollArea - ( - 190, - 20, - WIDTH - 210, - 420, - true - ); - - int startX = 5; - int startY = 5; - - _scaleSpeechDelay = AddCheckBox - ( - rightArea, - ResGumps.ScaleSpeechDelay, - _currentProfile.ScaleSpeechDelay, - startX, - startY - ); - - startX += _scaleSpeechDelay.Width + 5; - - _sliderSpeechDelay = AddHSlider - ( - rightArea, - 0, - 1000, - _currentProfile.SpeechDelay, - startX, - startY, - 180 - ); - - startX = 5; - startY += _scaleSpeechDelay.Height + 2; - - _saveJournalCheckBox = AddCheckBox - ( - rightArea, - ResGumps.SaveJournalToFileInGameFolder, - _currentProfile.SaveJournalToFile, - startX, - startY - ); - - startY += _saveJournalCheckBox.Height + 2; - - if (!_currentProfile.SaveJournalToFile) - { - World.Journal.CloseWriter(); - } - - _chatAfterEnter = AddCheckBox - ( - rightArea, - ResGumps.ActiveChatWhenPressingEnter, - _currentProfile.ActivateChatAfterEnter, - startX, - startY - ); - - startX += 40; - startY += _chatAfterEnter.Height + 2; - - _chatAdditionalButtonsCheckbox = AddCheckBox - ( - rightArea, - ResGumps.UseAdditionalButtonsToActivateChat, - _currentProfile.ActivateChatAdditionalButtons, - startX, - startY - ); - - startY += _chatAdditionalButtonsCheckbox.Height + 2; - - _chatShiftEnterCheckbox = AddCheckBox - ( - rightArea, - ResGumps.UseShiftEnterToSendMessage, - _currentProfile.ActivateChatShiftEnterSupport, - startX, - startY - ); - - startY += _chatShiftEnterCheckbox.Height + 2; - startX = 5; - - _hideChatGradient = AddCheckBox - ( - rightArea, - ResGumps.HideChatGradient, - _currentProfile.HideChatGradient, - startX, - startY - ); - - startY += _hideChatGradient.Height + 2; - - _ignoreGuildMessages = AddCheckBox - ( - rightArea, - ResGumps.IgnoreGuildMessages, - _currentProfile.IgnoreGuildMessages, - startX, - startY - ); - - startY += _ignoreGuildMessages.Height + 2; - - _ignoreAllianceMessages = AddCheckBox - ( - rightArea, - ResGumps.IgnoreAllianceMessages, - _currentProfile.IgnoreAllianceMessages, - startX, - startY - ); - - startY += 35; - - _randomizeColorsButton = new NiceButton - ( - startX, - startY, - 140, - 25, - ButtonAction.Activate, - ResGumps.RandomizeSpeechHues - ) - { ButtonParameter = (int)Buttons.Disabled }; - - _randomizeColorsButton.MouseUp += (sender, e) => - { - if (e.Button != MouseButtonType.Left) - { - return; - } - - ushort speechHue = (ushort)RandomHelper.GetValue(2, 0x03b2); //this seems to be the acceptable hue range for chat messages, - - ushort emoteHue = (ushort)RandomHelper.GetValue(2, 0x03b2); //taken from POL source code. - ushort yellHue = (ushort)RandomHelper.GetValue(2, 0x03b2); - ushort whisperHue = (ushort)RandomHelper.GetValue(2, 0x03b2); - _currentProfile.SpeechHue = speechHue; - _speechColorPickerBox.Hue = speechHue; - _currentProfile.EmoteHue = emoteHue; - _emoteColorPickerBox.Hue = emoteHue; - _currentProfile.YellHue = yellHue; - _yellColorPickerBox.Hue = yellHue; - _currentProfile.WhisperHue = whisperHue; - _whisperColorPickerBox.Hue = whisperHue; - }; - - rightArea.Add(_randomizeColorsButton); - startY += _randomizeColorsButton.Height + 2 + 20; - - - _speechColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.SpeechHue, - ResGumps.SpeechColor - ); - - startX += 200; - - _emoteColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.EmoteHue, - ResGumps.EmoteColor - ); - - startY += _emoteColorPickerBox.Height + 2; - startX = 5; - - _yellColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.YellHue, - ResGumps.YellColor - ); - - startX += 200; - - _whisperColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.WhisperHue, - ResGumps.WhisperColor - ); - - startY += _whisperColorPickerBox.Height + 2; - startX = 5; - - _partyMessageColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.PartyMessageHue, - ResGumps.PartyMessageColor - ); - - startX += 200; - - _guildMessageColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.GuildMessageHue, - ResGumps.GuildMessageColor - ); - - startY += _guildMessageColorPickerBox.Height + 2; - startX = 5; - - _allyMessageColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.AllyMessageHue, - ResGumps.AllianceMessageColor - ); - - startX += 200; - - _chatMessageColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.ChatMessageHue, - ResGumps.ChatMessageColor - ); - - startY += _chatMessageColorPickerBox.Height + 2; - startX = 5; - - Add(rightArea, PAGE); - } - - private void BuildCombat() - { - const int PAGE = 8; - - ScrollArea rightArea = new ScrollArea - ( - 190, - 20, - WIDTH - 210, - 420, - true - ); - - int startX = 5; - int startY = 5; - - _holdDownKeyTab = AddCheckBox - ( - rightArea, - ResGumps.TabCombat, - _currentProfile.HoldDownKeyTab, - startX, - startY - ); - - startY += _holdDownKeyTab.Height + 2; - - _queryBeforAttackCheckbox = AddCheckBox - ( - rightArea, - ResGumps.QueryAttack, - _currentProfile.EnabledCriminalActionQuery, - startX, - startY - ); - - startY += _queryBeforAttackCheckbox.Height + 2; - - _queryBeforeBeneficialCheckbox = AddCheckBox - ( - rightArea, - ResGumps.QueryBeneficialActs, - _currentProfile.EnabledBeneficialCriminalActionQuery, - startX, - startY - ); - - startY += _queryBeforeBeneficialCheckbox.Height + 2; - - _spellFormatCheckbox = AddCheckBox - ( - rightArea, - ResGumps.EnableOverheadSpellFormat, - _currentProfile.EnabledSpellFormat, - startX, - startY - ); - - startY += _spellFormatCheckbox.Height + 2; - - _spellColoringCheckbox = AddCheckBox - ( - rightArea, - ResGumps.EnableOverheadSpellHue, - _currentProfile.EnabledSpellHue, - startX, - startY - ); - - startY += _spellColoringCheckbox.Height + 2; - - _uiButtonsSingleClick = AddCheckBox - ( - rightArea, - ResGumps.UIButtonsSingleClick, - _currentProfile.CastSpellsByOneClick, - startX, - startY - ); - - startY += _uiButtonsSingleClick.Height + 2; - - _buffBarTime = AddCheckBox - ( - rightArea, - ResGumps.ShowBuffDuration, - _currentProfile.BuffBarTime, - startX, - startY - ); - - startY += _buffBarTime.Height + 2; - - _enableFastSpellsAssign = AddCheckBox - ( - rightArea, - ResGumps.EnableFastSpellsAssign, - _currentProfile.FastSpellsAssign, - startX, - startY - ); - - startY += 30; - - int initialY = startY; - - _innocentColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.InnocentHue, - ResGumps.InnocentColor - ); - - startY += _innocentColorPickerBox.Height + 2; - - _friendColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.FriendHue, - ResGumps.FriendColor - ); - - startY += _innocentColorPickerBox.Height + 2; - - _crimialColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.CriminalHue, - ResGumps.CriminalColor - ); - - startY += _innocentColorPickerBox.Height + 2; - - _canAttackColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.CanAttackHue, - ResGumps.CanAttackColor - ); - - startY += _innocentColorPickerBox.Height + 2; - - _murdererColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.MurdererHue, - ResGumps.MurdererColor - ); - - startY += _innocentColorPickerBox.Height + 2; - - _enemyColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.EnemyHue, - ResGumps.EnemyColor - ); - - startY += _innocentColorPickerBox.Height + 2; - - startY = initialY; - startX += 200; - - _beneficColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.BeneficHue, - ResGumps.BeneficSpellHue - ); - - startY += _beneficColorPickerBox.Height + 2; - - _harmfulColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.HarmfulHue, - ResGumps.HarmfulSpellHue - ); - - startY += _harmfulColorPickerBox.Height + 2; - - _neutralColorPickerBox = AddColorBox - ( - rightArea, - startX, - startY, - _currentProfile.NeutralHue, - ResGumps.NeutralSpellHue - ); - - startY += _neutralColorPickerBox.Height + 2; - - startX = 5; - startY += (_neutralColorPickerBox.Height + 2) * 4; - - _spellFormatBox = AddInputField - ( - rightArea, - startX, - startY, - 200, - TEXTBOX_HEIGHT, - ResGumps.SpellOverheadFormat, - 0, - true, - false, - 30 - ); - - _spellFormatBox.SetText(_currentProfile.SpellDisplayFormat); - - startX = 5; - startY += (_spellFormatBox.Height * 2) + 2; - Add(rightArea, PAGE); - } - - private void BuildCounters() - { - const int PAGE = 9; - - ScrollArea rightArea = new ScrollArea - ( - 190, - 20, - WIDTH - 210, - 420, - true - ); - - int startX = 5; - int startY = 5; - - - _enableCounters = AddCheckBox - ( - rightArea, - ResGumps.EnableCounters, - _currentProfile.CounterBarEnabled, - startX, - startY - ); - - startX += 40; - startY += _enableCounters.Height + 2; - - _highlightOnUse = AddCheckBox - ( - rightArea, - ResGumps.HighlightOnUse, - _currentProfile.CounterBarHighlightOnUse, - startX, - startY - ); - - startY += _highlightOnUse.Height + 2; - - _enableAbbreviatedAmount = AddCheckBox - ( - rightArea, - ResGumps.EnableAbbreviatedAmountCountrs, - _currentProfile.CounterBarDisplayAbbreviatedAmount, - startX, - startY - ); - - startX += _enableAbbreviatedAmount.Width + 5; - - _abbreviatedAmount = AddInputField - ( - rightArea, - startX, - startY, - 50, - TEXTBOX_HEIGHT, - null, - 50, - false, - true - ); - - _abbreviatedAmount.SetText(_currentProfile.CounterBarAbbreviatedAmount.ToString()); - - startX = 5; - startX += 40; - startY += _enableAbbreviatedAmount.Height + 2; - - _highlightOnAmount = AddCheckBox - ( - rightArea, - ResGumps.HighlightRedWhenBelow, - _currentProfile.CounterBarHighlightOnAmount, - startX, - startY - ); - - startX += _highlightOnAmount.Width + 5; - - _highlightAmount = AddInputField - ( - rightArea, - startX, - startY, - 50, - TEXTBOX_HEIGHT, - null, - 50, - false, - true, - 999 - ); - - _highlightAmount.SetText(_currentProfile.CounterBarHighlightAmount.ToString()); - - startX = 5; - startX += 40; - startY += _highlightAmount.Height + 2 + 5; - - startY += 40; - - Label text = AddLabel(rightArea, ResGumps.CounterLayout, startX, startY); - - startX += 40; - startY += text.Height + 2; - text = AddLabel(rightArea, ResGumps.CellSize, startX, startY); - - int initialX = startX; - startX += text.Width + 5; - - _cellSize = AddHSlider - ( - rightArea, - 30, - 80, - _currentProfile.CounterBarCellSize, - startX, - startY, - 80 - ); - - - startX = initialX; - startY += text.Height + 2 + 15; - - _rows = AddInputField - ( - rightArea, - startX, - startY, - 50, - 30, - ResGumps.Counter_Rows, - 50, - false, - true, - 30 - ); - - _rows.SetText(_currentProfile.CounterBarRows.ToString()); - - - startX += _rows.Width + 5 + 100; - - _columns = AddInputField - ( - rightArea, - startX, - startY, - 50, - 30, - ResGumps.Counter_Columns, - 50, - false, - true, - 30 - ); - - _columns.SetText(_currentProfile.CounterBarColumns.ToString()); - - - Add(rightArea, PAGE); - } - - private void BuildExperimental() - { - const int PAGE = 12; - - ScrollArea rightArea = new ScrollArea - ( - 190, - 20, - WIDTH - 210, - 420, - true - ); - - int startX = 5; - int startY = 5; - - _disableDefaultHotkeys = AddCheckBox - ( - rightArea, - ResGumps.DisableDefaultUOHotkeys, - _currentProfile.DisableDefaultHotkeys, - startX, - startY - ); - - startX += 40; - startY += _disableDefaultHotkeys.Height + 2; - - _disableArrowBtn = AddCheckBox - ( - rightArea, - ResGumps.DisableArrowsPlayerMovement, - _currentProfile.DisableArrowBtn, - startX, - startY - ); - - startY += _disableArrowBtn.Height + 2; - - _disableTabBtn = AddCheckBox - ( - rightArea, - ResGumps.DisableTab, - _currentProfile.DisableTabBtn, - startX, - startY - ); - - startY += _disableTabBtn.Height + 2; - - _disableCtrlQWBtn = AddCheckBox - ( - rightArea, - ResGumps.DisableMessageHistory, - _currentProfile.DisableCtrlQWBtn, - startX, - startY - ); - - startY += _disableCtrlQWBtn.Height + 2; - - _disableAutoMove = AddCheckBox - ( - rightArea, - ResGumps.DisableClickAutomove, - _currentProfile.DisableAutoMove, - startX, - startY - ); - - startY += _disableAutoMove.Height + 2; - - Add(rightArea, PAGE); - } - - private void BuildInfoBar() - { - const int PAGE = 10; - - ScrollArea rightArea = new ScrollArea - ( - 190, - 20, - WIDTH - 210, - 420, - true - ); - - int startX = 5; - int startY = 5; - - _showInfoBar = AddCheckBox - ( - rightArea, - ResGumps.ShowInfoBar, - _currentProfile.ShowInfoBar, - startX, - startY - ); - - startX += 40; - startY += _showInfoBar.Height + 2; - - Label text = AddLabel(rightArea, ResGumps.DataHighlightType, startX, startY); - - startX += text.Width + 5; - - _infoBarHighlightType = AddCombobox - ( - rightArea, - new[] { ResGumps.TextColor, ResGumps.ColoredBars }, - _currentProfile.InfoBarHighlightType, - startX, - startY, - 150 - ); - - startX = 5; - startY += _infoBarHighlightType.Height + 5; - - NiceButton nb = new NiceButton - ( - startX, - startY, - 90, - 20, - ButtonAction.Activate, - ResGumps.AddItem, - 0, - TEXT_ALIGN_TYPE.TS_LEFT - ) - { - ButtonParameter = -1, - IsSelectable = true, - IsSelected = true - }; - - nb.MouseUp += (sender, e) => - { - InfoBarBuilderControl ibbc = new InfoBarBuilderControl(new InfoBarItem("", InfoBarVars.HP, 0x3B9)); - ibbc.X = 5; - ibbc.Y = _databox.Children.Count * ibbc.Height; - _infoBarBuilderControls.Add(ibbc); - _databox.Add(ibbc); - _databox.WantUpdateSize = true; - }; - - rightArea.Add(nb); - - - startY += 40; - - text = AddLabel(rightArea, ResGumps.Label, startX, startY); - - startX += 150; - - text = AddLabel(rightArea, ResGumps.Color, startX, startY); - - startX += 55; - text = AddLabel(rightArea, ResGumps.Data, startX, startY); - - startX = 5; - startY += text.Height + 2; - - rightArea.Add - ( - new Line - ( - startX, - startY, - rightArea.Width, - 1, - Color.Gray.PackedValue - ) - ); - - startY += 20; - - - InfoBarManager ibmanager = Client.Game.GetScene().InfoBars; - - List _infoBarItems = ibmanager.GetInfoBars(); - - _infoBarBuilderControls = new List(); - - _databox = new DataBox(startX, startY, 10, 10) - { - WantUpdateSize = true - }; - - - for (int i = 0; i < _infoBarItems.Count; i++) - { - InfoBarBuilderControl ibbc = new InfoBarBuilderControl(_infoBarItems[i]); - ibbc.X = 5; - ibbc.Y = i * ibbc.Height; - _infoBarBuilderControls.Add(ibbc); - _databox.Add(ibbc); - } - - rightArea.Add(_databox); - - Add(rightArea, PAGE); - } - - private void BuildContainers() - { - const int PAGE = 11; - - ScrollArea rightArea = new ScrollArea - ( - 190, - 20, - WIDTH - 210, - 420, - true - ); - - int startX = 5; - int startY = 5; - Label text; - - bool hasBackpacks = Client.Version >= ClientVersion.CV_705301; - - if (hasBackpacks) - { - text = AddLabel(rightArea, ResGumps.BackpackStyle, startX, startY); - startX += text.Width + 5; - } - - _backpackStyle = AddCombobox - ( - rightArea, - new[] - { - ResGumps.BackpackStyle_Default, ResGumps.BackpackStyle_Suede, - ResGumps.BackpackStyle_PolarBear, ResGumps.BackpackStyle_GhoulSkin - }, - _currentProfile.BackpackStyle, - startX, - startY, - 200 - ); - - _backpackStyle.IsVisible = hasBackpacks; - - if (hasBackpacks) - { - startX = 5; - startY += _backpackStyle.Height + 2 + 10; - } - - text = AddLabel(rightArea, ResGumps.ContainerScale, startX, startY); - startX += text.Width + 5; - - _containersScale = AddHSlider - ( - rightArea, - Constants.MIN_CONTAINER_SIZE_PERC, - Constants.MAX_CONTAINER_SIZE_PERC, - _currentProfile.ContainersScale, - startX, - startY, - 200 - ); - - startX = 5; - startY += _containersScale.Height + 2; - - _containerScaleItems = AddCheckBox - ( - rightArea, - ResGumps.ScaleItemsInsideContainers, - _currentProfile.ScaleItemsInsideContainers, - startX, - startY - ); - startY += _containerScaleItems.Height + 2; - - _useLargeContianersGumps = AddCheckBox - ( - rightArea, - ResGumps.UseLargeContainersGump, - _currentProfile.UseLargeContainerGumps, - startX, - startY - ); - _useLargeContianersGumps.IsVisible = Client.Version >= ClientVersion.CV_706000; - - if (_useLargeContianersGumps.IsVisible) - { - startY += _useLargeContianersGumps.Height + 2; - } - - _containerDoubleClickToLoot = AddCheckBox - ( - rightArea, - ResGumps.DoubleClickLootContainers, - _currentProfile.DoubleClickToLootInsideContainers, - startX, - startY - ); - - startY += _containerDoubleClickToLoot.Height + 2; - - _relativeDragAnDropItems = AddCheckBox - ( - rightArea, - ResGumps.RelativeDragAndDropContainers, - _currentProfile.RelativeDragAndDropItems, - startX, - startY - ); - - startY += _relativeDragAnDropItems.Height + 2; - - _highlightContainersWhenMouseIsOver = AddCheckBox - ( - rightArea, - ResGumps.HighlightContainerWhenSelected, - _currentProfile.HighlightContainerWhenSelected, - startX, - startY - ); - - startY += _highlightContainersWhenMouseIsOver.Height + 2; - - _hueContainerGumps = AddCheckBox - ( - rightArea, - ResGumps.HueContainerGumps, - _currentProfile.HueContainerGumps, - startX, - startY - ); - - startY += _hueContainerGumps.Height + 2; - - _overrideContainerLocation = AddCheckBox - ( - rightArea, - ResGumps.OverrideContainerGumpLocation, - _currentProfile.OverrideContainerLocation, - startX, - startY - ); - - startX += _overrideContainerLocation.Width + 5; - - _overrideContainerLocationSetting = AddCombobox - ( - rightArea, - new[] - { - ResGumps.ContLoc_NearContainerPosition, ResGumps.ContLoc_TopRight, - ResGumps.ContLoc_LastDraggedPosition, ResGumps.ContLoc_RememberEveryContainer - }, - _currentProfile.OverrideContainerLocationSetting, - startX, - startY, - 200 - ); - - startX = 5; - startY += _overrideContainerLocation.Height + 2 + 10; - - NiceButton button = new NiceButton - ( - startX, - startY, - 130, - 30, - ButtonAction.Activate, - ResGumps.RebuildContainers - ) - { - ButtonParameter = -1, - IsSelectable = true, - IsSelected = true - }; - - button.MouseUp += (sender, e) => { ContainerManager.BuildContainerFile(true); }; - rightArea.Add(button); - - startX = 5; - startY += button.Height + 2; - - Add(rightArea, PAGE); - } - - private void BuildNameOverhead() - { - const int PAGE = 13; - - ScrollArea rightArea = new ScrollArea - ( - 190, - 52 + 25 + 4, - 150, - 360, - true - ); - - Add - ( - new Line - ( - 190, - 52 + 25 + 2, - 150, - 1, - Color.Gray.PackedValue - ), - PAGE - ); - - Add - ( - new Line - ( - 191 + 150, - 21, - 1, - 418, - Color.Gray.PackedValue - ), - PAGE - ); - - NiceButton addButton = new NiceButton - ( - 190, - 20, - 130, - 20, - ButtonAction.Activate, - "New entry" - ) - { IsSelectable = false, ButtonParameter = (int)Buttons.NewNameOverheadEntry }; - - Add(addButton, PAGE); - - NiceButton delButton = new NiceButton - ( - 190, - 52, - 130, - 20, - ButtonAction.Activate, - "Delete entry" - ) - { IsSelectable = false, ButtonParameter = (int)Buttons.DeleteOverheadEntry }; - - Add(delButton, PAGE); - - - int startX = 5; - int startY = 5; - - DataBox databox = new DataBox(startX, startY, 1, 1); - databox.WantUpdateSize = true; - rightArea.Add(databox); - - - addButton.MouseUp += (sender, e) => - { - EntryDialog dialog = new - ( - 250, - 150, - "Name overhead entry name", - name => - { - if (string.IsNullOrWhiteSpace(name)) - { - return; - } - if (NameOverHeadManager.FindOption(name) != null) - { - return; - } - NiceButton nb; - databox.Add - ( - nb = new NiceButton - ( - 0, - 0, - 130, - 25, - ButtonAction.Activate, - name - ) - { - ButtonParameter = (int)Buttons.Last + 1 + rightArea.Children.Count - } - ); - databox.ReArrangeChildren(); - nb.IsSelected = true; - _nameOverheadControl?.Dispose(); - var option = new NameOverheadOption(name); - NameOverHeadManager.AddOption(option); - _nameOverheadControl = new NameOverheadAssignControl(option) - { - X = 400, - Y = 20 - }; - Add(_nameOverheadControl, PAGE); - nb.MouseUp += (sss, eee) => - { - _nameOverheadControl?.Dispose(); - _nameOverheadControl = new NameOverheadAssignControl(option) - { - X = 400, - Y = 20 - }; - Add(_nameOverheadControl, PAGE); - }; - } - ) - { - CanCloseWithRightClick = true - }; - UIManager.Add(dialog); - }; - - delButton.MouseUp += (ss, ee) => - { - NiceButton nb = databox.FindControls().SingleOrDefault(a => a.IsSelected); - if (nb != null) - { - QuestionGump dialog = new QuestionGump - ( - ResGumps.MacroDeleteConfirmation, - b => - { - if (!b) - { - return; - } - if (_nameOverheadControl != null) - { - NameOverHeadManager.RemoveOption(_nameOverheadControl.Option); - _nameOverheadControl.Dispose(); - } - nb.Dispose(); - databox.ReArrangeChildren(); - } - ); - UIManager.Add(dialog); - } - }; - - - foreach (var option in NameOverHeadManager.GetAllOptions()) - { - NiceButton nb; - - databox.Add - ( - nb = new NiceButton - ( - 0, - 0, - 130, - 25, - ButtonAction.Activate, - option.Name - ) - { - ButtonParameter = (int)Buttons.Last + 1 + rightArea.Children.Count, - Tag = option - } - ); - - nb.IsSelected = true; - - nb.MouseUp += (sss, eee) => - { - NiceButton mupNiceButton = (NiceButton)sss; - var option = mupNiceButton.Tag as NameOverheadOption; - if (option == null) - { - return; - } - _nameOverheadControl?.Dispose(); - _nameOverheadControl = new NameOverheadAssignControl(option) - { - X = 400, - Y = 20 - }; - Add(_nameOverheadControl, PAGE); - }; - } - - databox.ReArrangeChildren(); - - Add(rightArea, PAGE); - } - - private void BuildCooldowns() - { - const int PAGE = 8787; - - ScrollArea rightArea = new ScrollArea - ( - 190, - 20, - WIDTH - 210, - 420, - true - ); - - - SettingsSection _coolDowns = new SettingsSection("Cooldown bars", rightArea.Width); - - { - _coolDowns.Add(AddLabel(null, "Position", 0, 0)); - _coolDowns.AddRight(_coolDownX = AddInputField( - null, 0, 0, - 50, TEXTBOX_HEIGHT, - numbersOnly: true - )); - _coolDownX.SetText(_currentProfile.CoolDownX.ToString()); - - _coolDowns.AddRight(_coolDownY = AddInputField( - null, 0, 0, - 50, TEXTBOX_HEIGHT, - numbersOnly: true - )); - _coolDownY.SetText(_currentProfile.CoolDownY.ToString()); - - _coolDowns.AddRight(_uselastCooldownPosition = AddCheckBox(null, "Use last moved bar position", _currentProfile.UseLastMovedCooldownPosition, 0, 0)); - - }//Cooldown position - rightArea.Add(_coolDowns); - - #region Cooldown conditions - SettingsSection conditions = new SettingsSection("Condition", rightArea.Width + 10); - conditions.Y = _coolDowns.Y + _coolDowns.Height + 5; - - { - NiceButton _button; - conditions.Add(_button = new NiceButton( - 0, 0, - 100, TEXTBOX_HEIGHT, - ButtonAction.Activate, - "+ Condition" - )); - _button.IsSelectable = false; - _button.MouseUp += (sender, e) => - { - conditions.Add(GenConditionControl(_currentProfile.CoolDownConditionCount, WIDTH - 240, true)); - }; - - int count = _currentProfile.CoolDownConditionCount; - for (int i = 0; i < count; i++) - { - conditions.Add(GenConditionControl(i, WIDTH - 240, false)); - } - } //Add condition - - rightArea.Add(conditions); - #endregion - - Add(rightArea, PAGE); - } - - private void BuildTazUO() - { - const int PAGE = 8788; - const int SPACING = 25; - ScrollArea rightArea = new ScrollArea - ( - 190, - 20, - WIDTH - 210, - 420, - true - ); - int startY = 5; - - { - SettingsSection gridSection = new SettingsSection("Grid Containers", rightArea.Width); - { - NiceButton _; - gridSection.BaseAdd(_ = new NiceButton(0, 0, 20, TEXTBOX_HEIGHT, ButtonAction.Activate, "<>") { IsSelectable = false }); - _.SetTooltip("Minimize section"); - _.X = rightArea.Width - 45; - _.Y = 0; - _.MouseUp += MinimizeSectionMouseUp; - } - - { - gridSection.Add(_useGridLayoutContainerGumps = AddCheckBox( - null, - "Use grid containers", - _currentProfile.UseGridLayoutContainerGumps, - 0, - 0 - )); - } //Use grid containers - - { - gridSection.Add(AddLabel(null, "Grid container scale", 0, 0)); - - gridSection.AddRight(_gridContainerScale = AddHSlider( - null, - 50, 200, - _currentProfile.GridContainersScale, - 0, 0, - 200 - )); - } //Grid container scale - - { - gridSection.PushIndent(); - - gridSection.Add(_gridContainerItemScale = AddCheckBox( - null, - "", - _currentProfile.GridContainerScaleItems, - 0, 0 - )); - - gridSection.AddRight(AddLabel(null, "Also scale items", 0, 0)); - - gridSection.PopIndent(); - } //Grid container item scales - - { - gridSection.Add(AddLabel(null, "Border opacity", 0, 0)); - gridSection.AddRight - ( - _gridBorderOpacity = AddHSlider - ( - null, - 0, - 100, - _currentProfile.GridBorderAlpha, - 0, - 0, - 200 - ) - ); - } //Grid border opacity - - { - gridSection.PushIndent(); - gridSection.Add - ( - _gridBorderHue = new ModernColorPicker.HueDisplay(_currentProfile.GridBorderHue, null, true) - ); - gridSection.AddRight(AddLabel(null, "Border hue", 0, 0)); - gridSection.PopIndent(); - } //Grid border hue - - { - gridSection.Add(AddLabel(null, "Background opacity", 0, 0)); - gridSection.AddRight(_containerOpacity = AddHSlider - ( - null, - 0, - 100, - _currentProfile.ContainerOpacity, - 0, - 0, - 200 - )); - } //Grid container opacity - - { - gridSection.PushIndent(); - gridSection.Add(_altGridContainerBackgroundHue = new ModernColorPicker.HueDisplay(_currentProfile.AltGridContainerBackgroundHue, null, true)); - gridSection.AddRight(AddLabel(null, "Background hue", 0, 0)); - gridSection.PopIndent(); - } //Grid container background hue - - { - gridSection.PushIndent(); - gridSection.Add(_gridOverrideWithContainerHue = AddCheckBox(null, "Override hue with the container's hue", _currentProfile.Grid_UseContainerHue, 0, 0)); - gridSection.PopIndent(); - } //Override grid hue with container hue - - { - gridSection.Add( - AddLabel(null, "Search Style", 0, 0) - ); - - gridSection.AddRight( - _gridContainerSearchAlternative = AddCombobox( - null, - new string[] { - "Only show", - "Highlight" - }, - _currentProfile.GridContainerSearchMode, - 0, - 0, - 200 - ) - ); - } //Grid container search mode - - { - gridSection.Add(_gridContainerPreview = AddCheckBox( - null, - "Enable container preview", - _currentProfile.GridEnableContPreview, - 0, - 0 - )); - _gridContainerPreview.SetTooltip("This only works on containers that you have opened, otherwise the client does not have that information yet."); - } //Grid preview - - { - gridSection.Add(_gridContainerAnchorable = AddCheckBox( - null, "Make anchorable", - _currentProfile.EnableGridContainerAnchor, - 0, 0 - )); - _gridContainerAnchorable.SetTooltip("This will allow grid containers to be anchored to other containers/world map/journal"); - } //Grid anchors - - { - gridSection.Add(AddLabel(null, "Container Style", 0, 0)); - - gridSection.AddRight(_gridBorderStyle = AddCombobox( - null, - Enum.GetNames(typeof(GridContainer.BorderStyle)), - _currentProfile.Grid_BorderStyle, - 0, 0, - 200 - )); - } //Grid border style - - gridSection.Add(AddLabel(null, "Hide border around gump", 0, 0)); - gridSection.AddRight(_gridHideBorder = AddCheckBox(null, "", _currentProfile.Grid_HideBorder, 0, 0)); - - { - gridSection.Add(AddLabel(null, "Default grid rows x columns", 0, 0)); - gridSection.AddRight(_gridDefaultRows = AddInputField(null, 0, 0, 25, TEXTBOX_HEIGHT, numbersOnly: true)); - _gridDefaultRows.SetText(_currentProfile.Grid_DefaultRows.ToString()); - gridSection.AddRight(_gridDefaultColumns = AddInputField(null, 0, 0, 25, TEXTBOX_HEIGHT, numbersOnly: true)); - _gridDefaultColumns.SetText(_currentProfile.Grid_DefaultColumns.ToString()); - } //Grid default rows and columns - - { - NiceButton _; - gridSection.Add(_ = new NiceButton(X, 0, 150, TEXTBOX_HEIGHT, ButtonAction.Activate, "Grid highlight settings")); - _.DisplayBorder = true; - _.IsSelectable = false; - _.MouseUp += (s, e) => - { - UIManager.GetGump()?.Dispose(); - UIManager.Add(new GridHightlightMenu()); - }; - - gridSection.Add(AddLabel(null, "Grid highlight line size", 0, 0)); - gridSection.AddRight(_gridHightlightLineSize = AddHSlider(null, 1, 10, _currentProfile.GridHightlightSize, 0, 0, 150)); - } //Grid highlight settings - - rightArea.Add(gridSection); - startY += gridSection.Height + SPACING; - }//Grid containers - - { - SettingsSection section = new SettingsSection("Journal", rightArea.Width) { Y = startY }; - - { - NiceButton _; - section.BaseAdd(_ = new NiceButton(0, 0, 20, TEXTBOX_HEIGHT, ButtonAction.Activate, "<>") { IsSelectable = false }); - _.SetTooltip("Minimize section"); - _.X = rightArea.Width - 45; - _.MouseUp += MinimizeSectionMouseUp; - } - - section.Add(AddLabel(null, "Max journal entries", 0, 0)); - section.AddRight(_maxJournalEntries = AddHSlider(null, 200, 2000, _currentProfile.MaxJournalEntries, 0, 0, 200)); - - { - section.Add(AddLabel(null, "Journal Opacity", 0, 0)); - - section.AddRight - ( - _journalOpacity = AddHSlider( - null, - 0, - 100, - _currentProfile.JournalOpacity, - 0, - 0, - 200 - ), - 2 - ); - section.PushIndent(); - section.Add - ( - _journalBackgroundColor = AddColorBox( - null, - 0, - 0, - _currentProfile.AltJournalBackgroundHue, - "" - ) - ); - section.AddRight(AddLabel(null, "Journal Background", 0, 0)); - section.PopIndent(); - - section.Add(AddLabel(null, "Journal style", 0, 0)); - section.AddRight(_journalStyle = AddCombobox( - null, - Enum.GetNames(typeof(ResizableJournal.BorderStyle)), - _currentProfile.JournalStyle, 0, 0, 150 - )); - } //Journal opac and hue - - section.Add(AddLabel(null, "Hide gump border", 0, 0)); - section.AddRight(_hideJournalBorder = AddCheckBox(null, "", _currentProfile.HideJournalBorder, 0, 0)); - - section.Add(AddLabel(null, "Hide timestamp", 0, 0)); - section.AddRight(_hideJournalTimestamp = AddCheckBox(null, "", _currentProfile.HideJournalTimestamp, 0, 0)); - - rightArea.Add(section); - startY += section.Height + SPACING; - }//Journal - - { - SettingsSection section = new SettingsSection("Modern Paperdoll", rightArea.Width) { Y = startY }; - - { - NiceButton _; - section.BaseAdd(_ = new NiceButton(0, 0, 20, TEXTBOX_HEIGHT, ButtonAction.Activate, "<>") { IsSelectable = false }); - _.SetTooltip("Minimize section"); - _.X = rightArea.Width - 45; - _.MouseUp += MinimizeSectionMouseUp; - } - - section.Add(_useModernPaperdoll = AddCheckBox( - null, "", - _currentProfile.UseModernPaperdoll, 0, 0 - )); - section.AddRight(AddLabel(null, "Use modern paperdoll", 0, 0)); - - section.PushIndent(); - section.Add(_paperDollHue = new ModernColorPicker.HueDisplay(ProfileManager.CurrentProfile.ModernPaperDollHue, null, true)); - section.AddRight(AddLabel(null, "Modern paperdoll hue", 0, 0)); - - section.Add(_durabilityBarHue = new ModernColorPicker.HueDisplay(ProfileManager.CurrentProfile.ModernPaperDollDurabilityHue, null, true)); - section.AddRight(AddLabel(null, "Modern paperdoll durability bar hue", 0, 0)); - - section.Add(_modernPaperdollDurabilityPercent = AddInputField(null, 0, 0, 75, TEXTBOX_HEIGHT)); - _modernPaperdollDurabilityPercent.SetText(_currentProfile.ModernPaperDoll_DurabilityPercent.ToString()); - section.AddRight(AddLabel(null, "Show durability bar below %", 0, 0)); - - section.PopIndent(); - - rightArea.Add(section); - startY += section.Height + SPACING; - }//Modern paperdoll - - { - SettingsSection section = new SettingsSection("Nameplates", rightArea.Width) { Y = startY }; - - { - NiceButton _; - section.BaseAdd(_ = new NiceButton(0, 0, 20, TEXTBOX_HEIGHT, ButtonAction.Activate, "<>") { IsSelectable = false }); - _.SetTooltip("Minimize section"); - _.X = rightArea.Width - 45; - _.MouseUp += MinimizeSectionMouseUp; - } - - { - section.Add( - _namePlateHealthBar = AddCheckBox(null, "", _currentProfile.NamePlateHealthBar, 0, 0) - ); - - section.AddRight(AddLabel(null, "Name plates also act as health bar", 0, 0)); - - section.PushIndent(); - section.Add(AddLabel(null, "HP opacity", 0, 0)); - section.AddRight(_namePlateHealthBarOpacity = AddHSlider( - null, - 0, 100, - _currentProfile.NamePlateHealthBarOpacity, - 0, 0, - 200 - )); - - section.Add(_namePlateShowAtFullHealth = AddCheckBox(null, "", _currentProfile.NamePlateHideAtFullHealth, 0, 0)); - section.AddRight(new Label("Hide nameplates above 100% hp.", true, HUE_FONT, font: FONT)); - section.PushIndent(); - - section.Add(_namePlateHealthOnlyWarmode = AddCheckBox(null, "", _currentProfile.NamePlateHideAtFullHealthInWarmode, 0, 0)); - section.AddRight(new Label("Only while in warmode", true, HUE_FONT, font: FONT)); - section.PopIndent(); - section.PopIndent(); - - section.Add(AddLabel(null, "Border opacity", 0, 0)); - section.AddRight(_nameplateBorderOpacity = AddHSlider( - null, - 0, 100, - _currentProfile.NamePlateBorderOpacity, - 0, 0, - 200 - )); - } //Name plate health bar - - { - section.Add(AddLabel(null, "Name plate background opacity", 0, 0)); - section.AddRight(_namePlateOpacity = AddHSlider( - null, - 0, 100, - _currentProfile.NamePlateOpacity, - 0, 0, - 200 - )); - } //Name plate background opacity - - rightArea.Add(section); - startY += section.Height + SPACING; - } //Name plates - - { - SettingsSection section = new SettingsSection("Mobiles", rightArea.Width) { Y = startY }; - - { - NiceButton _; - section.BaseAdd(_ = new NiceButton(0, 0, 20, TEXTBOX_HEIGHT, ButtonAction.Activate, "<>") { IsSelectable = false }); - _.SetTooltip("Minimize section"); - _.X = rightArea.Width - 45; - _.MouseUp += MinimizeSectionMouseUp; - } - - section.Add(_damageHueSelf = AddColorBox(null, 0, 0, _currentProfile.DamageHueSelf, "")); - section.AddRight(new Label("Damage to self", true, HUE_FONT, font: FONT)); - - section.AddRight(_damageHueOther = AddColorBox(null, 0, 0, _currentProfile.DamageHueOther, "")); - section.AddRight(new Label("Damage to others", true, HUE_FONT, font: FONT)); - - section.Add(_damageHuePet = AddColorBox(null, 0, 0, _currentProfile.DamageHuePet, "")); - section.AddRight(new Label("Damage to pets", true, HUE_FONT, font: FONT)); - _damageHuePet.SetTooltip("Due to client limitations magic summons don't work here."); - - section.Add(_damageHueAlly = AddColorBox(null, 0, 0, _currentProfile.DamageHueAlly, "")); - section.AddRight(new Label("Damage to allies", true, HUE_FONT, font: FONT)); - - section.Add(_damageHueLastAttack = AddColorBox(null, 0, 0, _currentProfile.DamageHueLastAttck, "")); - section.AddRight(new Label("Damage to last attack", true, HUE_FONT, font: FONT)); - _damageHueLastAttack.SetTooltip("Damage done to the last mobile you attacked, due to client limitations this is not neccesarily the damage YOU did to them."); - - section.Add(_displayPartyChatOverhead = AddCheckBox(null, "", _currentProfile.DisplayPartyChatOverhead, 0, 0)); - section.AddRight(AddLabel(null, "Display party chat over players heads.", 0, 0)); - - section.Add(AddLabel(null, "Overhead text width", 0, 0)); - section.AddRight(_overheadTextWidth = AddHSlider(null, 100, 600, _currentProfile.OverheadChatWidth, 0, 0, 200)); - - section.Add(AddLabel(null, "Below mobile health line size", 0, 0)); - section.AddRight(_healthLineSizeMultiplier = AddHSlider(null, 1, 5, _currentProfile.HealthLineSizeMultiplier, 0, 0, 150)); - - section.Add(AddLabel(null, "Open health bar gump for last attack automatically", 0, 0)); - section.AddRight(_openHealthBarForLastAttack = AddCheckBox(null, "", _currentProfile.OpenHealthBarForLastAttack, 0, 0)); - - rightArea.Add(section); - startY += section.Height + SPACING; - } //Mobiles - - { - SettingsSection section = new SettingsSection("Misc", rightArea.Width) { Y = startY }; - - { - NiceButton _; - section.BaseAdd(_ = new NiceButton(0, 0, 20, TEXTBOX_HEIGHT, ButtonAction.Activate, "<>") { IsSelectable = false }); - _.SetTooltip("Minimize section"); - _.X = rightArea.Width - 45; - _.MouseUp += MinimizeSectionMouseUp; - } - - { - section.Add(_disableSystemChat = AddCheckBox( - null, - "", - _currentProfile.DisableSystemChat, - 0, 0 - )); - section.AddRight(AddLabel(null, "Disable system chat", 0, 0)); - } //System chat - - { - section.Add(AddLabel(null, "Hidden Body Opacity", 0, 0)); - - section.AddRight - ( - _hiddenBodyAlpha = AddHSlider( - null, - 0, - 100, - _currentProfile.HiddenBodyAlpha, - 0, - 0, - 200 - ), - 2 - ); - section.PushIndent(); - section.Add - ( - _hiddenBodyHue = AddColorBox( - null, - 0, - 0, - _currentProfile.HiddenBodyHue, - "" - ) - ); - section.AddRight(AddLabel(null, "Hidden Body Hue", 0, 0)); - section.PopIndent(); - } //Hidden body mods - - section.Add(AddLabel(null, "Regular player opacity", 0, 0)); - section.AddRight(_regularPlayerAlpha = AddHSlider(null, 0, 100, _currentProfile.PlayerConstantAlpha, 0, 0, 200)); - - { - section.Add(AddLabel(null, "Auto Follow Distance", 0, 0)); - section.AddRight( - _autoFollowDistance = AddInputField( - null, - 0, - 0, - 50, - TEXTBOX_HEIGHT, - numbersOnly: true, - maxCharCount: 10 - ) - ); - _autoFollowDistance.SetText(_currentProfile.AutoFollowDistance.ToString()); - } //Auto follow distance - - { - section.Add(_enableImprovedBuffGump = AddCheckBox( - null, - "Enable improved buff gump", - _currentProfile.UseImprovedBuffBar, - 0, 0 - )); - - section.AddRight(_improvedBuffBarHue = AddColorBox( - null, - 0, 0, - _currentProfile.ImprovedBuffBarHue, - "" - )); - _improvedBuffBarHue.SetTooltip("Buff Bar Hue"); - }//Improved buff gump - - { - section.Add(_mainWindowHuePicker = new ModernColorPicker.HueDisplay(_currentProfile.MainWindowBackgroundHue, null, true)); - section.AddRight(AddLabel(null, "Main game window background hue", 0, 0)); - }//Main window background hue - - section.Add(_enableHealthIndicator = AddCheckBox(null, "Enable health indicator", _currentProfile.EnableHealthIndicator, 0, 0)); - section.PushIndent(); - section.Add(AddLabel(null, "Only show below hp %", 0, 0)); - section.AddRight(_healthIndicatorPercentage = AddInputField(null, 0, 0, 150, TEXTBOX_HEIGHT, numbersOnly: true)); - _healthIndicatorPercentage.SetText((_currentProfile.ShowHealthIndicatorBelow * 100).ToString()); - - section.Add(AddLabel(null, "Size", 0, 0)); - section.AddRight(_healthIndicatorWidth = AddInputField(null, 0, 0, 150, TEXTBOX_HEIGHT, numbersOnly: true)); - _healthIndicatorWidth.SetText(_currentProfile.HealthIndicatorWidth.ToString()); - section.PopIndent(); - - section.Add(AddLabel(null, "Spell Icon Scale", 0, 0)); - section.AddRight(_spellIconScale = AddHSlider(null, 50, 300, _currentProfile.SpellIconScale, 0, 0, 200)); - _spellIconScale.SetTooltip("This will take effect after you log out/back in or close and reopen the spell icon."); - - section.Add(AddLabel(null, "Display matching macro hotkeys on spell icons", 0, 0)); - section.AddRight(_spellIconDisplayHotkey = AddCheckBox(null, "", _currentProfile.SpellIcon_DisplayHotkey, 0, 0)); - - section.PushIndent(); - section.Add(AddLabel(null, "Hotkey text hue", 0, 0)); - section.AddRight(_spellIconHotkeyHue = new ModernColorPicker.HueDisplay(_currentProfile.SpellIcon_HotkeyHue, null, true)); - section.PopIndent(); - - section.Add(AddLabel(null, "Enable opacity adjustment via Alt + Scroll", 0, 0)); - section.AddRight(_enableAlphaScrollWheel = AddCheckBox(null, "", _currentProfile.EnableAlphaScrollingOnGumps, 0, 0)); - _enableAlphaScrollWheel.SetTooltip("This is to quickly adjust a gump's opacity(Not all gumps are supported)."); - - section.Add(AddLabel(null, "Use advanced shop gump", 0, 0)); - section.AddRight(_useModernShop = AddCheckBox(null, "", _currentProfile.UseModernShopGump, 0, 0)); - - section.Add(AddLabel(null, "Display skill progress bar on skill changes", 0, 0)); - section.AddRight(_skillProgressBarOnChange = AddCheckBox(null, "", _currentProfile.DisplaySkillBarOnChange, 0, 0)); - - Label _label; - section.Add(_label = AddLabel(null, "Skill progress bar format", 0, 0)); - section.AddRight(_skillProgressBarFormat = AddInputField(null, 0, 0, 250, TEXTBOX_HEIGHT)); - _skillProgressBarFormat.SetText(_currentProfile.SkillBarFormat); - - - section.Add(AddLabel(null, "Display spell indicators", 0, 0)); - section.AddRight(_displaySpellIndicators = AddCheckBox(null, "", _currentProfile.EnableSpellIndicators, 0, 0)); - NiceButton _importSpellConfig; - section.AddRight(_importSpellConfig = new NiceButton(0, 0, 150, TEXTBOX_HEIGHT, ButtonAction.Activate, "Import from url") { IsSelectable = false, DisplayBorder = true }); - _importSpellConfig.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - UIManager.Add( - new InputRequest("Enter the url for the spell config. /c[red]This will override your current config.", "Download", "Cancel", (r, s) => - { - if (r == InputRequest.Result.BUTTON1 && !string.IsNullOrEmpty(s)) - { - if (Uri.TryCreate(s, UriKind.Absolute, out var uri)) - { - GameActions.Print("Attempting to download spell config.."); - Task.Factory.StartNew(() => - { - try - { - using HttpClient httpClient = new HttpClient(); - string result = httpClient.GetStringAsync(uri).Result; - - if (SpellVisualRangeManager.Instance.LoadFromString(result)) - { - GameActions.Print("Succesfully downloaded new spell config."); - } - } - catch(Exception ex) - { - GameActions.Print($"Failed to download the spell config. ({ex.Message})"); - } - }); - } - } - }) - { - X = (Client.Game.Window.ClientBounds.Width >> 1 )- 50, - Y = (Client.Game.Window.ClientBounds.Height >> 1 )- 50 - } - ); - } - }; - - - section.Add(AddLabel(null, "Close anchored healthbars when automatically closing healthbars", 0, 0)); - section.AddRight(_closeHPBarWhenAnchored = AddCheckBox(null, "", _currentProfile.CloseHealthBarIfAnchored, 0, 0)); - - - NiceButton autoLoot; - section.Add(autoLoot = new NiceButton(0, 0, 150, TEXTBOX_HEIGHT, ButtonAction.Activate, "Open auto loot options") { IsSelectable = false, DisplayBorder = true }); - autoLoot.MouseUp += (s, e) => { - if(e.Button == MouseButtonType.Left) - { - AutoLootOptions.AddToUI(); - } - }; - - rightArea.Add(section); - startY += section.Height + SPACING + 30; - } //Misc - - { - SettingsSection section = new SettingsSection("Tooltips", rightArea.Width) { Y = startY }; - - { - NiceButton _; - section.BaseAdd(_ = new NiceButton(0, 0, 20, TEXTBOX_HEIGHT, ButtonAction.Activate, "<>") { IsSelectable = false }); - _.SetTooltip("Minimize section"); - _.X = rightArea.Width - 45; - _.MouseUp += MinimizeSectionMouseUp; - } - - section.Add(_leftAlignToolTips = AddCheckBox(null, "Align tooltips to the left side", _currentProfile.LeftAlignToolTips, 0, 0)); - section.PushIndent(); - section.Add(_forceCenterAlignMobileTooltips = AddCheckBox(null, "Center align mobile name tooltips", _currentProfile.ForceCenterAlignTooltipMobiles, 0, 0)); - section.PopIndent(); - - section.Add(AddLabel(null, "Tooltip background hue", 0, 0)); - section.AddRight(_tooltipBGHue = new ModernColorPicker.HueDisplay(_currentProfile.ToolTipBGHue, null, true)); - - section.Add(AddLabel(null, "Tooltip header format (Item name)", 0, 0)); - section.AddRight(_tooltipHeaderFormat = AddInputField(null, 0, 0, 250, TEXTBOX_HEIGHT)); - _tooltipHeaderFormat.SetText(_currentProfile.TooltipHeaderFormat); - - NiceButton ttipO = new NiceButton(0, 0, 250, TEXTBOX_HEIGHT, ButtonAction.Activate, "Open tooltip override settings") { IsSelectable = false, DisplayBorder = true }; - ttipO.SetTooltip("Warning: This is an advanced feature."); - ttipO.MouseUp += (s, e) => { UIManager.GetGump()?.Dispose(); UIManager.Add(new ToolTipOverideMenu()); }; - - section.Add(ttipO); - - rightArea.Add(section); - startY += section.Height + SPACING; - }// Tooltip sections - - { - SettingsSection section = new SettingsSection("Font settings", rightArea.Width) { Y = startY }; - - { - NiceButton _; - section.BaseAdd(_ = new NiceButton(0, 0, 20, TEXTBOX_HEIGHT, ButtonAction.Activate, "<>") { IsSelectable = false }); - _.SetTooltip("Minimize section"); - _.X = rightArea.Width - 45; - _.MouseUp += MinimizeSectionMouseUp; - } - - section.Add(AddLabel(null, "TTF Font text border size", 0, 0)); - section.AddRight(_textStrokeSize = AddHSlider(null, 0, 2, _currentProfile.TextBorderSize, 0, 0, 150)); - - section.Add(new Line(0, 0, section.Width, 1, Color.Gray.PackedValue)); - - section.Add(AddLabel(null, "InfoBar font", 0, 0)); - section.AddRight(_infoBarFont = GenerateFontSelector(_currentProfile.InfoBarFont)); - - section.PushIndent(); - section.Add(AddLabel(null, "InfoBar font size", 0, 0)); - section.AddRight(_infoBarFontSize = AddHSlider(null, 5, 40, _currentProfile.InfoBarFontSize, 0, 0, 200)); - section.PopIndent(); - - section.Add(new Line(0, 0, section.Width, 1, Color.Gray.PackedValue)); - - - section.Add(AddLabel(null, "System chat font", 0, 0)); - section.AddRight(_gameWindowSideChatFont = GenerateFontSelector(_currentProfile.GameWindowSideChatFont)); - - section.PushIndent(); - section.Add(AddLabel(null, "System chat font size", 0, 0)); - section.AddRight(_gameWindowSideChatFontSize = AddHSlider(null, 5, 40, _currentProfile.GameWindowSideChatFontSize, 0, 0, 200)); - section.PopIndent(); - - section.Add(new Line(0, 0, section.Width, 1, Color.Gray.PackedValue)); - - - section.Add(AddLabel(null, "Tooltip font", 0, 0)); - section.AddRight(_tooltipFontSelect = GenerateFontSelector(_currentProfile.SelectedToolTipFont)); - - section.PushIndent(); - section.Add(AddLabel(null, "Tooltip font size", 0, 0)); - section.AddRight(_tooltipFontSize = AddHSlider(null, 5, 40, _currentProfile.SelectedToolTipFontSize, 0, 0, 200)); - section.PopIndent(); - - section.Add(new Line(0, 0, section.Width, 1, Color.Gray.PackedValue)); - - - section.Add(AddLabel(null, "Overhead text font", 0, 0)); - section.AddRight(_overheadFont = GenerateFontSelector(_currentProfile.OverheadChatFont)); - - section.PushIndent(); - section.Add(AddLabel(null, "Overhead text font size", 0, 0)); - section.AddRight(_overheadFontSize = AddHSlider(null, 5, 40, _currentProfile.OverheadChatFontSize, 0, 0, 200)); - section.PopIndent(); - - section.Add(new Line(0, 0, section.Width, 1, Color.Gray.PackedValue)); - - - section.Add(AddLabel(null, "Journal text font", 0, 0)); - section.AddRight(_journalFontSelection = GenerateFontSelector(_currentProfile.SelectedTTFJournalFont)); - - section.PushIndent(); - section.Add(AddLabel(null, "Journal font size", 0, 0)); - section.Add(_journalFontSize = AddHSlider(null, 5, 40, _currentProfile.SelectedJournalFontSize, 0, 0, 200)); - section.PopIndent(); - - rightArea.Add(section); - startY += section.Height + SPACING + 30; - }// Font settings - - { - SettingsSection section = new SettingsSection("Global Settings", rightArea.Width) { Y = startY }; - - { - NiceButton _; - section.BaseAdd(_ = new NiceButton(0, 0, 20, TEXTBOX_HEIGHT, ButtonAction.Activate, "<>") { IsSelectable = false }); - _.SetTooltip("Minimize section"); - _.X = rightArea.Width - 45; - _.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - int diff = section.Height - 25; - if (section.Children[2].IsVisible) - diff = -section.Height + 25; - for (int i = rightArea.Children.IndexOf(section) + 1; i < rightArea.Children.Count; i++) - if (rightArea.Children[i] != section) - rightArea.Children[i].Y += diff; - section.Children[2].IsVisible = !section.Children[2].IsVisible; - } - }; - } - - - string rootpath; - - if (string.IsNullOrWhiteSpace(Settings.GlobalSettings.ProfilesPath)) - { - rootpath = Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Profiles"); - } - else - { - rootpath = Settings.GlobalSettings.ProfilesPath; - } - - List locations = new List(); - List sameServerLocations = new List(); - string[] allAccounts = Directory.GetDirectories(rootpath); - - foreach (string account in allAccounts) - { - string[] allServers = Directory.GetDirectories(account); - foreach (string server in allServers) - { - string[] allCharacters = Directory.GetDirectories(server); - foreach (string character in allCharacters) - { - locations.Add(new ProfileLocationData(server, account, character)); - if(_currentProfile.ServerName == Path.GetFileName(server)) - { - sameServerLocations.Add(new ProfileLocationData(server, account, character)); - } - } - } - } - - section.Add(new Label( - $"! Warning !
" + - $"This will override all other character's profile options!
" + - $"This is not reversable!
" + - $"You have {locations.Count - 1} other profiles that will may overridden with the settings in this profile.
" + - $"
This will not override: Macros, skill groups, info bar, grid container data, or gump saved positions.
" - , true, 32, section.Width - 32, align: TEXT_ALIGN_TYPE.TS_CENTER, ishtml: true)); - - NiceButton overrideButton; - section.Add(overrideButton = new NiceButton(0, 0, section.Width - 32, 20, ButtonAction.Activate, $"Override {locations.Count - 1} other profiles with this one.") { IsSelectable = false }); - overrideButton.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - OverrideAllProfiles(locations); - section.BaseAdd(new FadingLabel(7, $"{locations.Count - 1} profiles overriden.", true, 0xff) { X = overrideButton.X, Y = overrideButton.Y }); - } - }; - - NiceButton overrideSSButton; - section.Add(overrideSSButton = new NiceButton(0, 0, section.Width - 32, 20, ButtonAction.Activate, $"Override {sameServerLocations.Count - 1} other profiles on this same server with this one.") { IsSelectable = false }); - overrideSSButton.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - OverrideAllProfiles(sameServerLocations); - section.BaseAdd(new FadingLabel(7, $"{sameServerLocations.Count - 1} profiles overriden.", true, 0xff) { X = overrideButton.X, Y = overrideButton.Y }); - } - }; - - rightArea.Add(section); - startY += section.Height + SPACING; - }// Global settings - - - //{ - // SettingsSection section = new SettingsSection("Misc", rightArea.Width) { Y = startY }; - - // { - // NiceButton _; - // section.BaseAdd(_ = new NiceButton(0, 0, 20, TEXTBOX_HEIGHT, ButtonAction.Activate, "<>") { IsSelectable = false }); - // _.SetTooltip("Minimize section"); - // _.X = rightArea.Width - 45; - // _.MouseUp += MinimizeSectionMouseUp; - // } - - // rightArea.Add(section); - // startY += section.Height + SPACING; - //}// Blank setting section - - Add(rightArea, PAGE); - - foreach (SettingsSection section in rightArea.Children.OfType()) - { - section.Update(); - int diff = section.Height - 25; - if (section.Children[2].IsVisible) - diff = -section.Height + 25; - for (int i = rightArea.Children.IndexOf(section) + 1; i < rightArea.Children.Count; i++) - { - if (rightArea.Children[i] != section) - rightArea.Children[i].Y += diff; - } - section.Children[2].IsVisible = !section.Children[2].IsVisible; - } - } - - private void MinimizeSectionMouseUp(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtonType.Left) - { - if (sender is NiceButton) - { - SettingsSection section = ((NiceButton)sender).Parent as SettingsSection; - - ScrollArea rightArea = section.Parent as ScrollArea; - - int diff = section.Height - 25; - if (section.Children[2].IsVisible) - diff = -section.Height + 25; - - for (int i = rightArea.Children.IndexOf(section) + 1; i < rightArea.Children.Count; i++) - if (rightArea.Children[i] != section) - rightArea.Children[i].Y += diff; - section.Children[2].IsVisible = !section.Children[2].IsVisible; - } - } - } - - private class ProfileLocationData - { - public readonly DirectoryInfo Server; - public readonly DirectoryInfo Username; - public readonly DirectoryInfo Character; - - public ProfileLocationData(string server, string username, string character) - { - this.Server = new DirectoryInfo(server); - this.Username = new DirectoryInfo(username); - this.Character = new DirectoryInfo(character); - } - - public override string ToString() - { - return Character.ToString(); - } - } - - private void OverrideAllProfiles(List allProfiles) - { - foreach (var profile in allProfiles) - { - ProfileManager.CurrentProfile.Save(profile.ToString(), false); - } - } - - public Combobox GenerateFontSelector(string selectedFont = "") - { - string[] fontArray = TrueTypeLoader.Instance.Fonts; - int selectedFontInd = Array.IndexOf(fontArray, selectedFont); - return AddCombobox( - null, - fontArray, - selectedFontInd < 0 ? 0 : selectedFontInd, - 0, 0, 200 - ); - } - - public Control GenConditionControl(int key, int width, bool createIfNotExists) - { - CoolDownBar.CoolDownConditionData data = CoolDownBar.CoolDownConditionData.GetConditionData(key, createIfNotExists); - Area main = new Area(); - main.Width = width; - main.Height = 60; - - AlphaBlendControl _background = new AlphaBlendControl(); - _background.Width = width; - _background.Height = main.Height; - main.Add(_background); - - - NiceButton _delete = new NiceButton(1, 1, 22, TEXTBOX_HEIGHT, ButtonAction.Activate, "X"); - _delete.SetTooltip("Delete this cooldown bar"); - _delete.MouseUp += (sender, e) => - { - if (e.Button == MouseButtonType.Left) - { - CoolDownBar.CoolDownConditionData.RemoveCondition(key); - main.Dispose(); - } - }; - main.Add(_delete); - - - Label _hueLabel = new Label("Hue:", true, HUE_FONT, 25, FONT); - _hueLabel.X = _delete.X + _delete.Width + 5; - _hueLabel.Y = 1; - main.Add(_hueLabel); - - ClickableColorBox _hueSelector = new ClickableColorBox(_hueLabel.X + _hueLabel.Width + 2, 1, 13, 14, data.hue); - main.Add(_hueSelector); - - - InputField _name = AddInputField(null, _hueSelector.X + _hueSelector.Width + 10, 1, 100, TEXTBOX_HEIGHT); - _name.SetText(data.label); - main.Add(_name); - - - - Label _cooldownLabel = new Label("Cooldown:", true, HUE_FONT, 52, FONT); - _cooldownLabel.X = _name.X + _name.Width + 5; - _cooldownLabel.Y = 1; - main.Add(_cooldownLabel); - - InputField _cooldown = AddInputField( - null, 0, 1, - 25, TEXTBOX_HEIGHT, - numbersOnly: true - ); - _cooldown.X = _cooldownLabel.X + _cooldownLabel.Width + 5; - _cooldown.SetText(data.cooldown.ToString()); - main.Add(_cooldown); - - Combobox _message_type = AddCombobox(null, new string[] { "All", "Self", "Other" }, data.message_type, _cooldown.X + _cooldown.Width + 5, 1, 80); - main.Add(_message_type); - - InputField _conditionText = AddInputField( - null, 1, _delete.Height + 5, - main.Width - 25, TEXTBOX_HEIGHT - ); - _conditionText.SetText(data.trigger); - main.Add(_conditionText); - - Checkbox _replaceIfExists = AddCheckBox(null, "", data.replace_if_exists, _conditionText.X + _conditionText.Width + 2, _conditionText.Y); - _replaceIfExists.SetTooltip("Replace any active cooldown of this type with a new one if triggered again."); - main.Add(_replaceIfExists); - - NiceButton _save = new NiceButton(main.Width - 37, 1, 37, TEXTBOX_HEIGHT, ButtonAction.Activate, "Save"); - _save.IsSelectable = false; - _save.MouseUp += (s, e) => - { - CoolDownBar.CoolDownConditionData.SaveCondition(key, _hueSelector.Hue, _name.Text, _conditionText.Text, int.Parse(_cooldown.Text), false, _message_type.SelectedIndex, _replaceIfExists.IsChecked); - }; - main.Add(_save); - - NiceButton _preview = new NiceButton(_save.X - 54, 1, 54, TEXTBOX_HEIGHT, ButtonAction.Activate, "Preview"); - _preview.IsSelectable = false; - _preview.MouseUp += (s, e) => - { - CoolDownBarManager.AddCoolDownBar(TimeSpan.FromSeconds(int.Parse(_cooldown.Text)), _name.Text, _hueSelector.Hue, _replaceIfExists.IsChecked); - }; - main.Add(_preview); - return main; - } - - public override void OnButtonClick(int buttonID) - { - if (buttonID == (int)Buttons.Last + 1) - { - // it's the macro buttonssss - return; - } - - switch ((Buttons)buttonID) - { - case Buttons.Disabled: break; - - case Buttons.Cancel: - Dispose(); - - break; - - case Buttons.Apply: - Apply(); - - break; - - case Buttons.Default: - SetDefault(); - - break; - - case Buttons.Ok: - Apply(); - Dispose(); - - break; - - case Buttons.NewMacro: break; - - case Buttons.DeleteMacro: break; - case Buttons.OpenIgnoreList: - // If other IgnoreManagerGump exist - Dispose it - UIManager.GetGump()?.Dispose(); - // Open new - UIManager.Add(new IgnoreManagerGump()); - break; - } - } - - private void SetDefault() - { - switch (ActivePage) - { - case 1: // general - _sliderFPS.Value = 60; - _reduceFPSWhenInactive.IsChecked = true; - _highlightObjects.IsChecked = true; - _enableTopbar.IsChecked = false; - _holdDownKeyTab.IsChecked = true; - _holdDownKeyAlt.IsChecked = true; - _closeAllAnchoredGumpsWithRClick.IsChecked = false; - _holdShiftForContext.IsChecked = false; - _holdAltToMoveGumps.IsChecked = false; - _holdShiftToSplitStack.IsChecked = false; - _enablePathfind.IsChecked = false; - _useShiftPathfind.IsChecked = false; - _alwaysRun.IsChecked = false; - _alwaysRunUnlessHidden.IsChecked = false; - _showHpMobile.IsChecked = false; - _hpComboBox.SelectedIndex = 0; - _hpComboBoxShowWhen.SelectedIndex = 0; - _highlightByPoisoned.IsChecked = true; - _highlightByParalyzed.IsChecked = true; - _highlightByInvul.IsChecked = true; - _poisonColorPickerBox.Hue = 0x0044; - _paralyzedColorPickerBox.Hue = 0x014C; - _invulnerableColorPickerBox.Hue = 0x0030; - _drawRoofs.IsChecked = false; - _enableCaveBorder.IsChecked = false; - _treeToStumps.IsChecked = false; - _hideVegetation.IsChecked = false; - _noColorOutOfRangeObjects.IsChecked = false; - _circleOfTranspRadius.Value = Constants.MIN_CIRCLE_OF_TRANSPARENCY_RADIUS; - _cotType.SelectedIndex = 0; - _useCircleOfTransparency.IsChecked = false; - _healtbarType.SelectedIndex = 0; - _fieldsType.SelectedIndex = 0; - _useStandardSkillsGump.IsChecked = true; - _showCorpseNameIncoming.IsChecked = true; - _showMobileNameIncoming.IsChecked = true; - _gridLoot.SelectedIndex = 0; - _sallosEasyGrab.IsChecked = false; - _partyInviteGump.IsChecked = false; - _showHouseContent.IsChecked = false; - _objectsFading.IsChecked = true; - _textFading.IsChecked = true; - _enableDragSelect.IsChecked = false; - _showTargetRangeIndicator.IsChecked = false; - _customBars.IsChecked = false; - _customBarsBBG.IsChecked = false; - _autoOpenCorpse.IsChecked = false; - _autoOpenDoors.IsChecked = false; - _smoothDoors.IsChecked = false; - _skipEmptyCorpse.IsChecked = false; - _saveHealthbars.IsChecked = false; - _use_smooth_boat_movement.IsChecked = false; - _hideScreenshotStoredInMessage.IsChecked = false; - _use_old_status_gump.IsChecked = false; - _auraType.SelectedIndex = 0; - _fieldsType.SelectedIndex = 0; - _journalOpacity.Value = 50; - - _showSkillsMessage.IsChecked = true; - _showSkillsMessageDelta.Value = 1; - _showStatsMessage.IsChecked = true; - - _dragSelectStartX.Value = 100; - _dragSelectStartY.Value = 100; - _dragSelectAsAnchor.IsChecked = false; - _hiddenBodyAlpha.Value = 40; - _hiddenBodyHue.Hue = 0x038E; - - break; - - case 2: // sounds - _enableSounds.IsChecked = true; - _enableMusic.IsChecked = true; - _combatMusic.IsChecked = true; - _soundsVolume.Value = 100; - _musicVolume.Value = 100; - _musicInBackground.IsChecked = false; - _footStepsSound.IsChecked = true; - _loginMusicVolume.Value = 100; - _loginMusic.IsChecked = true; - _soundsVolume.IsVisible = _enableSounds.IsChecked; - _musicVolume.IsVisible = _enableMusic.IsChecked; - - break; - - case 3: // video - _windowBorderless.IsChecked = false; - _zoomCheckbox.IsChecked = false; - _restorezoomCheckbox.IsChecked = false; - _gameWindowWidth.SetText("600"); - _gameWindowHeight.SetText("480"); - _gameWindowPositionX.SetText("20"); - _gameWindowPositionY.SetText("20"); - _gameWindowLock.IsChecked = false; - _gameWindowFullsize.IsChecked = false; - _enableDeathScreen.IsChecked = true; - _enableBlackWhiteEffect.IsChecked = true; - Client.Game.Scene.Camera.Zoom = 1f; - _currentProfile.DefaultScale = 1f; - _lightBar.Value = 0; - _enableLight.IsChecked = false; - _lightLevelType.SelectedIndex = 0; - _useColoredLights.IsChecked = false; - _darkNights.IsChecked = false; - _enableShadows.IsChecked = true; - _enableShadowsStatics.IsChecked = true; - _terrainShadowLevel.Value = 15; - _runMouseInSeparateThread.IsChecked = true; - _auraMouse.IsChecked = true; - _partyAura.IsChecked = true; - _animatedWaterEffect.IsChecked = false; - _partyAuraColorPickerBox.Hue = 0x0044; - - break; - - case 4: // macros - break; - - case 5: // tooltip - _use_tooltip.IsChecked = true; - _tooltip_font_hue.Hue = 0xFFFF; - _delay_before_display_tooltip.Value = 200; - _tooltip_background_opacity.Value = 70; - _tooltip_zoom.Value = 100; - _tooltip_font_selector.SetSelectedFont(1); - - break; - - case 6: // fonts - _fontSelectorChat.SetSelectedFont(0); - _overrideAllFonts.IsChecked = false; - _overrideAllFontsIsUnicodeCheckbox.SelectedIndex = 1; - - break; - - case 7: // speech - _scaleSpeechDelay.IsChecked = true; - _sliderSpeechDelay.Value = 100; - _speechColorPickerBox.Hue = 0x02B2; - _emoteColorPickerBox.Hue = 0x0021; - _yellColorPickerBox.Hue = 0x0021; - _whisperColorPickerBox.Hue = 0x0033; - _partyMessageColorPickerBox.Hue = 0x0044; - _guildMessageColorPickerBox.Hue = 0x0044; - _allyMessageColorPickerBox.Hue = 0x0057; - _chatMessageColorPickerBox.Hue = 0x0256; - _chatAfterEnter.IsChecked = false; - UIManager.SystemChat.IsActive = !_chatAfterEnter.IsChecked; - _chatAdditionalButtonsCheckbox.IsChecked = true; - _chatShiftEnterCheckbox.IsChecked = true; - _saveJournalCheckBox.IsChecked = false; - _hideChatGradient.IsChecked = false; - _ignoreGuildMessages.IsChecked = false; - _ignoreAllianceMessages.IsChecked = false; - - break; - - case 8: // combat - _innocentColorPickerBox.Hue = 0x005A; - _friendColorPickerBox.Hue = 0x0044; - _crimialColorPickerBox.Hue = 0x03b2; - _canAttackColorPickerBox.Hue = 0x03b2; - _murdererColorPickerBox.Hue = 0x0023; - _enemyColorPickerBox.Hue = 0x0031; - _queryBeforAttackCheckbox.IsChecked = true; - _queryBeforeBeneficialCheckbox.IsChecked = false; - _uiButtonsSingleClick.IsChecked = false; - _buffBarTime.IsChecked = false; - _enableFastSpellsAssign.IsChecked = false; - _beneficColorPickerBox.Hue = 0x0059; - _harmfulColorPickerBox.Hue = 0x0020; - _neutralColorPickerBox.Hue = 0x03b2; - _spellFormatBox.SetText(ResGumps.SpellFormat_Default); - _spellColoringCheckbox.IsChecked = false; - _spellFormatCheckbox.IsChecked = false; - - break; - - case 9: // counters - _enableCounters.IsChecked = false; - _highlightOnUse.IsChecked = false; - _enableAbbreviatedAmount.IsChecked = false; - _columns.SetText("1"); - _rows.SetText("1"); - _cellSize.Value = 40; - _highlightOnAmount.IsChecked = false; - _highlightAmount.SetText("5"); - _abbreviatedAmount.SetText("1000"); - - break; - - case 10: // info bar - - - break; - - case 11: // containers - _containerOpacity.Value = 50; - _containersScale.Value = 100; - _containerScaleItems.IsChecked = false; - _useGridLayoutContainerGumps.IsChecked = true; - _useLargeContianersGumps.IsChecked = false; - _containerDoubleClickToLoot.IsChecked = false; - _relativeDragAnDropItems.IsChecked = false; - _highlightContainersWhenMouseIsOver.IsChecked = false; - _overrideContainerLocation.IsChecked = false; - _overrideContainerLocationSetting.SelectedIndex = 0; - _backpackStyle.SelectedIndex = 0; - _hueContainerGumps.IsChecked = true; - - break; - - case 12: // experimental - - _disableDefaultHotkeys.IsChecked = false; - _disableArrowBtn.IsChecked = false; - _disableTabBtn.IsChecked = false; - _disableCtrlQWBtn.IsChecked = false; - _disableAutoMove.IsChecked = false; - - break; - } - } - - private void Apply() - { - WorldViewportGump vp = UIManager.GetGump(); - - // general - if (Settings.GlobalSettings.FPS != _sliderFPS.Value) - { - Client.Game.SetRefreshRate(_sliderFPS.Value); - } - - if (_currentProfile.JournalStyle != _journalStyle.SelectedIndex) - { - _currentProfile.JournalStyle = _journalStyle.SelectedIndex; - UIManager.GetGump()?.BuildBorder(); - } - - if (_currentProfile.MainWindowBackgroundHue != _mainWindowHuePicker.Hue) - { - _currentProfile.MainWindowBackgroundHue = _mainWindowHuePicker.Hue; - GameController.UpdateBackgroundHueShader(); - } - - if (_currentProfile.SelectedTTFJournalFont != TrueTypeLoader.Instance.Fonts[_journalFontSelection.SelectedIndex]) - { - _currentProfile.SelectedTTFJournalFont = TrueTypeLoader.Instance.Fonts[_journalFontSelection.SelectedIndex]; - Gump g = UIManager.GetGump(); - if (g != null) - { - g.Dispose(); - UIManager.Add(new ResizableJournal()); - } - } - - if (_currentProfile.SelectedJournalFontSize != _journalFontSize.Value) - { - _currentProfile.SelectedJournalFontSize = _journalFontSize.Value; - Gump g = UIManager.GetGump(); - if (g != null) - { - g.Dispose(); - UIManager.Add(new ResizableJournal()); - } - } - _currentProfile.CloseHealthBarIfAnchored = _closeHPBarWhenAnchored.IsChecked; - _currentProfile.UseLastMovedCooldownPosition = _uselastCooldownPosition.IsChecked; - - _currentProfile.InfoBarFont = TrueTypeLoader.Instance.Fonts[_infoBarFont.SelectedIndex]; - _currentProfile.InfoBarFontSize = _infoBarFontSize.Value; - - _currentProfile.PlayerConstantAlpha = _regularPlayerAlpha.Value; - - _currentProfile.EnableSpellIndicators = _displaySpellIndicators.IsChecked; - - _currentProfile.DisplaySkillBarOnChange = _skillProgressBarOnChange.IsChecked; - _currentProfile.SkillBarFormat = _skillProgressBarFormat.Text; - - if (_tooltipHeaderFormat.Text.Length > 0) - _currentProfile.TooltipHeaderFormat = _tooltipHeaderFormat.Text; - - _currentProfile.ToolTipBGHue = _tooltipBGHue.Hue; - - _currentProfile.OpenHealthBarForLastAttack = _openHealthBarForLastAttack.IsChecked; - _currentProfile.HealthLineSizeMultiplier = _healthLineSizeMultiplier.Value; - - _currentProfile.MaxJournalEntries = _maxJournalEntries.Value; - - if (_currentProfile.HideJournalBorder != _hideJournalBorder.IsChecked) - { - _currentProfile.HideJournalBorder = _hideJournalBorder.IsChecked; - UIManager.GetGump()?.BuildBorder(); - } - _currentProfile.HideJournalTimestamp = _hideJournalTimestamp.IsChecked; - - _currentProfile.TextBorderSize = _textStrokeSize.Value; - - _currentProfile.ForceCenterAlignTooltipMobiles = _forceCenterAlignMobileTooltips.IsChecked; - - _currentProfile.UseModernShopGump = _useModernShop.IsChecked; - - _currentProfile.OverheadChatFont = TrueTypeLoader.Instance.Fonts[_overheadFont.SelectedIndex]; - _currentProfile.OverheadChatFontSize = _overheadFontSize.Value; - _currentProfile.OverheadChatWidth = _overheadTextWidth.Value; - - _currentProfile.GameWindowSideChatFont = TrueTypeLoader.Instance.Fonts[_gameWindowSideChatFont.SelectedIndex]; - _currentProfile.GameWindowSideChatFontSize = _gameWindowSideChatFontSize.Value; - - _currentProfile.SelectedToolTipFont = TrueTypeLoader.Instance.Fonts[_tooltipFontSelect.SelectedIndex]; - _currentProfile.SelectedToolTipFontSize = _tooltipFontSize.Value; - - _currentProfile.EnableAlphaScrollingOnGumps = _enableAlphaScrollWheel.IsChecked; - _currentProfile.SpellIcon_DisplayHotkey = _spellIconDisplayHotkey.IsChecked; - _currentProfile.SpellIcon_HotkeyHue = _spellIconHotkeyHue.Hue; - _currentProfile.SpellIconScale = _spellIconScale.Value; - - _currentProfile.DisplayPartyChatOverhead = _displayPartyChatOverhead.IsChecked; - - _currentProfile.EnableHealthIndicator = _enableHealthIndicator.IsChecked; - if (int.TryParse(_healthIndicatorPercentage.Text, out int hpPercent)) - _currentProfile.ShowHealthIndicatorBelow = (float)hpPercent / 100f; - if (int.TryParse(_healthIndicatorWidth.Text, out int healthWidth)) - _currentProfile.HealthIndicatorWidth = healthWidth; - - _currentProfile.PathfindSingleClick = _pathFindSingleClick.IsChecked; - - _currentProfile.DragSelect_PlayersModifier = _dragSelectPlayersModifier.SelectedIndex; - _currentProfile.DragSelect_MonstersModifier = _dragSelectMonsertModifier.SelectedIndex; - _currentProfile.DragSelect_NameplateModifier = _dragSelectNameplateModifier.SelectedIndex; - - _currentProfile.NamePlateHideAtFullHealthInWarmode = _namePlateHealthOnlyWarmode.IsChecked; - - _currentProfile.LeftAlignToolTips = _leftAlignToolTips.IsChecked; - - _currentProfile.ModernPaperDollHue = _paperDollHue.Hue; - _currentProfile.ModernPaperDollDurabilityHue = _durabilityBarHue.Hue; - if (_currentProfile.ModernPaperDoll_DurabilityPercent.ToString() != _modernPaperdollDurabilityPercent.Text) - { - if (int.TryParse(_modernPaperdollDurabilityPercent.Text, out int percent)) - { - if (percent > 100) - percent = 100; - if (percent < 1) - percent = 1; - _currentProfile.ModernPaperDoll_DurabilityPercent = percent; - } - else - { - _modernPaperdollDurabilityPercent.SetText(_currentProfile.ModernPaperDoll_DurabilityPercent.ToString()); - } - } - - _currentProfile.UseModernPaperdoll = _useModernPaperdoll.IsChecked; - - _currentProfile.NamePlateHideAtFullHealth = _namePlateShowAtFullHealth.IsChecked; - - _currentProfile.DamageHueSelf = _damageHueSelf.Hue; - _currentProfile.DamageHuePet = _damageHuePet.Hue; - _currentProfile.DamageHueAlly = _damageHueAlly.Hue; - _currentProfile.DamageHueLastAttck = _damageHueLastAttack.Hue; - - if (_currentProfile.EnableGridContainerAnchor != _gridContainerAnchorable.IsChecked) - { - _currentProfile.EnableGridContainerAnchor = _gridContainerAnchorable.IsChecked; - foreach (GridContainer _ in UIManager.Gumps.OfType()) - { - _.AnchorType = _currentProfile.EnableGridContainerAnchor ? ANCHOR_TYPE.NONE : ANCHOR_TYPE.DISABLED; - } - } - if (_currentProfile.UseImprovedBuffBar != _enableImprovedBuffGump.IsChecked) - { - _currentProfile.UseImprovedBuffBar = _enableImprovedBuffGump.IsChecked; - if (_currentProfile.UseImprovedBuffBar) - { - foreach (Gump g in UIManager.Gumps.OfType()) - g.Dispose(); - UIManager.Add(new ImprovedBuffGump()); - } - else - { - foreach (Gump g in UIManager.Gumps.OfType()) - g.Dispose(); - UIManager.Add(new BuffGump(100, 100)); - } - } - - if (_currentProfile.Grid_BorderStyle != _gridBorderStyle.SelectedIndex || _currentProfile.Grid_HideBorder != _gridHideBorder.IsChecked) - { - _currentProfile.Grid_BorderStyle = _gridBorderStyle.SelectedIndex; - _currentProfile.Grid_HideBorder = _gridHideBorder.IsChecked; - foreach (GridContainer gridContainer in UIManager.Gumps.OfType()) - { - gridContainer.BuildBorder(); - } - } - - - _currentProfile.ImprovedBuffBarHue = _improvedBuffBarHue.Hue; - - _currentProfile.DisableSystemChat = _disableSystemChat.IsChecked; - _currentProfile.GridBorderAlpha = (byte)_gridBorderOpacity.Value; - _currentProfile.GridBorderHue = _gridBorderHue.Hue; - _currentProfile.GridContainersScale = (byte)_gridContainerScale.Value; - _currentProfile.NamePlateHealthBar = _namePlateHealthBar.IsChecked; - _currentProfile.NamePlateOpacity = (byte)_namePlateOpacity.Value; - _currentProfile.NamePlateBorderOpacity = (byte)_nameplateBorderOpacity.Value; - _currentProfile.NamePlateHealthBarOpacity = (byte)_namePlateHealthBarOpacity.Value; - _currentProfile.GridContainerSearchMode = _gridContainerSearchAlternative.SelectedIndex; - _currentProfile.GridContainerScaleItems = _gridContainerItemScale.IsChecked; - _currentProfile.GridEnableContPreview = _gridContainerPreview.IsChecked; - _currentProfile.Grid_DefaultColumns = int.Parse(_gridDefaultColumns.Text); - _currentProfile.Grid_DefaultRows = int.Parse(_gridDefaultRows.Text); - _currentProfile.Grid_UseContainerHue = _gridOverrideWithContainerHue.IsChecked; - _currentProfile.GridHightlightSize = _gridHightlightLineSize.Value; - - { - _currentProfile.CoolDownX = int.Parse(_coolDownX.Text); - _currentProfile.CoolDownY = int.Parse(_coolDownY.Text); - } //Cooldown bars - - int val = int.Parse(_autoFollowDistance.Text); - _currentProfile.AutoFollowDistance = val < 1 ? 1 : val; - - _currentProfile.HighlightGameObjects = _highlightObjects.IsChecked; - _currentProfile.ReduceFPSWhenInactive = _reduceFPSWhenInactive.IsChecked; - _currentProfile.EnablePathfind = _enablePathfind.IsChecked; - _currentProfile.UseShiftToPathfind = _useShiftPathfind.IsChecked; - _currentProfile.AlwaysRun = _alwaysRun.IsChecked; - _currentProfile.AlwaysRunUnlessHidden = _alwaysRunUnlessHidden.IsChecked; - _currentProfile.ShowMobilesHP = _showHpMobile.IsChecked; - _currentProfile.HighlightMobilesByPoisoned = _highlightByPoisoned.IsChecked; - _currentProfile.HighlightMobilesByParalize = _highlightByParalyzed.IsChecked; - _currentProfile.HighlightMobilesByInvul = _highlightByInvul.IsChecked; - _currentProfile.PoisonHue = _poisonColorPickerBox.Hue; - _currentProfile.ParalyzedHue = _paralyzedColorPickerBox.Hue; - _currentProfile.InvulnerableHue = _invulnerableColorPickerBox.Hue; - _currentProfile.MobileHPType = _hpComboBox.SelectedIndex; - _currentProfile.MobileHPShowWhen = _hpComboBoxShowWhen.SelectedIndex; - _currentProfile.HoldDownKeyTab = _holdDownKeyTab.IsChecked; - _currentProfile.HoldDownKeyAltToCloseAnchored = _holdDownKeyAlt.IsChecked; - - _currentProfile.CloseAllAnchoredGumpsInGroupWithRightClick = _closeAllAnchoredGumpsWithRClick.IsChecked; - - _currentProfile.HoldShiftForContext = _holdShiftForContext.IsChecked; - _currentProfile.HoldAltToMoveGumps = _holdAltToMoveGumps.IsChecked; - _currentProfile.HoldShiftToSplitStack = _holdShiftToSplitStack.IsChecked; - _currentProfile.CloseHealthBarType = _healtbarType.SelectedIndex; - _currentProfile.HideScreenshotStoredInMessage = _hideScreenshotStoredInMessage.IsChecked; - - _currentProfile.HiddenBodyHue = _hiddenBodyHue.Hue; - _currentProfile.HiddenBodyAlpha = (byte)_hiddenBodyAlpha.Value; - - if (_currentProfile.DrawRoofs == _drawRoofs.IsChecked) - { - _currentProfile.DrawRoofs = !_drawRoofs.IsChecked; - - Client.Game.GetScene()?.UpdateMaxDrawZ(true); - } - - if (_currentProfile.TopbarGumpIsDisabled != _enableTopbar.IsChecked) - { - if (_enableTopbar.IsChecked) - { - UIManager.GetGump()?.Dispose(); - } - else - { - TopBarGump.Create(); - } - - _currentProfile.TopbarGumpIsDisabled = _enableTopbar.IsChecked; - } - - if (_currentProfile.EnableCaveBorder != _enableCaveBorder.IsChecked) - { - StaticFilters.CleanCaveTextures(); - _currentProfile.EnableCaveBorder = _enableCaveBorder.IsChecked; - } - - if (_currentProfile.TreeToStumps != _treeToStumps.IsChecked) - { - StaticFilters.CleanTreeTextures(); - _currentProfile.TreeToStumps = _treeToStumps.IsChecked; - } - - _currentProfile.FieldsType = _fieldsType.SelectedIndex; - _currentProfile.HideVegetation = _hideVegetation.IsChecked; - _currentProfile.NoColorObjectsOutOfRange = _noColorOutOfRangeObjects.IsChecked; - _currentProfile.UseCircleOfTransparency = _useCircleOfTransparency.IsChecked; - - if (_currentProfile.CircleOfTransparencyRadius != _circleOfTranspRadius.Value) - { - _currentProfile.CircleOfTransparencyRadius = _circleOfTranspRadius.Value; - CircleOfTransparency.Create(_currentProfile.CircleOfTransparencyRadius); - } - - _currentProfile.CircleOfTransparencyType = _cotType.SelectedIndex; - _currentProfile.StandardSkillsGump = _useStandardSkillsGump.IsChecked; - - _currentProfile.AltJournalBackgroundHue = _journalBackgroundColor.Hue; - - if (_currentProfile.AltGridContainerBackgroundHue != _altGridContainerBackgroundHue.Hue) - { - _currentProfile.AltGridContainerBackgroundHue = _altGridContainerBackgroundHue.Hue; - foreach (GridContainer _ in UIManager.Gumps.OfType()) - { - _.OptionsUpdated(); - } - } - - if (_currentProfile.ContainerOpacity != (byte)_containerOpacity.Value) - { - _currentProfile.ContainerOpacity = (byte)_containerOpacity.Value; - foreach (GridContainer _ in UIManager.Gumps.OfType()) - { - _.OptionsUpdated(); - } - } - - if (_useStandardSkillsGump.IsChecked) - { - SkillGumpAdvanced newGump = UIManager.GetGump(); - - if (newGump != null) - { - UIManager.Add(new StandardSkillsGump { X = newGump.X, Y = newGump.Y }); - - newGump.Dispose(); - } - } - else - { - StandardSkillsGump standardGump = UIManager.GetGump(); - - if (standardGump != null) - { - UIManager.Add(new SkillGumpAdvanced { X = standardGump.X, Y = standardGump.Y }); - - standardGump.Dispose(); - } - } - - _currentProfile.ShowNewMobileNameIncoming = _showMobileNameIncoming.IsChecked; - _currentProfile.ShowNewCorpseNameIncoming = _showCorpseNameIncoming.IsChecked; - _currentProfile.GridLootType = _gridLoot.SelectedIndex; - _currentProfile.SallosEasyGrab = _sallosEasyGrab.IsChecked; - _currentProfile.PartyInviteGump = _partyInviteGump.IsChecked; - _currentProfile.UseObjectsFading = _objectsFading.IsChecked; - _currentProfile.TextFading = _textFading.IsChecked; - _currentProfile.UseSmoothBoatMovement = _use_smooth_boat_movement.IsChecked; - - if (_currentProfile.JournalOpacity != _journalOpacity.Value) - { - _currentProfile.JournalOpacity = (byte)_journalOpacity.Value; - UIManager.GetGump()?.RequestUpdateContents(); - } - - if (_currentProfile.ShowHouseContent != _showHouseContent.IsChecked) - { - _currentProfile.ShowHouseContent = _showHouseContent.IsChecked; - NetClient.Socket.Send_ShowPublicHouseContent(_currentProfile.ShowHouseContent); - } - - - // sounds - _currentProfile.EnableSound = _enableSounds.IsChecked; - _currentProfile.EnableMusic = _enableMusic.IsChecked; - _currentProfile.EnableFootstepsSound = _footStepsSound.IsChecked; - _currentProfile.EnableCombatMusic = _combatMusic.IsChecked; - _currentProfile.ReproduceSoundsInBackground = _musicInBackground.IsChecked; - _currentProfile.SoundVolume = _soundsVolume.Value; - _currentProfile.MusicVolume = _musicVolume.Value; - Settings.GlobalSettings.LoginMusicVolume = _loginMusicVolume.Value; - Settings.GlobalSettings.LoginMusic = _loginMusic.IsChecked; - - Client.Game.Audio.UpdateCurrentMusicVolume(); - Client.Game.Audio.UpdateCurrentSoundsVolume(); - - if (!_currentProfile.EnableMusic) - { - Client.Game.Audio.StopMusic(); - } - - if (!_currentProfile.EnableSound) - { - Client.Game.Audio.StopSounds(); - } - - // speech - _currentProfile.ScaleSpeechDelay = _scaleSpeechDelay.IsChecked; - _currentProfile.SpeechDelay = _sliderSpeechDelay.Value; - _currentProfile.SpeechHue = _speechColorPickerBox.Hue; - _currentProfile.EmoteHue = _emoteColorPickerBox.Hue; - _currentProfile.YellHue = _yellColorPickerBox.Hue; - _currentProfile.WhisperHue = _whisperColorPickerBox.Hue; - _currentProfile.PartyMessageHue = _partyMessageColorPickerBox.Hue; - _currentProfile.GuildMessageHue = _guildMessageColorPickerBox.Hue; - _currentProfile.AllyMessageHue = _allyMessageColorPickerBox.Hue; - _currentProfile.ChatMessageHue = _chatMessageColorPickerBox.Hue; - - if (_currentProfile.ActivateChatAfterEnter != _chatAfterEnter.IsChecked) - { - UIManager.SystemChat.IsActive = !_chatAfterEnter.IsChecked; - _currentProfile.ActivateChatAfterEnter = _chatAfterEnter.IsChecked; - } - - _currentProfile.ActivateChatAdditionalButtons = _chatAdditionalButtonsCheckbox.IsChecked; - _currentProfile.ActivateChatShiftEnterSupport = _chatShiftEnterCheckbox.IsChecked; - _currentProfile.SaveJournalToFile = _saveJournalCheckBox.IsChecked; - - // video - _currentProfile.EnableDeathScreen = _enableDeathScreen.IsChecked; - _currentProfile.EnableBlackWhiteEffect = _enableBlackWhiteEffect.IsChecked; - - var camera = Client.Game.Scene.Camera; - _currentProfile.DefaultScale = camera.Zoom = (_sliderZoom.Value * camera.ZoomStep) + camera.ZoomMin; - - _currentProfile.EnableMousewheelScaleZoom = _zoomCheckbox.IsChecked; - _currentProfile.RestoreScaleAfterUnpressCtrl = _restorezoomCheckbox.IsChecked; - - if (!CUOEnviroment.IsOutlands && _use_old_status_gump.IsChecked != _currentProfile.UseOldStatusGump) - { - StatusGumpBase status = StatusGumpBase.GetStatusGump(); - - _currentProfile.UseOldStatusGump = _use_old_status_gump.IsChecked; - - if (status != null) - { - status.Dispose(); - UIManager.Add(StatusGumpBase.AddStatusGump(status.ScreenCoordinateX, status.ScreenCoordinateY)); - } - } - - - int.TryParse(_gameWindowWidth.Text, out int gameWindowSizeWidth); - int.TryParse(_gameWindowHeight.Text, out int gameWindowSizeHeight); - - if (gameWindowSizeWidth != Client.Game.Scene.Camera.Bounds.Width || gameWindowSizeHeight != Client.Game.Scene.Camera.Bounds.Height) - { - if (vp != null) - { - Point n = vp.ResizeGameWindow(new Point(gameWindowSizeWidth, gameWindowSizeHeight)); - - _gameWindowWidth.SetText(n.X.ToString()); - _gameWindowHeight.SetText(n.Y.ToString()); - } - } - - int.TryParse(_gameWindowPositionX.Text, out int gameWindowPositionX); - int.TryParse(_gameWindowPositionY.Text, out int gameWindowPositionY); - - if (gameWindowPositionX != camera.Bounds.X || gameWindowPositionY != camera.Bounds.Y) - { - if (vp != null) - { - vp.SetGameWindowPosition(new Point(gameWindowPositionX, gameWindowPositionY)); - _currentProfile.GameWindowPosition = vp.Location; - } - } - - if (_currentProfile.GameWindowLock != _gameWindowLock.IsChecked) - { - if (vp != null) - { - vp.CanMove = !_gameWindowLock.IsChecked; - } - - _currentProfile.GameWindowLock = _gameWindowLock.IsChecked; - } - - if (_currentProfile.GameWindowFullSize != _gameWindowFullsize.IsChecked) - { - Point n = Point.Zero, loc = Point.Zero; - - if (_gameWindowFullsize.IsChecked) - { - if (vp != null) - { - n = vp.ResizeGameWindow(new Point(Client.Game.Window.ClientBounds.Width, Client.Game.Window.ClientBounds.Height)); - vp.SetGameWindowPosition(new Point(-5, -5)); - _currentProfile.GameWindowPosition = vp.Location; - } - } - else - { - if (vp != null) - { - n = vp.ResizeGameWindow(new Point(600, 480)); - vp.SetGameWindowPosition(new Point(20, 20)); - _currentProfile.GameWindowPosition = vp.Location; - } - } - - _gameWindowPositionX.SetText(loc.X.ToString()); - _gameWindowPositionY.SetText(loc.Y.ToString()); - _gameWindowWidth.SetText(n.X.ToString()); - _gameWindowHeight.SetText(n.Y.ToString()); - - _currentProfile.GameWindowFullSize = _gameWindowFullsize.IsChecked; - } - - if (_currentProfile.WindowBorderless != _windowBorderless.IsChecked) - { - _currentProfile.WindowBorderless = _windowBorderless.IsChecked; - Client.Game.SetWindowBorderless(_windowBorderless.IsChecked); - } - - _currentProfile.UseAlternativeLights = _altLights.IsChecked; - _currentProfile.UseCustomLightLevel = _enableLight.IsChecked; - _currentProfile.LightLevel = (byte)(_lightBar.MaxValue - _lightBar.Value); - _currentProfile.LightLevelType = _lightLevelType.SelectedIndex; - - if (_enableLight.IsChecked) - { - World.Light.Overall = _currentProfile.LightLevelType == 1 ? Math.Min(World.Light.RealOverall, _currentProfile.LightLevel) : _currentProfile.LightLevel; - World.Light.Personal = 0; - } - else - { - World.Light.Overall = World.Light.RealOverall; - World.Light.Personal = World.Light.RealPersonal; - } - - _currentProfile.UseColoredLights = _useColoredLights.IsChecked; - _currentProfile.UseDarkNights = _darkNights.IsChecked; - _currentProfile.ShadowsEnabled = _enableShadows.IsChecked; - _currentProfile.ShadowsStatics = _enableShadowsStatics.IsChecked; - _currentProfile.TerrainShadowsLevel = _terrainShadowLevel.Value; - _currentProfile.AuraUnderFeetType = _auraType.SelectedIndex; - - Client.Game.IsMouseVisible = Settings.GlobalSettings.RunMouseInASeparateThread = _runMouseInSeparateThread.IsChecked; - - _currentProfile.AuraOnMouse = _auraMouse.IsChecked; - _currentProfile.AnimatedWaterEffect = _animatedWaterEffect.IsChecked; - _currentProfile.PartyAura = _partyAura.IsChecked; - _currentProfile.PartyAuraHue = _partyAuraColorPickerBox.Hue; - _currentProfile.HideChatGradient = _hideChatGradient.IsChecked; - _currentProfile.IgnoreGuildMessages = _ignoreGuildMessages.IsChecked; - _currentProfile.IgnoreAllianceMessages = _ignoreAllianceMessages.IsChecked; - - // fonts - _currentProfile.ForceUnicodeJournal = _forceUnicodeJournal.IsChecked; - byte _fontValue = _fontSelectorChat.GetSelectedFont(); - _currentProfile.OverrideAllFonts = _overrideAllFonts.IsChecked; - _currentProfile.OverrideAllFontsIsUnicode = _overrideAllFontsIsUnicodeCheckbox.SelectedIndex == 1; - - if (_currentProfile.ChatFont != _fontValue) - { - _currentProfile.ChatFont = _fontValue; - UIManager.SystemChat.TextBoxControl.Font = _fontValue; - } - - // combat - _currentProfile.InnocentHue = _innocentColorPickerBox.Hue; - _currentProfile.FriendHue = _friendColorPickerBox.Hue; - _currentProfile.CriminalHue = _crimialColorPickerBox.Hue; - _currentProfile.CanAttackHue = _canAttackColorPickerBox.Hue; - _currentProfile.EnemyHue = _enemyColorPickerBox.Hue; - _currentProfile.MurdererHue = _murdererColorPickerBox.Hue; - _currentProfile.EnabledCriminalActionQuery = _queryBeforAttackCheckbox.IsChecked; - _currentProfile.EnabledBeneficialCriminalActionQuery = _queryBeforeBeneficialCheckbox.IsChecked; - _currentProfile.CastSpellsByOneClick = _uiButtonsSingleClick.IsChecked; - _currentProfile.BuffBarTime = _buffBarTime.IsChecked; - _currentProfile.FastSpellsAssign = _enableFastSpellsAssign.IsChecked; - - _currentProfile.BeneficHue = _beneficColorPickerBox.Hue; - _currentProfile.HarmfulHue = _harmfulColorPickerBox.Hue; - _currentProfile.NeutralHue = _neutralColorPickerBox.Hue; - _currentProfile.EnabledSpellHue = _spellColoringCheckbox.IsChecked; - _currentProfile.EnabledSpellFormat = _spellFormatCheckbox.IsChecked; - _currentProfile.SpellDisplayFormat = _spellFormatBox.Text; - - // macros - Client.Game.GetScene().Macros.Save(); - - // counters - - bool before = _currentProfile.CounterBarEnabled; - _currentProfile.CounterBarEnabled = _enableCounters.IsChecked; - _currentProfile.CounterBarCellSize = _cellSize.Value; - - if (!int.TryParse(_rows.Text, out int v)) - { - v = 1; - _rows.SetText("1"); - } - - _currentProfile.CounterBarRows = v; - - if (!int.TryParse(_columns.Text, out v)) - { - v = 1; - _columns.SetText("1"); - } - _currentProfile.CounterBarColumns = v; - _currentProfile.CounterBarHighlightOnUse = _highlightOnUse.IsChecked; - - if (!int.TryParse(_highlightAmount.Text, out v)) - { - v = 5; - _highlightAmount.SetText("5"); - } - _currentProfile.CounterBarHighlightAmount = v; - - if (!int.TryParse(_abbreviatedAmount.Text, out v)) - { - v = 1000; - _abbreviatedAmount.SetText("1000"); - } - _currentProfile.CounterBarAbbreviatedAmount = v; - _currentProfile.CounterBarHighlightOnAmount = _highlightOnAmount.IsChecked; - _currentProfile.CounterBarDisplayAbbreviatedAmount = _enableAbbreviatedAmount.IsChecked; - - CounterBarGump counterGump = UIManager.GetGump(); - - counterGump?.SetLayout(_currentProfile.CounterBarCellSize, _currentProfile.CounterBarRows, _currentProfile.CounterBarColumns); - - - if (before != _currentProfile.CounterBarEnabled) - { - if (counterGump == null) - { - if (_currentProfile.CounterBarEnabled) - { - UIManager.Add - ( - new CounterBarGump - ( - 200, - 200, - _currentProfile.CounterBarCellSize, - _currentProfile.CounterBarRows, - _currentProfile.CounterBarColumns - ) - ); - } - } - else - { - counterGump.IsEnabled = counterGump.IsVisible = _currentProfile.CounterBarEnabled; - } - } - - // experimental - // Reset nested checkboxes if parent checkbox is unchecked - if (!_disableDefaultHotkeys.IsChecked) - { - _disableArrowBtn.IsChecked = false; - _disableTabBtn.IsChecked = false; - _disableCtrlQWBtn.IsChecked = false; - _disableAutoMove.IsChecked = false; - } - - // NOTE: Keep these assignments AFTER the code above that resets nested checkboxes if parent checkbox is unchecked - _currentProfile.DisableDefaultHotkeys = _disableDefaultHotkeys.IsChecked; - _currentProfile.DisableArrowBtn = _disableArrowBtn.IsChecked; - _currentProfile.DisableTabBtn = _disableTabBtn.IsChecked; - _currentProfile.DisableCtrlQWBtn = _disableCtrlQWBtn.IsChecked; - _currentProfile.DisableAutoMove = _disableAutoMove.IsChecked; - _currentProfile.AutoOpenDoors = _autoOpenDoors.IsChecked; - _currentProfile.SmoothDoors = _smoothDoors.IsChecked; - _currentProfile.AutoOpenCorpses = _autoOpenCorpse.IsChecked; - _currentProfile.AutoOpenCorpseRange = int.Parse(_autoOpenCorpseRange.Text); - _currentProfile.CorpseOpenOptions = _autoOpenCorpseOptions.SelectedIndex; - _currentProfile.SkipEmptyCorpse = _skipEmptyCorpse.IsChecked; - - _currentProfile.EnableDragSelect = _enableDragSelect.IsChecked; - _currentProfile.DragSelectModifierKey = _dragSelectModifierKey.SelectedIndex; - //_currentProfile.DragSelectHumanoidsOnly = _dragSelectHumanoidsOnly.IsChecked; - _currentProfile.DragSelectStartX = _dragSelectStartX.Value; - _currentProfile.DragSelectStartY = _dragSelectStartY.Value; - _currentProfile.DragSelectAsAnchor = _dragSelectAsAnchor.IsChecked; - - _currentProfile.ShowSkillsChangedMessage = _showSkillsMessage.IsChecked; - _currentProfile.ShowSkillsChangedDeltaValue = _showSkillsMessageDelta.Value; - _currentProfile.ShowStatsChangedMessage = _showStatsMessage.IsChecked; - - _currentProfile.OverrideContainerLocation = _overrideContainerLocation.IsChecked; - _currentProfile.OverrideContainerLocationSetting = _overrideContainerLocationSetting.SelectedIndex; - - _currentProfile.ShowTargetRangeIndicator = _showTargetRangeIndicator.IsChecked; - - - bool updateHealthBars = _currentProfile.CustomBarsToggled != _customBars.IsChecked; - _currentProfile.CustomBarsToggled = _customBars.IsChecked; - - if (updateHealthBars) - { - if (_currentProfile.CustomBarsToggled) - { - List hbgstandard = UIManager.Gumps.OfType().ToList(); - - foreach (HealthBarGump healthbar in hbgstandard) - { - UIManager.Add(new HealthBarGumpCustom(healthbar.LocalSerial) { X = healthbar.X, Y = healthbar.Y }); - - healthbar.Dispose(); - } - } - else - { - List hbgcustom = UIManager.Gumps.OfType().ToList(); - - foreach (HealthBarGumpCustom customhealthbar in hbgcustom) - { - UIManager.Add(new HealthBarGump(customhealthbar.LocalSerial) { X = customhealthbar.X, Y = customhealthbar.Y }); - - customhealthbar.Dispose(); - } - } - } - - _currentProfile.CBBlackBGToggled = _customBarsBBG.IsChecked; - _currentProfile.SaveHealthbars = _saveHealthbars.IsChecked; - - - // infobar - _currentProfile.ShowInfoBar = _showInfoBar.IsChecked; - _currentProfile.InfoBarHighlightType = _infoBarHighlightType.SelectedIndex; - - - InfoBarManager ibmanager = Client.Game.GetScene().InfoBars; - - ibmanager.Clear(); - - for (int i = 0; i < _infoBarBuilderControls.Count; i++) - { - if (!_infoBarBuilderControls[i].IsDisposed) - { - ibmanager.AddItem(new InfoBarItem(_infoBarBuilderControls[i].LabelText, _infoBarBuilderControls[i].Var, _infoBarBuilderControls[i].Hue)); - } - } - - ibmanager.Save(); - - InfoBarGump infoBarGump = UIManager.GetGump(); - - if (_currentProfile.ShowInfoBar) - { - if (infoBarGump == null) - { - UIManager.Add(new InfoBarGump { X = 300, Y = 300 }); - } - else - { - infoBarGump.ResetItems(); - infoBarGump.SetInScreen(); - } - } - else - { - if (infoBarGump != null) - { - infoBarGump.Dispose(); - } - } - - - // containers - - - int containerScale = _currentProfile.ContainersScale; - - if ((byte)_containersScale.Value != containerScale || _currentProfile.ScaleItemsInsideContainers != _containerScaleItems.IsChecked) - { - containerScale = _currentProfile.ContainersScale = (byte)_containersScale.Value; - UIManager.ContainerScale = containerScale / 100f; - _currentProfile.ScaleItemsInsideContainers = _containerScaleItems.IsChecked; - - foreach (ContainerGump resizableGump in UIManager.Gumps.OfType()) - { - resizableGump.RequestUpdateContents(); - } - } - - _currentProfile.UseGridLayoutContainerGumps = _useGridLayoutContainerGumps.IsChecked; - _currentProfile.UseLargeContainerGumps = _useLargeContianersGumps.IsChecked; - _currentProfile.DoubleClickToLootInsideContainers = _containerDoubleClickToLoot.IsChecked; - _currentProfile.RelativeDragAndDropItems = _relativeDragAnDropItems.IsChecked; - _currentProfile.HighlightContainerWhenSelected = _highlightContainersWhenMouseIsOver.IsChecked; - _currentProfile.HueContainerGumps = _hueContainerGumps.IsChecked; - - - if (_currentProfile.BackpackStyle != _backpackStyle.SelectedIndex) - { - _currentProfile.BackpackStyle = _backpackStyle.SelectedIndex; - UIManager.GetGump(World.Player.Serial)?.RequestUpdateContents(); - UIManager.GetGump(World.Player.Serial)?.RequestUpdateContents(); - Item backpack = World.Player.FindItemByLayer(Layer.Backpack); - GameActions.DoubleClick(backpack); - } - - - // tooltip - _currentProfile.UseTooltip = _use_tooltip.IsChecked; - _currentProfile.TooltipTextHue = _tooltip_font_hue.Hue; - _currentProfile.TooltipDelayBeforeDisplay = _delay_before_display_tooltip.Value; - _currentProfile.TooltipBackgroundOpacity = _tooltip_background_opacity.Value; - _currentProfile.TooltipDisplayZoom = _tooltip_zoom.Value; - _currentProfile.TooltipFont = _tooltip_font_selector.GetSelectedFont(); - - _currentProfile?.Save(ProfileManager.ProfilePath); - } - - internal void UpdateVideo() - { - var camera = Client.Game.Scene.Camera; - - _gameWindowPositionX.SetText(camera.Bounds.X.ToString()); - _gameWindowPositionY.SetText(camera.Bounds.Y.ToString()); - _gameWindowWidth.SetText(camera.Bounds.Width.ToString()); - _gameWindowHeight.SetText(camera.Bounds.Height.ToString()); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - batcher.Draw - ( - LogoTexture, - new Rectangle - ( - x + 190, - y + 20, - WIDTH - 250, - 400 - ), - hueVector - ); - - batcher.DrawRectangle - ( - SolidColorTextureCache.GetTexture(Color.Gray), - x, - y, - Width, - Height, - hueVector - ); - - return base.Draw(batcher, x, y); - } - - private InputField AddInputField - ( - ScrollArea area, - int x, - int y, - int width, - int height, - string label = null, - int maxWidth = 0, - bool set_down = false, - bool numbersOnly = false, - int maxCharCount = -1 - ) - { - InputField elem = new InputField - ( - 0x0BB8, - FONT, - HUE_FONT, - true, - width, - height, - maxWidth, - maxCharCount - ) - { - NumbersOnly = numbersOnly, - X = x, - Y = y - }; - - - if (area != null) - { - Label text = AddLabel(area, label, x, y); - - if (set_down) - { - elem.Y = text.Bounds.Bottom + 2; - } - else - { - elem.X = text.Bounds.Right + 2; - } - - area.Add(elem); - } - - return elem; - } - - private Label AddLabel(ScrollArea area, string text, int x, int y) - { - Label label = new Label(text, true, HUE_FONT) - { - X = x, - Y = y - }; - - area?.Add(label); - - return label; - } - - private Checkbox AddCheckBox(ScrollArea area, string text, bool ischecked, int x, int y) - { - Checkbox box = new Checkbox - ( - 0x00D2, - 0x00D3, - text, - FONT, - HUE_FONT - ) - { - IsChecked = ischecked, - X = x, - Y = y - }; - - area?.Add(box); - - return box; - } - - private Combobox AddCombobox - ( - ScrollArea area, - string[] values, - int currentIndex, - int x, - int y, - int width - ) - { - Combobox combobox = new Combobox(x, y, width, values) - { - SelectedIndex = currentIndex - }; - - area?.Add(combobox); - - return combobox; - } - - private HSliderBar AddHSlider - ( - ScrollArea area, - int min, - int max, - int value, - int x, - int y, - int width - ) - { - HSliderBar slider = new HSliderBar - ( - x, - y, - width, - min, - max, - value, - HSliderBarStyle.MetalWidgetRecessedBar, - true, - FONT, - HUE_FONT - ); - - area?.Add(slider); - - return slider; - } - - private ClickableColorBox AddColorBox(ScrollArea area, int x, int y, ushort hue, string text) - { - ClickableColorBox box = new ClickableColorBox - ( - x, - y, - 13, - 14, - hue - ); - - area?.Add(box); - - area?.Add - ( - new Label(text, true, HUE_FONT) - { - X = x + box.Width + 10, - Y = y - } - ); - - return box; - } - - private SettingsSection AddSettingsSection(DataBox area, string label) - { - SettingsSection section = new SettingsSection(label, area.Width); - area.Add(section); - area.WantUpdateSize = true; - //area.ReArrangeChildren(); - - return section; - } - - protected override void OnDragBegin(int x, int y) - { - if (UIManager.MouseOverControl?.RootParent == this) - { - UIManager.MouseOverControl.InvokeDragBegin(new Point(x, y)); - } - - base.OnDragBegin(x, y); - } - - protected override void OnDragEnd(int x, int y) - { - if (UIManager.MouseOverControl?.RootParent == this) - { - UIManager.MouseOverControl.InvokeDragEnd(new Point(x, y)); - } - - base.OnDragEnd(x, y); - } - - private enum Buttons - { - Disabled, //no action will be done on these buttons, at least not by OnButtonClick() - Cancel, - Apply, - Default, - Ok, - SpeechColor, - EmoteColor, - PartyMessageColor, - GuildMessageColor, - AllyMessageColor, - InnocentColor, - FriendColor, - CriminalColor, - EnemyColor, - MurdererColor, - - OpenIgnoreList, - NewMacro, - DeleteMacro, - - NewNameOverheadEntry, - DeleteOverheadEntry, - - Last = DeleteMacro - } - - - public class SettingsSection : Control - { - private readonly DataBox _databox; - private int _indent; - - public SettingsSection(string title, int width) - { - CanMove = true; - AcceptMouseInput = true; - WantUpdateSize = true; - - - Label label = new Label(title, true, HUE_FONT, font: FONT); - label.X = 5; - base.Add(label); - - base.Add - ( - new Line - ( - 0, - label.Height, - width - 30, - 1, - 0xFFbabdc2 - ) - ); - - Width = width; - Height = label.Height + 1; - - _databox = new DataBox(label.X + 10, label.Height + 4, 0, 0); - - base.Add(_databox); - } - - public void PushIndent() - { - _indent += 40; - } - - public void PopIndent() - { - _indent -= 40; - } - - - public void AddRight(Control c, int offset = 15) - { - int i = _databox.Children.Count - 1; - - for (; i >= 0; --i) - { - if (_databox.Children[i].IsVisible) - { - break; - } - } - - c.X = i >= 0 ? _databox.Children[i].Bounds.Right + offset : _indent; - - c.Y = i >= 0 ? _databox.Children[i].Bounds.Top : 0; - - _databox.Add(c); - _databox.WantUpdateSize = true; - } - - public void BaseAdd(Control c, int page = 0) - { - base.Add(c, page); - } - - public override void Add(Control c, int page = 0) - { - int i = _databox.Children.Count - 1; - int bottom = 0; - - for (; i >= 0; --i) - { - if (_databox.Children[i].IsVisible) - { - if (bottom == 0 || bottom < _databox.Children[i].Bounds.Bottom + 2) - { - bottom = _databox.Children[i].Bounds.Bottom + 2; - } - else - { - break; - } - } - } - - c.X = _indent; - c.Y = bottom; - - _databox.Add(c, page); - _databox.WantUpdateSize = true; - - Height += c.Height + 2; - } - } - - private class FontSelector : Control - { - private readonly RadioButton[] _buttons; - - public FontSelector(int max_font, int current_font_index, string markup) - { - CanMove = false; - CanCloseWithRightClick = false; - - int y = 0; - - _buttons = new RadioButton[max_font]; - - for (byte i = 0; i < max_font; i++) - { - if (FontsLoader.Instance.UnicodeFontExists(i)) - { - Add - ( - _buttons[i] = new RadioButton - ( - 0, - 0x00D0, - 0x00D1, - markup, - i, - HUE_FONT - ) - { - Y = y, - Tag = i, - IsChecked = current_font_index == i - } - ); - - y += 25; - } - } - } - - public byte GetSelectedFont() - { - for (byte i = 0; i < _buttons.Length; i++) - { - RadioButton b = _buttons[i]; - - if (b != null && b.IsChecked) - { - return i; - } - } - - return 0xFF; - } - - public void SetSelectedFont(int index) - { - if (index >= 0 && index < _buttons.Length && _buttons[index] != null) - { - _buttons[index].IsChecked = true; - } - } - } - - public class InputField : Control - { - private readonly StbTextBox _textbox; - - public event EventHandler TextChanged { add { _textbox.TextChanged += value; } remove { _textbox.TextChanged -= value; } } - - public InputField - ( - ushort backgroundGraphic, - byte font, - ushort hue, - bool unicode, - int width, - int height, - int maxWidthText = 0, - int maxCharsCount = -1 - ) - { - WantUpdateSize = false; - - Width = width; - Height = height; - - ResizePic background = new ResizePic(backgroundGraphic) - { - Width = width, - Height = height - }; - - _textbox = new StbTextBox - ( - font, - maxCharsCount, - maxWidthText, - unicode, - FontStyle.BlackBorder, - hue - ) - { - X = 4, - Y = 4, - Width = width - 8, - Height = height - 8 - }; - - - Add(background); - Add(_textbox); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - if (batcher.ClipBegin(x, y, Width, Height)) - { - base.Draw(batcher, x, y); - - batcher.ClipEnd(); - } - - return true; - } - - - public string Text => _textbox.Text; - - public override bool AcceptKeyboardInput - { - get => _textbox.AcceptKeyboardInput; - set => _textbox.AcceptKeyboardInput = value; - } - - public bool NumbersOnly - { - get => _textbox.NumbersOnly; - set => _textbox.NumbersOnly = value; - } - - - public void SetText(string text) - { - _textbox.SetText(text); - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/PaperdollGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/PaperdollGump.cs deleted file mode 100644 index 598513048..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/PaperdollGump.cs +++ /dev/null @@ -1,1168 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Network; -using ClassicUO.Renderer; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using System; -using System.Xml; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class PaperDollGump : TextContainerGump - { - private static readonly ushort[] PeaceModeBtnGumps = { 0x07e5, 0x07e6, 0x07e7 }; - private static readonly ushort[] WarModeBtnGumps = { 0x07e8, 0x07e9, 0x07ea }; - private GumpPic _combatBook, - _racialAbilitiesBook; - private HitBox _hitBox; - private bool _isWarMode, - _isMinimized; - - private PaperDollInteractable _paperDollInteractable; - private GumpPic _partyManifestPic; - - private GumpPic _picBase; - private GumpPic _profilePic; - private readonly EquipmentSlot[] _slots = new EquipmentSlot[6]; - private readonly EquipmentSlot[] _slots_right = new EquipmentSlot[6]; - private Label _titleLabel; - private GumpPic _virtueMenuPic; - private Button _warModeBtn; - - public PaperDollGump() : base(0, 0) - { - CanMove = true; - CanCloseWithRightClick = true; - X = ProfileManager.CurrentProfile.PaperdollPosition.X; - Y = ProfileManager.CurrentProfile.PaperdollPosition.Y; - IsLocked = ProfileManager.CurrentProfile.PaperdollLocked; - } - - public PaperDollGump(uint serial, bool canLift) : this() - { - LocalSerial = serial; - CanLift = canLift; - Scale = InternalScale = ProfileManager.CurrentProfile.PaperdollScale; - BuildGump(); - } - - private static Settings _settings; - private static Settings settings - { - get - { - if (_settings == null) - { - _settings = (Settings)Settings.Load(typeof(PaperDollGump).ToString()); - if (_settings == null) - { - _settings = new Settings(); - Settings.Save(typeof(PaperDollGump).ToString(), _settings); - } - return _settings; - } - else - { - return _settings; - } - } - } - - public override GumpType GumpType => GumpType.PaperDoll; - - public bool IsMinimized - { - get => _isMinimized; - set - { - if (_isMinimized != value) - { - _isMinimized = value; - - _picBase.Dispose(); - _picBase = new GumpPic(0, 0, value ? settings.Graphic_Button_Minimized : (LocalSerial == World.Player ? settings.Graphic_Background_Player : settings.Graphic_Background_Other), 0); - _picBase.ScaleWidthAndHeight(Scale).SetInternalScale(Scale); - _picBase.MouseDoubleClick += _picBase_MouseDoubleClick; - Insert(0, _picBase); - - foreach (Control c in Children) - { - c.IsVisible = !value; - } - - _picBase.IsVisible = true; - WantUpdateSize = true; - } - } - } - - public bool CanLift { get; set; } - - public override void Dispose() - { - UIManager.SavePosition(LocalSerial, Location); - - if (LocalSerial == World.Player) - { - if (_virtueMenuPic != null) - { - _virtueMenuPic.MouseDoubleClick -= VirtueMenu_MouseDoubleClickEvent; - } - - if (_partyManifestPic != null) - { - _partyManifestPic.MouseDoubleClick -= PartyManifest_MouseDoubleClickEvent; - } - if (ProfileManager.CurrentProfile != null) - ProfileManager.CurrentProfile.PaperdollPosition = Location; - } - - Clear(); - base.Dispose(); - } - - private void _hitBox_MouseUp(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtonType.Left && !IsMinimized) - { - IsMinimized = true; - } - } - - private void BuildGump() - { - _picBase?.Dispose(); - _hitBox?.Dispose(); - - var showPaperdollBooks = - LocalSerial == World.Player && World.ClientFeatures.PaperdollBooks; - var showRacialAbilitiesBook = - showPaperdollBooks && Client.Version >= ClientVersion.CV_7000; - if (LocalSerial == World.Player) - { - Add(_picBase = new GumpPic(0, 0, settings.Graphic_Background_Player, settings.Hue_Background_Player)); - _picBase.ScaleWidthAndHeight(Scale).SetInternalScale(Scale); - _picBase.MouseDoubleClick += _picBase_MouseDoubleClick; - - //HELP BUTTON - Add( - new Button((int)Buttons.Help, settings.Graphic_Button_Help_Normal, settings.Graphic_Button_Help_Pressed, settings.Graphic_Button_Help_Hover) - { - X = settings.Position_X_Help, - Y = settings.Position_Y_Help, - ButtonAction = ButtonAction.Activate - }.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale) - ); - - //OPTIONS BUTTON - Add( - new Button((int)Buttons.Options, settings.Graphic_Button_Options_Normal, settings.Graphic_Button_Options_Pressed, settings.Graphic_Button_Options_Hover) - { - X = settings.Position_X_Options, - Y = settings.Position_Y_Options, - ButtonAction = ButtonAction.Activate - }.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale) - ); - - // LOG OUT BUTTON - Add( - new Button((int)Buttons.LogOut, settings.Graphic_Button_Logout_Normal, settings.Graphic_Button_Logout_Pressed, settings.Graphic_Button_Logout_Hover) - { - X = settings.Position_X_Logout, - Y = settings.Position_Y_Logout, - ButtonAction = ButtonAction.Activate - }.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale) - ); - - if (Client.Version < ClientVersion.CV_500A) - { - // JOURNAL BUTTON - Add( - new Button((int)Buttons.Journal, settings.Graphic_Button_Journal_Normal, settings.Graphic_Button_Journal_Pressed, settings.Graphic_Button_Journal_Hover) - { - X = settings.Position_X_Journal, - Y = settings.Position_Y_Journal, - ButtonAction = ButtonAction.Activate - }.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale) - ); - } - else - { - // QUESTS BUTTON - Add( - new Button((int)Buttons.Quests, settings.Graphic_Button_Quest_Normal, settings.Graphic_Button_Quest_Pressed, settings.Graphic_Button_Quest_Hover) - { - X = settings.Position_X_Quest, - Y = settings.Position_Y_Quest, - ButtonAction = ButtonAction.Activate - }.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale) - ); - } - - // SKILLS BUTTON - Add( - new Button((int)Buttons.Skills, settings.Graphic_Button_Skills_Normal, settings.Graphic_Button_Skills_Pressed, settings.Graphic_Button_Skills_Hover) - { - X = settings.Position_X_Skills, - Y = settings.Position_Y_Skills, - ButtonAction = ButtonAction.Activate - }.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale) - ); - - // GUILD BUTTON - Add( - new Button((int)Buttons.Guild, settings.Graphic_Button_Guild_Normal, settings.Graphic_Button_Guild_Pressed, settings.Graphic_Button_Guild_Hover) - { - X = settings.Position_X_Guild, - Y = settings.Position_Y_Guild, - ButtonAction = ButtonAction.Activate - }.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale) - ); - - // TOGGLE PEACE/WAR BUTTON - Mobile mobile = World.Mobiles.Get(LocalSerial); - - _isWarMode = mobile?.InWarMode ?? false; - - if (_isWarMode) - { - Add( - _warModeBtn = new Button( - (int)Buttons.PeaceWarToggle, - settings.Graphic_Button_Warmode_Normal, - settings.Graphic_Button_Warmode_Pressed, - settings.Graphic_Button_Warmode_Hover - ) - { - X = settings.Position_X_WarMode, - Y = settings.Position_Y_Warmode, - ButtonAction = ButtonAction.Activate - } - ); - } - else - { - Add( - _warModeBtn = new Button( - (int)Buttons.PeaceWarToggle, - settings.Graphic_Button_Peacemode_Normal, - settings.Graphic_Button_Peacemode_Pressed, - settings.Graphic_Button_Peacemode_Hover - ) - { - X = settings.Position_X_WarMode, - Y = settings.Position_Y_Warmode, - ButtonAction = ButtonAction.Activate - } - ); - } - _warModeBtn.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale); - - int profileX = settings.Position_X_Profile; - - if (showRacialAbilitiesBook) - { - profileX += settings.Racial_Abilities_Width; - } - - Add(_profilePic = new GumpPic(profileX, settings.Position_Y_Profile, settings.Graphic_Button_Profile, 0)); - profileX += _profilePic.Width; - _profilePic.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale); - _profilePic.MouseDoubleClick += Profile_MouseDoubleClickEvent; - - Add(_partyManifestPic = new GumpPic(profileX, settings.Position_Y_Profile, settings.Graphic_Button_Party, 0)); - _partyManifestPic.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale); - _partyManifestPic.MouseDoubleClick += PartyManifest_MouseDoubleClickEvent; - - _hitBox = new HitBox(settings.Position_X_MinimizeButton, settings.Position_Y_MinimizeButton, settings.Size_Width_MinimizeButton, settings.Size_Height_MinimizeButton, alpha: 0f); - _hitBox.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale); - _hitBox.MouseUp += _hitBox_MouseUp; - - Add(_hitBox); - } - else - { - Add(_picBase = new GumpPic(0, 0, settings.Graphic_Background_Other, settings.Hue_Background_Other)); - _picBase.ScaleWidthAndHeight(Scale).SetInternalScale(Scale); - Add(_profilePic = new GumpPic(settings.Position_X_Profile, settings.Position_Y_Profile, settings.Graphic_Button_Profile, 0)); - _profilePic.ScaleWidthAndHeight(Scale).SetInternalScale(Scale); - _profilePic.MouseDoubleClick += Profile_MouseDoubleClickEvent; - } - - // STATUS BUTTON - Add( - new Button((int)Buttons.Status, settings.Graphic_Button_Status_Normal, settings.Graphic_Button_Status_Pressed, settings.Graphic_Button_Status_Hover) - { - X = settings.Position_X_Status, - Y = settings.Position_Y_Status, - ButtonAction = ButtonAction.Activate - }.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale) - ); - - // Virtue menu - Add(_virtueMenuPic = new GumpPic(settings.Position_X_Virtue, settings.Position_Y_Virtue, settings.Graphic_Button_Virtue, 0)); - _virtueMenuPic.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale); - _virtueMenuPic.MouseDoubleClick += VirtueMenu_MouseDoubleClickEvent; - - if (LocalSerial == World.Player.Serial) - Add(new DurabilityGumpMinimized() - { - X = settings.Position_X_Durability, - Y = settings.Position_Y_Durability, - Graphic = settings.Graphic_Button_Durability - }.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale)); - - // Equipment slots for hat/earrings/neck/ring/bracelet - Add(_slots[0] = new EquipmentSlot(0, settings.Position_X_LeftSlots, settings.Position_Y_LeftSlots, Layer.Helmet, this)); - - Add(_slots[1] = new EquipmentSlot(0, settings.Position_X_LeftSlots, settings.Position_Y_LeftSlots + settings.Size_Height_LeftSlots, Layer.Earrings, this)); - - Add(_slots[2] = new EquipmentSlot(0, settings.Position_X_LeftSlots, settings.Position_Y_LeftSlots + settings.Size_Height_LeftSlots * 2, Layer.Necklace, this)); - - Add(_slots[3] = new EquipmentSlot(0, settings.Position_X_LeftSlots, settings.Position_Y_LeftSlots + settings.Size_Height_LeftSlots * 3, Layer.Ring, this)); - - Add(_slots[4] = new EquipmentSlot(0, settings.Position_X_LeftSlots, settings.Position_Y_LeftSlots + settings.Size_Height_LeftSlots * 4, Layer.Bracelet, this)); - - Add(_slots[5] = new EquipmentSlot(0, settings.Position_X_LeftSlots, settings.Position_Y_LeftSlots + settings.Size_Height_LeftSlots * 5, Layer.Tunic, this)); - - foreach (var slot in _slots) - { - slot.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale); - } - - // Right side equip slots - Add(_slots_right[0] = new EquipmentSlot(0, settings.Position_X_RightSlots, settings.Position_Y_RightSlots, Layer.Torso, this)); - - Add(_slots_right[1] = new EquipmentSlot(0, settings.Position_X_RightSlots, settings.Position_Y_RightSlots + settings.Size_Height_RightSlots, Layer.Arms, this)); - - Add(_slots_right[2] = new EquipmentSlot(0, settings.Position_X_RightSlots, settings.Position_Y_RightSlots + settings.Size_Height_RightSlots * 2, Layer.Shirt, this)); - - Add(_slots_right[3] = new EquipmentSlot(0, settings.Position_X_RightSlots, settings.Position_Y_RightSlots + settings.Size_Height_RightSlots * 3, Layer.Pants, this)); - - Add(_slots_right[4] = new EquipmentSlot(0, settings.Position_X_RightSlots, settings.Position_Y_RightSlots + settings.Size_Height_RightSlots * 4, Layer.Skirt, this)); - - Add(_slots_right[5] = new EquipmentSlot(0, settings.Position_X_RightSlots, settings.Position_Y_RightSlots + settings.Size_Height_RightSlots * 5, Layer.Shoes, this)); - - foreach (var slot in _slots_right) - { - slot.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale); - } - - // Paperdoll control! - _paperDollInteractable = new PaperDollInteractable(settings.Position_X_Avatar, settings.Position_Y_Avatar, LocalSerial, this, Scale); - _paperDollInteractable.ScaleXAndY(Scale); - Add(_paperDollInteractable); - - if (showPaperdollBooks) - { - Add(_combatBook = new GumpPic(settings.Position_X_CombatBook, settings.Position_Y_CombatBook, settings.Graphic_Button_Combat, 0)); - _combatBook.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale); - _combatBook.MouseDoubleClick += (sender, e) => GameActions.OpenAbilitiesBook(); - - if (showRacialAbilitiesBook) - { - Add(_racialAbilitiesBook = new GumpPic(settings.Position_X_RacialAbilities, settings.Position_Y_RacialAbilities, settings.Graphic_Button_RacialAbilties, 0)); - _racialAbilitiesBook.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale); - _racialAbilitiesBook.MouseDoubleClick += (sender, e) => - { - if (UIManager.GetGump() == null) - { - UIManager.Add(new RacialAbilitiesBookGump(100, 100)); - } - }; - } - } - - // Name and title - _titleLabel = new Label("", false, settings.Hue_Title, settings.Size_Width_Hue, font: 1) { X = settings.Position_X_Title, Y = settings.Position_Y_Title }; - _titleLabel.ScaleWidthAndHeight(Scale).ScaleXAndY(Scale).SetInternalScale(Scale); - - Add(_titleLabel); - - RequestUpdateContents(); - - WantUpdateSize = true; - } - - private void _picBase_MouseDoubleClick(object sender, MouseDoubleClickEventArgs e) - { - if (e.Button == MouseButtonType.Left && IsMinimized) - { - IsMinimized = false; - } - } - - public void UpdateTitle(string text) - { - _titleLabel.Text = text; - } - - private void VirtueMenu_MouseDoubleClickEvent(object sender, MouseDoubleClickEventArgs args) - { - if (args.Button == MouseButtonType.Left) - { - GameActions.ReplyGump( - World.Player, - 0x000001CD, - 0x00000001, - new[] { LocalSerial }, - new Tuple[0] - ); - } - } - - private void Profile_MouseDoubleClickEvent(object o, MouseDoubleClickEventArgs args) - { - if (args.Button == MouseButtonType.Left) - { - GameActions.RequestProfile(LocalSerial); - } - } - - private void PartyManifest_MouseDoubleClickEvent( - object sender, - MouseDoubleClickEventArgs args - ) - { - if (args.Button == MouseButtonType.Left) - { - if (CUOEnviroment.IsOutlands) - { - NetClient.Socket.Send_ASCIISpeechRequest("party", MessageType.Command, 0, 0); - } - else - { - PartyGump party = UIManager.GetGump(); - - if (party == null) - { - int x = Client.Game.Window.ClientBounds.Width / 2 - 272; - int y = Client.Game.Window.ClientBounds.Height / 2 - 240; - UIManager.Add(new PartyGump(x, y, World.Party.CanLoot)); - } - else - { - party.BringOnTop(); - } - } - } - } - - public override void Update() - { - if (IsDisposed) - { - return; - } - - Mobile mobile = World.Mobiles.Get(LocalSerial); - - if (mobile != null && mobile.IsDestroyed) - { - Dispose(); - - return; - } - - if (LocalSerial == World.Player) - { - // This is to update the state of the war mode button. - if (mobile != null && _isWarMode != mobile.InWarMode) - { - _isWarMode = mobile.InWarMode; - ushort[] btngumps = _isWarMode ? WarModeBtnGumps : PeaceModeBtnGumps; - _warModeBtn.ButtonGraphicNormal = btngumps[0]; - _warModeBtn.ButtonGraphicPressed = btngumps[1]; - _warModeBtn.ButtonGraphicOver = btngumps[2]; - } - - if (Location != ProfileManager.CurrentProfile.PaperdollPosition) - ProfileManager.CurrentProfile.PaperdollPosition = Location; - } - - base.Update(); - - if (_paperDollInteractable != null && (CanLift || LocalSerial == World.Player.Serial)) - { - bool force_false = - SelectedObject.Object is Item item - && (item.Layer == Layer.Backpack || item.ItemData.IsContainer); - - if ( - _paperDollInteractable.HasFakeItem && !Client.Game.GameCursor.ItemHold.Enabled - || force_false - ) - { - _paperDollInteractable.SetFakeItem(false); - } - else if ( - !_paperDollInteractable.HasFakeItem - && Client.Game.GameCursor.ItemHold.Enabled - && !Client.Game.GameCursor.ItemHold.IsFixedPosition - && UIManager.MouseOverControl?.RootParent == this - ) - { - if (Client.Game.GameCursor.ItemHold.ItemData.AnimID != 0) - { - if ( - mobile != null - && mobile.FindItemByLayer( - (Layer)Client.Game.GameCursor.ItemHold.ItemData.Layer - ) == null - ) - { - _paperDollInteractable.SetFakeItem(true); - } - } - } - } - } - - protected override void OnMouseExit(int x, int y) - { - _paperDollInteractable?.SetFakeItem(false); - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - base.OnMouseUp(x, y, button); - if (button == MouseButtonType.Left && World.InGame) - { - Mobile container = World.Mobiles.Get(LocalSerial); - - if (Client.Game.GameCursor.ItemHold.Enabled) - { - if (CanLift || LocalSerial == World.Player.Serial) - { - if ( - SelectedObject.Object is Item item - && (item.Layer == Layer.Backpack || item.ItemData.IsContainer) - ) - { - GameActions.DropItem( - Client.Game.GameCursor.ItemHold.Serial, - 0xFFFF, - 0xFFFF, - 0, - item.Serial - ); - - Mouse.CancelDoubleClick = true; - } - else - { - if (Client.Game.GameCursor.ItemHold.ItemData.IsWearable) - { - Item equipment = container.FindItemByLayer( - (Layer)Client.Game.GameCursor.ItemHold.ItemData.Layer - ); - - if (equipment == null) - { - GameActions.Equip( - LocalSerial != World.Player ? container : World.Player - ); - Mouse.CancelDoubleClick = true; - } - } - } - } - } - else if (SelectedObject.Object is Item item) - { - if (TargetManager.IsTargeting) - { - TargetManager.Target(item.Serial); - Mouse.CancelDoubleClick = true; - Mouse.LastLeftButtonClickTime = 0; - - if (TargetManager.TargetingState == CursorTarget.SetTargetClientSide) - { - UIManager.Add(new InspectorGump(item)); - } - } - else if (!DelayedObjectClickManager.IsEnabled) - { - Point off = Mouse.LDragOffset; - - DelayedObjectClickManager.Set( - item.Serial, - Mouse.Position.X - off.X - ScreenCoordinateX, - Mouse.Position.Y - off.Y - ScreenCoordinateY, - Time.Ticks + Mouse.MOUSE_DELAY_DOUBLE_CLICK - ); - } - } - } - else - { - base.OnMouseUp(x, y, button); - } - } - - public override void Save(XmlTextWriter writer) - { - base.Save(writer); - - writer.WriteAttributeString("isminimized", IsMinimized.ToString()); - if (LocalSerial == World.Player.Serial) - ProfileManager.CurrentProfile.PaperdollPosition = Location; - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - - if (LocalSerial == World.Player) - { - BuildGump(); - - //GameActions.DoubleClick(0x8000_0000 | LocalSerial); - Client.Game.GetScene()?.DoubleClickDelayed(LocalSerial); - - IsMinimized = bool.Parse(xml.GetAttribute("isminimized")); - X = ProfileManager.CurrentProfile.PaperdollPosition.X; - Y = ProfileManager.CurrentProfile.PaperdollPosition.Y; - } - else - { - Dispose(); - } - } - - protected override void UpdateContents() - { - Mobile mobile = World.Mobiles.Get(LocalSerial); - - if (mobile != null && mobile.Title != _titleLabel.Text) - { - UpdateTitle(mobile.Title); - } - - _paperDollInteractable.RequestUpdate(); - - if (mobile != null) - { - for (int i = 0; i < _slots.Length; i++) - { - int idx = (int)_slots[i].Layer; - - _slots[i].LocalSerial = mobile.FindItemByLayer((Layer)idx)?.Serial ?? 0; - } - - for (int i = 0; i < _slots_right.Length; i++) - { - int idx = (int)_slots_right[i].Layer; - - _slots_right[i].LocalSerial = mobile.FindItemByLayer((Layer)idx)?.Serial ?? 0; - } - } - } - - public override void OnButtonClick(int buttonID) - { - if ( - Client.Game.GameCursor.ItemHold.Enabled - && !Client.Game.GameCursor.ItemHold.IsFixedPosition - ) - { - OnMouseUp(0, 0, MouseButtonType.Left); - - return; - } - - switch ((Buttons)buttonID) - { - case Buttons.Help: - GameActions.RequestHelp(); - - break; - - case Buttons.Options: - GameActions.OpenSettings(); - - break; - - case Buttons.LogOut: - Client.Game.GetScene()?.RequestQuitGame(); - - break; - - case Buttons.Journal: - GameActions.OpenJournal(); - - break; - - case Buttons.Quests: - GameActions.RequestQuestMenu(); - - break; - - case Buttons.Skills: - GameActions.OpenSkills(); - - break; - - case Buttons.Guild: - GameActions.OpenGuildGump(); - - break; - - case Buttons.PeaceWarToggle: - GameActions.ToggleWarMode(); - - break; - - case Buttons.Status: - - if (LocalSerial == World.Player) - { - UIManager.GetGump(LocalSerial)?.Dispose(); - - StatusGumpBase status = StatusGumpBase.GetStatusGump(); - - if (status == null) - { - UIManager.Add(StatusGumpBase.AddStatusGump(ProfileManager.CurrentProfile.StatusGumpPosition.X, ProfileManager.CurrentProfile.StatusGumpPosition.Y)); - } - else - { - status.BringOnTop(); - } - } - else - { - if (UIManager.GetGump(LocalSerial) != null) - { - break; - } - - if (ProfileManager.CurrentProfile.CustomBarsToggled) - { - Rectangle bounds = new Rectangle( - 0, - 0, - HealthBarGumpCustom.HPB_WIDTH, - HealthBarGumpCustom.HPB_HEIGHT_SINGLELINE - ); - - UIManager.Add( - new HealthBarGumpCustom(LocalSerial) - { - X = Mouse.Position.X - (bounds.Width >> 1), - Y = Mouse.Position.Y - 5 - } - ); - } - else - { - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(0x0804); - - UIManager.Add( - new HealthBarGump(LocalSerial) - { - X = Mouse.Position.X - (gumpInfo.UV.Width >> 1), - Y = Mouse.Position.Y - 5 - } - ); - } - } - - break; - } - } - - private enum Buttons - { - Help, - Options, - LogOut, - Journal, - Quests, - Skills, - Guild, - PeaceWarToggle, - Status - } - - private class EquipmentSlot : Control - { - private ItemGumpFixed _itemGump; - private readonly PaperDollGump _paperDollGump; - - private Control bg, border; - private double forcedScale = 1f; - - public EquipmentSlot( - uint serial, - int x, - int y, - Layer layer, - PaperDollGump paperDollGump - ) - { - X = x; - Y = y; - LocalSerial = serial; - Width = 19; - Height = 20; - _paperDollGump = paperDollGump; - Layer = layer; - - Add(bg = new GumpPicTiled(0, 0, 19, 20, 0x243A) { AcceptMouseInput = false }); - - Add(border = new GumpPic(0, 0, 0x2344, 0) { AcceptMouseInput = false }); - - AcceptMouseInput = true; - - WantUpdateSize = false; - } - - public override Control ScaleWidthAndHeight(double scale) - { - forcedScale = scale; - bg?.ScaleWidthAndHeight(scale); - border?.ScaleWidthAndHeight(scale); - return base.ScaleWidthAndHeight(scale); - } - - public override Control ScaleXAndY(double scale) - { - forcedScale = scale; - bg?.ScaleXAndY(scale); - border?.ScaleXAndY(scale); - return base.ScaleXAndY(scale); - } - - public Layer Layer { get; } - - public override void Update() - { - Item item = World.Items.Get(LocalSerial); - - if (item == null || item.IsDestroyed) - { - _itemGump?.Dispose(); - _itemGump = null; - } - - Mobile mobile = World.Mobiles.Get(_paperDollGump.LocalSerial); - - if (mobile != null) - { - Item it_at_layer = mobile.FindItemByLayer(Layer); - - if ((it_at_layer != null && _itemGump != null && _itemGump.Graphic != it_at_layer.DisplayedGraphic) || _itemGump == null) - { - if (_itemGump != null) - { - _itemGump.Dispose(); - _itemGump = null; - } - - item = it_at_layer; - - if (item != null) - { - LocalSerial = it_at_layer.Serial; - - Add( - _itemGump = new ItemGumpFixed(item, 18, 18) - { - X = 0, - Y = 0, - Width = 18, - Height = 18, - HighlightOnMouseOver = false, - CanPickUp = - World.InGame - && ( - World.Player.Serial == _paperDollGump.LocalSerial - || _paperDollGump.CanLift - ) - } - ); - _itemGump.ScaleWidthAndHeight(forcedScale).ScaleXAndY(forcedScale); - } - } - } - - base.Update(); - } - - private class ItemGumpFixed : ItemGump - { - private Point originalSize; - private Point point; - private readonly Rectangle graphicSize; - - public ItemGumpFixed(Item item, int w, int h) - : base(item.Serial, item.DisplayedGraphic, item.Hue, item.X, item.Y) - { - Width = w; - Height = h; - WantUpdateSize = false; - - graphicSize = Client.Game.Arts.GetRealArtBounds(item.DisplayedGraphic); - - originalSize.X = Width; - originalSize.Y = Height; - - if (graphicSize.Width < Width) - { - originalSize.X = graphicSize.Width; - point.X = (Width >> 1) - (originalSize.X >> 1); - } - - if (graphicSize.Height < Height) - { - originalSize.Y = graphicSize.Height; - point.Y = (Height >> 1) - (originalSize.Y >> 1); - } - } - - public override Control ScaleWidthAndHeight(double scale) - { - base.ScaleWidthAndHeight(scale); - - originalSize.X = Width; - originalSize.Y = Height; - - if (graphicSize.Width < Width) - { - originalSize.X = graphicSize.Width; - point.X = (Width >> 1) - (originalSize.X >> 1); - } - - if (graphicSize.Height < Height) - { - originalSize.Y = graphicSize.Height; - point.Y = (Height >> 1) - (originalSize.Y >> 1); - } - - return this; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - Item item = World.Items.Get(LocalSerial); - - if (item == null) - { - Dispose(); - } - - if (IsDisposed) - { - return false; - } - - Vector3 hueVector = ShaderHueTranslator.GetHueVector( - MouseIsOver && HighlightOnMouseOver ? 0x0035 : item.Hue, - item.ItemData.IsPartialHue, - 1, - true - ); - - ref readonly var artInfo = ref Client.Game.Arts.GetArt(item.DisplayedGraphic); - - if (artInfo.Texture != null) - { - batcher.Draw( - artInfo.Texture, - new Rectangle( - x + point.X, - y + point.Y, - originalSize.X, - originalSize.Y - ), - new Rectangle( - artInfo.UV.X + graphicSize.X, - artInfo.UV.Y + graphicSize.Y, - graphicSize.Width, - graphicSize.Height - ), - hueVector - ); - - return true; - } - - return false; - } - - public override bool Contains(int x, int y) - { - return true; - } - } - } - - public class Settings : UISettings - { - public ushort Graphic_Background_Player { get; set; } = 0x07d0; - public ushort Graphic_Background_Other { get; set; } = 0x07d1; - - public ushort Graphic_Button_Help_Normal { get; set; } = 0x07ef; - public ushort Graphic_Button_Help_Pressed { get; set; } = 0x07f0; - public ushort Graphic_Button_Help_Hover { get; set; } = 0x07f1; - - public ushort Graphic_Button_Options_Normal { get; set; } = 2006; - public ushort Graphic_Button_Options_Pressed { get; set; } = 2007; - public ushort Graphic_Button_Options_Hover { get; set; } = 2008; - - public ushort Graphic_Button_Logout_Normal { get; set; } = 2009; - public ushort Graphic_Button_Logout_Pressed { get; set; } = 2010; - public ushort Graphic_Button_Logout_Hover { get; set; } = 2011; - - public ushort Graphic_Button_Journal_Normal { get; set; } = 2012; - public ushort Graphic_Button_Journal_Pressed { get; set; } = 2013; - public ushort Graphic_Button_Journal_Hover { get; set; } = 2014; - - public ushort Graphic_Button_Quest_Normal { get; set; } = 22453; - public ushort Graphic_Button_Quest_Pressed { get; set; } = 22455; - public ushort Graphic_Button_Quest_Hover { get; set; } = 22454; - - public ushort Graphic_Button_Skills_Normal { get; set; } = 2015; - public ushort Graphic_Button_Skills_Pressed { get; set; } = 2016; - public ushort Graphic_Button_Skills_Hover { get; set; } = 2017; - - public ushort Graphic_Button_Guild_Normal { get; set; } = 22450; - public ushort Graphic_Button_Guild_Pressed { get; set; } = 22452; - public ushort Graphic_Button_Guild_Hover { get; set; } = 22451; - - public ushort Graphic_Button_Warmode_Normal { get; set; } = 0x07e8; - public ushort Graphic_Button_Warmode_Pressed { get; set; } = 0x07e9; - public ushort Graphic_Button_Warmode_Hover { get; set; } = 0x07ea; - - public ushort Graphic_Button_Peacemode_Normal { get; set; } = 0x07e5; - public ushort Graphic_Button_Peacemode_Pressed { get; set; } = 0x07e6; - public ushort Graphic_Button_Peacemode_Hover { get; set; } = 0x07e7; - - public ushort Graphic_Button_Status_Normal { get; set; } = 2027; - public ushort Graphic_Button_Status_Pressed { get; set; } = 2028; - public ushort Graphic_Button_Status_Hover { get; set; } = 2029; - - public ushort Graphic_Button_Profile { get; set; } = 0x07D2; - public ushort Graphic_Button_Party { get; set; } = 0x07D2; - - public ushort Graphic_Button_Virtue { get; set; } = 0x0071; - - public ushort Graphic_Button_Durability { get; set; } = 5587; - - public ushort Graphic_Button_Combat { get; set; } = 0x2B34; - - public ushort Graphic_Button_RacialAbilties { get; set; } = 0x2B28; - - public ushort Graphic_Button_Minimized { get; set; } = 0x7EE; - - public ushort Hue_Background_Player { get; set; } = 0; - public ushort Hue_Background_Other { get; set; } = 0; - - public ushort Hue_Title { get; set; } = 0x0386; - public int Size_Width_Hue { get; set; } = 185; - - public int Position_X_Help { get; set; } = 185; - public int Position_Y_Help { get; set; } = 44; - - public int Position_X_Options { get; set; } = 185; - public int Position_Y_Options { get; set; } = 44 + 27 * 1; - - public int Position_X_Logout { get; set; } = 185; - public int Position_Y_Logout { get; set; } = 44 + 27 * 2; - - public int Position_X_Journal { get; set; } = 185; - public int Position_Y_Journal { get; set; } = 44 + 27 * 3; - - public int Position_X_Quest { get; set; } = 185; - public int Position_Y_Quest { get; set; } = 44 + 27 * 3; - - public int Position_X_Skills { get; set; } = 185; - public int Position_Y_Skills { get; set; } = 44 + 27 * 4; - - public int Position_X_Guild { get; set; } = 185; - public int Position_Y_Guild { get; set; } = 44 + 27 * 5; - - public int Position_X_WarMode { get; set; } = 185; - public int Position_Y_Warmode { get; set; } = 44 + 27 * 6; - - public int Position_X_Status { get; set; } = 185; - public int Position_Y_Status { get; set; } = 44 + 27 * 7; - - public int Position_X_Profile { get; set; } = 25; - public int Position_Y_Profile { get; set; } = 196; - public int Racial_Abilities_Width { get; set; } = 14; - - public int Position_X_RacialAbilities { get; set; } = 23; - public int Position_Y_RacialAbilities { get; set; } = 200; - - public int Position_X_Virtue { get; set; } = 80; - public int Position_Y_Virtue { get; set; } = 4; - - public int Position_X_Durability { get; set; } = 0; - public int Position_Y_Durability { get; set; } = 40; - - public int Position_X_LeftSlots { get; set; } = 2; - public int Position_Y_LeftSlots { get; set; } = 75; - public int Size_Height_LeftSlots { get; set; } = 21; - - public int Position_X_RightSlots { get; set; } = 166; - public int Position_Y_RightSlots { get; set; } = 75; - public int Size_Height_RightSlots { get; set; } = 21; - - public int Position_X_Avatar { get; set; } = 8; - public int Position_Y_Avatar { get; set; } = 19; - - public int Position_X_CombatBook { get; set; } = 156; - public int Position_Y_CombatBook { get; set; } = 200; - - public int Position_X_Title { get; set; } = 39; - public int Position_Y_Title { get; set; } = 262; - - public int Position_X_MinimizeButton { get; set; } = 228; - public int Position_Y_MinimizeButton { get; set; } = 260; - public int Size_Width_MinimizeButton { get; set; } = 16; - public int Size_Height_MinimizeButton { get; set; } = 16; - - - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/PartyGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/PartyGump.cs deleted file mode 100644 index 9082f2be1..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/PartyGump.cs +++ /dev/null @@ -1,442 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Assets; -using ClassicUO.Network; -using ClassicUO.Resources; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class PartyGump : Gump - { - public PartyGump(int x, int y, bool canloot) : base(0, 0) - { - X = x; - Y = y; - CanLoot = canloot; - - CanMove = true; - AcceptMouseInput = true; - CanCloseWithRightClick = true; - - BuildGump(); - } - - public bool CanLoot; - - - protected override void UpdateContents() - { - Clear(); - BuildGump(); - } - - private void BuildGump() - { - Add - ( - new ResizePic(0x0A28) - { - Width = 450, - Height = 480 - } - ); - - Add - ( - new Label(ResGumps.Tell, false, 0x0386, font: 1) - { - X = 40, - Y = 30 - } - ); - - Add - ( - new Label(ResGumps.Kick, false, 0x0386, font: 1) - { - X = 80, - Y = 30 - } - ); - - Add - ( - new Label(ResGumps.PartyManifest, false, 0x0386, font: 2) - { - X = 153, - Y = 20 - } - ); - - bool isLeader = World.Party.Leader == 0 || World.Party.Leader == World.Player; - bool isMemeber = World.Party.Leader != 0 && World.Party.Leader != World.Player; - - int yPtr = 48; - - for (int i = 0; i < 10; i++) - { - Add - ( - new Button((int) (Buttons.TellMember + i), 0x0FAB, 0x0FAD, 0x0FAC) - { - X = 40, - Y = yPtr + 2, - ButtonAction = ButtonAction.Activate - } - ); - - if (isLeader) - { - Add - ( - new Button((int) (Buttons.KickMember + i), 0x0FB1, 0x0FB3, 0x0FB2) - { - X = 80, - Y = yPtr + 2, - ButtonAction = ButtonAction.Activate - } - ); - } - - Add(new GumpPic(130, yPtr, 0x0475, 0)); - - string name = ""; - - if (World.Party.Members[i] != null && World.Party.Members[i].Name != null) - { - name = World.Party.Members[i].Name; - } - - Add - ( - new Label - ( - name, - false, - 0x0386, - font: 2, - maxwidth: 250, - align: TEXT_ALIGN_TYPE.TS_CENTER - ) - { - X = 140, - Y = yPtr + 1 - } - ); - - yPtr += 25; - } - - Add - ( - new Button((int) Buttons.SendMessage, 0x0FAB, 0x0FAD, 0x0FAC) - { - X = 70, - Y = 307, - ButtonAction = ButtonAction.Activate - } - ); - - Add - ( - new Label(ResGumps.SendThePartyAMessage, false, 0x0386, font: 2) - { - X = 110, - Y = 307 - } - ); - - if (CanLoot) - { - Add - ( - new Button((int) Buttons.LootType, 0x0FA2, 0x0FA2, 0x0FA2) - { - X = 70, - Y = 334, - ButtonAction = ButtonAction.Activate - } - ); - - Add - ( - new Label(ResGumps.PartyCanLootMe, false, 0x0386, font: 2) - { - X = 110, - Y = 334 - } - ); - } - else - { - Add - ( - new Button((int) Buttons.LootType, 0x0FA9, 0x0FA9, 0x0FA9) - { - X = 70, - Y = 334, - ButtonAction = ButtonAction.Activate - } - ); - - Add - ( - new Label(ResGumps.PartyCannotLootMe, false, 0x0386, font: 2) - { - X = 110, - Y = 334 - } - ); - } - - - Add - ( - new Button((int) Buttons.Leave, 0x0FAE, 0x0FB0, 0x0FAF) - { - X = 70, - Y = 360, - ButtonAction = ButtonAction.Activate - } - ); - - if (isMemeber) - { - Add - ( - new Label(ResGumps.LeaveTheParty, false, 0x0386, font: 2) - { - X = 110, - Y = 360 - } - ); - } - else - { - Add - ( - new Label(ResGumps.DisbandTheParty, false, 0x0386, font: 2) - { - X = 110, - Y = 360 - } - ); - } - - if (isLeader) - { - Add - ( - new Button((int) Buttons.Add, 0x0FA8, 0x0FAA, 0x0FA9) - { - X = 70, - Y = 385, - ButtonAction = ButtonAction.Activate - } - ); - - Add - ( - new Label(ResGumps.AddNewMember, false, 0x0386, font: 2) - { - X = 110, - Y = 385 - } - ); - } - - Add - ( - new Button((int) Buttons.OK, 0x00F9, 0x00F8, 0x00F7) - { - X = 130, - Y = 430, - ButtonAction = ButtonAction.Activate - } - ); - - Add - ( - new Button((int) Buttons.Cancel, 0x00F3, 0x00F1, 0x00F2) - { - X = 236, - Y = 430, - ButtonAction = ButtonAction.Activate - } - ); - } - - public override void OnButtonClick(int buttonID) - { - switch ((Buttons) buttonID) - { - case Buttons.OK: - if (World.Party.Leader != 0 && World.Party.CanLoot != CanLoot) - { - World.Party.CanLoot = CanLoot; - NetClient.Socket.Send_PartyChangeLootTypeRequest(CanLoot); - } - - Dispose(); - - break; - - case Buttons.Cancel: - Dispose(); - - break; - - case Buttons.SendMessage: - if (World.Party.Leader == 0) - { - GameActions.Print - ( - ResGumps.YouAreNotInAParty, - 0, - MessageType.System, - 3, - false - ); - } - else - { - UIManager.SystemChat.TextBoxControl.SetText("/"); - } - - break; - - case Buttons.LootType: - CanLoot = !CanLoot; - RequestUpdateContents(); - - break; - - case Buttons.Leave: - if (World.Party.Leader == 0) - { - GameActions.Print - ( - ResGumps.YouAreNotInAParty, - 0, - MessageType.System, - 3, - false - ); - } - else - { - // NetClient.Socket.Send(new PPartyRemoveRequest(World.Player)); - GameActions.RequestPartyQuit(); - //for (int i = 0; i < 10; i++) - //{ - // if (World.Party.Members[i] != null && World.Party.Members[i].Serial != 0) - // { - // NetClient.Socket.Send(new PPartyRemoveRequest(World.Party.Members[i].Serial)); - // } - //} - } - - break; - - case Buttons.Add: - if (World.Party.Leader == 0 || World.Party.Leader == World.Player) - { - NetClient.Socket.Send_PartyInviteRequest(); - } - - break; - - default: - if (buttonID >= (int) Buttons.TellMember && buttonID < (int) Buttons.KickMember) - { - int index = (int) (buttonID - Buttons.TellMember); - - if (World.Party.Members[index] == null || World.Party.Members[index].Serial == 0) - { - GameActions.Print - ( - ResGumps.ThereIsNoOneInThatPartySlot, - 0, - MessageType.System, - 3, - false - ); - } - else - { - //UIManager.SystemChat.textBox.SetText($"/{index + 1}"); - //UIManager.SystemChat.Mode = ChatMode.Party; - UIManager.SystemChat.TextBoxControl.SetText($"/{index + 1} "); - } - } - else if (buttonID >= (int) Buttons.KickMember) - { - int index = (int) (buttonID - Buttons.KickMember); - - if (World.Party.Members[index] == null || World.Party.Members[index].Serial == 0) - { - GameActions.Print - ( - ResGumps.ThereIsNoOneInThatPartySlot, - 0, - MessageType.System, - 3, - false - ); - } - else - { - NetClient.Socket.Send_PartyRemoveRequest(World.Party.Members[index].Serial); - } - } - - break; - } - } - - private enum Buttons - { - OK, - Cancel, - SendMessage, - LootType, - Leave, - Add, - TellMember, - KickMember = TellMember + 10 - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/PartyInviteGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/PartyInviteGump.cs deleted file mode 100644 index 6ddb5d9c1..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/PartyInviteGump.cs +++ /dev/null @@ -1,115 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Network; -using ClassicUO.Resources; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class PartyInviteGump : Gump - { - public PartyInviteGump(uint inviter) : base(0, 0) - { - CanCloseWithRightClick = true; - - Mobile mobile = World.Mobiles.Get(inviter); - - var nameWidthAdjustment = mobile == null || mobile.Name.Length < 10 ? 0 : mobile.Name.Length * 5; - - AlphaBlendControl partyGumpBackground = new AlphaBlendControl - { - Width = 270 + nameWidthAdjustment, - Height = 80, - X = Client.Game.Scene.Camera.Bounds.Width / 2 - 125, - Y = 150, - Alpha = 0.8f - }; - - Label text = new Label(string.Format(ResGumps.P0HasInvitedYouToParty, mobile == null || string.IsNullOrEmpty(mobile.Name) ? ResGumps.NoName : mobile.Name), true, 15) - { - X = Client.Game.Scene.Camera.Bounds.Width / 2 - 115, - Y = 165 - }; - - NiceButton acceptButton = new NiceButton - ( - Client.Game.Scene.Camera.Bounds.Width / 2 + 99 + nameWidthAdjustment, - 205, - 45, - 25, - ButtonAction.Activate, - ResGumps.Accept - ); - - NiceButton declineButton = new NiceButton - ( - Client.Game.Scene.Camera.Bounds.Width / 2 + 39 + nameWidthAdjustment, - 205, - 45, - 25, - ButtonAction.Activate, - ResGumps.Decline - ); - - Add(partyGumpBackground); - Add(text); - Add(acceptButton); - Add(declineButton); - - acceptButton.MouseUp += (sender, e) => - { - if (World.Party.Inviter != 0 && World.Party.Leader == 0) - { - GameActions.RequestPartyAccept(World.Party.Inviter); - World.Party.Leader = World.Party.Inviter; - World.Party.Inviter = 0; - } - - base.Dispose(); - }; - - declineButton.MouseUp += (sender, e) => - { - if (World.Party.Inviter != 0 && World.Party.Leader == 0) - { - NetClient.Socket.Send_PartyDecline(World.Party.Inviter); - World.Party.Inviter = 0; - } - - base.Dispose(); - }; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/PopupMenuGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/PopupMenuGump.cs deleted file mode 100644 index e05d420a6..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/PopupMenuGump.cs +++ /dev/null @@ -1,156 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Data; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - public class PopupMenuGump : Gump - { - private ushort _selectedItem; - private readonly PopupMenuData _data; - - public PopupMenuGump(PopupMenuData data) : base(0, 0) - { - CanMove = false; - CanCloseWithRightClick = true; - _data = data; - - ResizePic pic = new ResizePic(0x0A3C) - { - Alpha = 0.75f - }; - - Add(pic); - int offsetY = 10; - bool arrowAdded = false; - int width = 0, height = 20; - - for (int i = 0; i < data.Items.Length; i++) - { - ref PopupMenuItem item = ref data.Items[i]; - - string text = ClilocLoader.Instance.GetString(item.Cliloc); - - ushort hue = item.Hue; - - if (item.ReplacedHue != 0) - { - uint h = (HuesHelper.Color16To32(item.ReplacedHue) << 8) | 0xFF; - - FontsLoader.Instance.SetUseHTML(true, h); - } - - Label label = new Label(text, true, hue, font: 1) - { - X = 10, - Y = offsetY - }; - - FontsLoader.Instance.SetUseHTML(false); - - HitBox box = new HitBox(10, offsetY, label.Width, label.Height) - { - Tag = item.Index - }; - - box.MouseEnter += (sender, e) => - { - _selectedItem = (ushort)(sender as HitBox).Tag; - }; - - Add(box); - Add(label); - - if ((item.Flags & 0x02) != 0 && !arrowAdded) - { - arrowAdded = true; - - // TODO: wat? - Add - ( - new Button(0, 0x15E6, 0x15E2, 0x15E2) - { - X = 20, - Y = offsetY - } - ); - - height += 20; - } - - offsetY += label.Height; - - if (!arrowAdded) - { - height += label.Height; - - if (width < label.Width) - { - width = label.Width; - } - } - } - - width += 20; - - if (height <= 10 || width <= 20) - { - Dispose(); - } - else - { - pic.Width = width; - pic.Height = height; - - foreach (HitBox box in FindControls()) - { - box.Width = width - 20; - } - } - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - if (button == MouseButtonType.Left) - { - GameActions.ResponsePopupMenu(_data.Serial, _selectedItem); - Dispose(); - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/ProfileGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/ProfileGump.cs deleted file mode 100644 index 1ebee1f21..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/ProfileGump.cs +++ /dev/null @@ -1,254 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Network; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class ProfileGump : Gump - { - private const int _diffY = 22; - private readonly DataBox _databox; - private readonly GumpPic _gumpPic; - private readonly HitBox _hitBox; - private bool _isMinimized; - private readonly string _originalText; - private readonly ScrollArea _scrollArea; - private readonly StbTextBox _textBox; - - public ProfileGump(uint serial, string header, string footer, string body, bool canEdit) : base(serial, 0) - { - Height = 300 + _diffY; - CanMove = true; - AcceptKeyboardInput = true; - CanCloseWithRightClick = true; - - Add(_gumpPic = new GumpPic(143, 0, 0x82D, 0)); - _gumpPic.MouseDoubleClick += _picBase_MouseDoubleClick; - - Add(new ExpandableScroll(0, _diffY, Height - _diffY, 0x0820)); - - _scrollArea = new ScrollArea - ( - 22, - 32 + _diffY, - 272 - 22, - Height - (96 + _diffY), - false - ); - - Label topText = new Label - ( - header, - true, - 0, - font: 1, - maxwidth: 140 - ) - { - X = 53, - Y = 6 - }; - - _scrollArea.Add(topText); - - int offsetY = topText.Height - 15; - - _scrollArea.Add(new GumpPic(4, offsetY, 0x005C, 0)); - - _scrollArea.Add - ( - new GumpPicTiled - ( - 56, - offsetY, - 138, - 0, - 0x005D - ) - ); - - _scrollArea.Add(new GumpPic(194, offsetY, 0x005E, 0)); - - offsetY += 44; - - _textBox = new StbTextBox(1, -1, 220) - { - Width = 220, - X = 4, - Y = offsetY, - IsEditable = canEdit, - Multiline = true - }; - - _originalText = body; - _textBox.TextChanged += _textBox_TextChanged; - _textBox.SetText(body); - _scrollArea.Add(_textBox); - - - _databox = new DataBox(4, _textBox.Height + 3, 1, 1); - _databox.WantUpdateSize = true; - - _databox.Add(new GumpPic(4, 0, 0x005F, 0)); - - _databox.Add - ( - new GumpPicTiled - ( - 13, - 0 + 9, - 197, - 0, - 0x0060 - ) - ); - - _databox.Add(new GumpPic(210, 0, 0x0061, 0)); - - _databox.Add - ( - new Label - ( - footer, - true, - 0, - font: 1, - maxwidth: 220 - ) - { - X = 2, - Y = 26 - } - ); - - Add(_scrollArea); - _scrollArea.Add(_databox); - - Add(_hitBox = new HitBox(143, 0, 23, 24)); - _hitBox.MouseUp += _hitBox_MouseUp; - } - - public bool IsMinimized - { - get => _isMinimized; - set - { - if (_isMinimized != value) - { - _isMinimized = value; - - _gumpPic.Graphic = value ? (ushort) 0x9D4 : (ushort) 0x82D; - - if (value) - { - _gumpPic.X = 0; - } - else - { - _gumpPic.X = 143; - } - - foreach (Control c in Children) - { - c.IsVisible = !value; - } - - _gumpPic.IsVisible = true; - WantUpdateSize = true; - } - } - } - - - public override void Update() - { - _scrollArea.Height = Height - (96 + _diffY); - _databox.Y = _textBox.Bounds.Bottom + 3; - _databox.WantUpdateSize = true; - - base.Update(); - } - - private void _textBox_TextChanged(object sender, EventArgs e) - { - _textBox.Height = Math.Max - ( - FontsLoader.Instance.GetHeightUnicode - ( - 1, - _textBox.Text, - 220, - TEXT_ALIGN_TYPE.TS_LEFT, - 0x0 - ) + 5, - 20 - ); - } - - - private void _hitBox_MouseUp(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtonType.Left && !IsMinimized) - { - IsMinimized = true; - } - } - - private void _picBase_MouseDoubleClick(object sender, MouseDoubleClickEventArgs e) - { - if (e.Button == MouseButtonType.Left && IsMinimized) - { - IsMinimized = false; - } - } - - public override void OnButtonClick(int buttonID) - { - // necessary to avoid closing - } - - public override void Dispose() - { - if (_originalText != _textBox.Text && World.Player != null && !World.Player.IsDestroyed && NetClient.Socket.IsConnected) - { - NetClient.Socket.Send_ProfileUpdate(LocalSerial, _textBox.Text); - } - - base.Dispose(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/QuestArrowGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/QuestArrowGump.cs deleted file mode 100644 index 746fdafd1..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/QuestArrowGump.cs +++ /dev/null @@ -1,231 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.Scenes; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class QuestArrowGump : Gump - { - private GumpPic _arrow; - private Direction _direction; - private int _mx; - private int _my; - private bool _needHue; - private float _timer; - - public QuestArrowGump(uint serial, int mx, int my) : base(serial, serial) - { - CanMove = false; - CanCloseWithRightClick = false; - - AcceptMouseInput = true; - - SetRelativePosition(mx, my); - WantUpdateSize = false; - } - - public void SetRelativePosition(int x, int y) - { - _mx = x; - _my = y; - } - - public override void Update() - { - base.Update(); - - if (!World.InGame) - { - Dispose(); - } - - GameScene scene = Client.Game.GetScene(); - - if (IsDisposed || ProfileManager.CurrentProfile == null || scene == null) - { - return; - } - - Direction dir = (Direction) GameCursor.GetMouseDirection - ( - World.Player.X, - World.Player.Y, - _mx, - _my, - 0 - ); - - ushort gumpID = (ushort) (0x1194 + ((int) dir + 1) % 8); - - if (_direction != dir || _arrow == null) - { - _direction = dir; - - if (_arrow == null) - { - Add(_arrow = new GumpPic(0, 0, gumpID, 0)); - } - else - { - _arrow.Graphic = gumpID; - } - - Width = _arrow.Width; - Height = _arrow.Height; - } - - int gox = World.Player.X - _mx; - int goy = World.Player.Y - _my; - - - int x = (Client.Game.Scene.Camera.Bounds.Width >> 1) - (gox - goy) * 22; - int y = (Client.Game.Scene.Camera.Bounds.Height >> 1) - (gox + goy) * 22; - - x -= (int) World.Player.Offset.X; - y -= (int) (World.Player.Offset.Y - World.Player.Offset.Z); - y += World.Player.Z << 2; - - - switch (dir) - { - case Direction.North: - x -= _arrow.Width; - - break; - - case Direction.South: - y -= _arrow.Height; - - break; - - case Direction.East: - x -= _arrow.Width; - y -= _arrow.Height; - - break; - - case Direction.West: break; - - case Direction.Right: - x -= _arrow.Width; - y -= _arrow.Height / 2; - - break; - - case Direction.Left: - x += _arrow.Width / 2; - y -= _arrow.Height / 2; - - break; - - case Direction.Up: - x -= _arrow.Width / 2; - y += _arrow.Height / 2; - - break; - - case Direction.Down: - x -= _arrow.Width / 2; - y -= _arrow.Height; - - break; - } - - var camera = scene.Camera; - - Point p = new Point(x, y); - p = Client.Game.Scene.Camera.WorldToScreen(p); - p.X += camera.Bounds.X; - p.Y += camera.Bounds.Y; - x = p.X; - y = p.Y; - - if (x < camera.Bounds.X) - { - x = camera.Bounds.X; - } - else if (x > camera.Bounds.Right - _arrow.Width) - { - x = camera.Bounds.Right - _arrow.Width; - } - - - if (y < camera.Bounds.Y) - { - y = camera.Bounds.Y; - } - else if (y > camera.Bounds.Bottom - _arrow.Height) - { - y = camera.Bounds.Bottom - _arrow.Height; - } - - X = x; - Y = y; - - if (_timer < Time.Ticks) - { - _timer = Time.Ticks + 1000; - _needHue = !_needHue; - } - - _arrow.Hue = (ushort) (_needHue ? 0 : 0x21); - } - - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - bool leftClick = button == MouseButtonType.Left; - bool rightClick = button == MouseButtonType.Right; - - if (leftClick || rightClick) - { - GameActions.QuestArrow(rightClick); - } - } - - public override bool Contains(int x, int y) - { - if (_arrow == null) - { - return true; - } - - return _arrow.Contains(x, y); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/QuestionGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/QuestionGump.cs deleted file mode 100644 index 06d6e89c7..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/QuestionGump.cs +++ /dev/null @@ -1,108 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Assets; -using ClassicUO.Renderer; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class QuestionGump : Gump - { - private readonly Action _result; - - public QuestionGump(string message, Action result) : base(0, 0) - { - CanCloseWithRightClick = true; - Add(new GumpPic(0, 0, 0x0816, 0)); - - ref readonly var gumpInfo = ref Client.Game.Gumps.GetGump(0x0816); - - Width = gumpInfo.UV.Width; - Height = gumpInfo.UV.Height; - - Add(new Label(message, false, 0x0386, 165, font: 1) { X = 33, Y = 30 }); - - Add( - new Button((int)Buttons.Cancel, 0x817, 0x818, 0x0819) - { - X = 37, - Y = 75, - ButtonAction = ButtonAction.Activate - } - ); - - Add( - new Button((int)Buttons.Ok, 0x81A, 0x81B, 0x081C) - { - X = 100, - Y = 75, - ButtonAction = ButtonAction.Activate - } - ); - - CanMove = false; - IsModal = true; - - X = (Client.Game.Window.ClientBounds.Width - Width) >> 1; - Y = (Client.Game.Window.ClientBounds.Height - Height) >> 1; - - WantUpdateSize = false; - _result = result; - } - - public override void OnButtonClick(int buttonID) - { - switch (buttonID) - { - case 0: - _result(false); - Dispose(); - - break; - - case 1: - _result(true); - Dispose(); - - break; - } - } - - private enum Buttons - { - Cancel, - Ok - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/RaceChangeGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/RaceChangeGump.cs deleted file mode 100644 index caa807377..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/RaceChangeGump.cs +++ /dev/null @@ -1,823 +0,0 @@ -using ClassicUO.Assets; -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Network; -using System; -using System.Collections.Generic; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class RaceChangeGump : Gump - { - private bool isFemale { get; } = false; - private RaceType selectedRace { get; } = RaceType.HUMAN; - private PlayerMobile fakeMobile; - private CustomPaperDollGump paperDollInteractable; - private readonly Dictionary> CurrentColorOption = new Dictionary>(); - private readonly Dictionary CurrentOption = new Dictionary() - { - { - Layer.Hair, 1 - }, - { - Layer.Beard, 0 - } - }; - private Item hair, beard; - - #region - private ushort raceTextGraphic - { - get - { - switch (selectedRace) - { - case RaceType.HUMAN: - return 0x702; - case RaceType.ELF: - return 0x705; - case RaceType.GARGOYLE: - return 0x7D4; - } - return 0; - } - } - private int raceTextWidth - { - get - { - switch (selectedRace) - { - case RaceType.HUMAN: - return 79; - case RaceType.ELF: - return 79; - case RaceType.GARGOYLE: - return 99; - } - return 0; - } - } - private ushort genderTextGraphic - { - get - { - return (ushort)(isFemale ? 0x70D : 0x710); - } - } - #endregion - - public RaceChangeGump(bool isFemale, byte race) : base(0, 0) - { - if (race <= 0 || race > (int)RaceType.GARGOYLE) - { - //Invalid race byte - Dispose(); - return; - } - - selectedRace = (RaceType)race; - this.isFemale = isFemale; - - X = 50; - Y = 50; - CanMove = false; - CanCloseWithRightClick = true; - AcceptMouseInput = true; - - BuildGump(); - - WantUpdateSize = true; - } - - private void BuildGump() - { - #region Background elements - Add - ( - new ResizePic(0x0E10) - { - X = 0, - Y = 0, - Width = 595, - Height = 400 - }, - 1 - ); //Main background - - Add - ( - new ResizePic(0x0E10) - { - X = 25, - Y = 45, - Width = 151, - Height = 310 - }, - 1 - ); //Left side, hair style etc - - Add - ( - new ResizePic(0x0E10) - { - X = 419, - Y = 45, - Width = 151, - Height = 310 - }, - 1 - ); //Right side tone/colors - #endregion - - Add(new GumpPic(176 - raceTextWidth, 360, raceTextGraphic, 0)); //non-functional "Button" that says Human, Elf, or Gargoyle - - Add(new GumpPic(419, 360, genderTextGraphic, 0)); //non-functional "Button" that says Male or Female - - Button confirmButton; - Add(confirmButton = new Button(0, 0x15A4, 0x15A6, 0x15A5) { X = 560, Y = 360 }); //Button to confirm, in classic client it is an arrow pointing right. - confirmButton.MouseUp += ConfirmButton_MouseUp; - - //Add hair styles - BuildHairStyles(40, 60); - - //Add color pickers - BuildColorOptions(434, 60); - - //Create fake character - CreateCharacter(); - UpdateEquipments(); - - //Add the main paperdoll graphic - Add(new GumpPic(185, 25, 0x708, 0)); - Add - ( - paperDollInteractable = new CustomPaperDollGump(210, 75, fakeMobile, hair, beard) - { - AcceptMouseInput = false - } - ); - - paperDollInteractable.RequestUpdate(); - - Add(new GumpPic(211, 15, 0x769, 0)); //Character Race Changer text - } - - /// - /// Build hair options for race change gump. - /// - /// The starting point for these ui elements - /// The starting point for these ui elements - private void BuildHairStyles(int x, int y) - { - #region TextSetup - bool isAsianLang = string.Compare(Settings.GlobalSettings.Language, "CHT", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "KOR", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "JPN", StringComparison.InvariantCultureIgnoreCase) == 0; - - bool unicode = isAsianLang; - byte font = (byte)(isAsianLang ? 3 : 9); - ushort hue = (ushort)(isAsianLang ? 0xFFFF : 0); - #endregion - - CharacterCreationValues.ComboContent content = CharacterCreationValues.GetHairComboContent(isFemale, selectedRace); - - CurrentOption[Layer.Beard] = 0; - CurrentOption[Layer.Hair] = 0; - - #region Hair style - Add - ( - new Label(ClilocLoader.Instance.GetString(selectedRace == RaceType.GARGOYLE ? 1112309 : 3000121), unicode, hue, font: font) - { - X = x + 1, - Y = y - } - ); - y += 15; - - Combobox hair; - Add - (hair = - new Combobox - ( - x, - y, - 120, - content.Labels, - CurrentOption[Layer.Hair] - ) - ); - hair.OnOptionSelected += (s, e) => - { - CurrentOption[Layer.Hair] = e; - UpdateEquipments(); - paperDollInteractable.RequestUpdate(); - }; - y += 30; - #endregion - - #region Facial Hair - if (!isFemale && selectedRace != RaceType.ELF) - { - content = CharacterCreationValues.GetFacialHairComboContent(selectedRace); - - Add - ( - new Label(ClilocLoader.Instance.GetString(selectedRace == RaceType.GARGOYLE ? 1112511 : 3000122), unicode, hue, font: font) - { - X = x + 1, - Y = y - } - ); - y += 15; - - Combobox facialHair; - Add - (facialHair = - new Combobox - ( - x, - y, - 120, - content.Labels, - CurrentOption[Layer.Beard] - ) - ); - facialHair.OnOptionSelected += (s, e) => - { - CurrentOption[Layer.Beard] = e; - UpdateEquipments(); - paperDollInteractable.RequestUpdate(); - }; - } - #endregion - } - - /// - /// Build color options for race change gump - /// - /// The starting point for these ui elements - /// The starting point for these ui elements - private void BuildColorOptions(int x, int y) - { - ushort[] pallet = CharacterCreationValues.GetSkinPallet(selectedRace); - - AddCustomColorPicker - ( - x, - y, - pallet, - Layer.Invalid, - 3000183, - 8, - pallet.Length >> 3 - ); - y += 42; - - // Hair - pallet = CharacterCreationValues.GetHairPallet(selectedRace); - - AddCustomColorPicker - ( - x, - y, - pallet, - Layer.Hair, - selectedRace == RaceType.GARGOYLE ? 1112322 : 3000184, - 8, - pallet.Length >> 3 - ); - y += 42; - - if (!isFemale && selectedRace != RaceType.ELF) - { - // Facial - pallet = CharacterCreationValues.GetHairPallet(selectedRace); - - AddCustomColorPicker - ( - x, - y, - pallet, - Layer.Beard, - selectedRace == RaceType.GARGOYLE ? 1112512 : 3000446, - 8, - pallet.Length >> 3 - ); - } - } - - /// - /// Must be called *after* color options have been set up. - /// - private void CreateCharacter() - { - #region Create a fake character to use for the gump - if (fakeMobile == null || fakeMobile.IsDestroyed) - { - fakeMobile = new PlayerMobile(0); - } - - LinkedObject first = fakeMobile.Items; - - while (first != null) - { - LinkedObject next = first.Next; - - World.RemoveItem((Item)first, true); - - first = next; - } - - fakeMobile.Clear(); - fakeMobile.Race = selectedRace; - fakeMobile.IsFemale = isFemale; - - if (isFemale) - { - fakeMobile.Flags |= Flags.Female; - } - else - { - fakeMobile.Flags &= ~Flags.Female; - } - #endregion - - if (selectedRace == RaceType.ELF) - { - fakeMobile.Graphic = (ushort)(isFemale ? 0x025E : 0x025D); - } - else - { - fakeMobile.Graphic = (ushort)(isFemale ? 0x0191 : 0x0190); - } - - hair = CreateItem(0x4000_0000 + (int)Layer.Hair, 0, Layer.Hair); - if (!isFemale && selectedRace != RaceType.ELF) - { - beard = CreateItem(0x4000_0000 + (int)Layer.Beard, 0, Layer.Beard); - } - } - - private void AddCustomColorPicker - ( - int x, - int y, - ushort[] pallet, - Layer layer, - int clilocLabel, - int rows, - int columns - ) - { - CustomColorPicker colorPicker; - - Add - ( - colorPicker = new CustomColorPicker - ( - layer, - clilocLabel, - pallet, - rows, - columns - ) - { - X = x, - Y = y - }, - 1 - ); - - if (!CurrentColorOption.ContainsKey(layer)) - { - CurrentColorOption[layer] = new Tuple(0, colorPicker.HueSelected); - } - else - { - colorPicker.SetSelectedIndex(CurrentColorOption[layer].Item1); - } - - colorPicker.ColorSelected += ColorPicker_ColorSelected; - } - - private void ColorPicker_ColorSelected(object sender, ColorSelectedEventArgs e) - { - if (e.SelectedIndex == 0xFFFF) - { - return; - } - - CurrentColorOption[e.Layer] = new Tuple(e.SelectedIndex, e.SelectedHue); - - switch (e.Layer) - { - case Layer.Beard: - beard.Hue = e.SelectedHue; - break; - case Layer.Hair: - hair.Hue = e.SelectedHue; - break; - case Layer.Invalid: - fakeMobile.Hue = e.SelectedHue; - break; - } - - paperDollInteractable.RequestUpdate(); - } - - private void ConfirmButton_MouseUp(object sender, MouseEventArgs e) - { - if (e.Button == Input.MouseButtonType.Left) - { - if (!isFemale && selectedRace != RaceType.ELF) //Has beard - { - NetClient.Socket.Send_ChangeRaceRequest( - CurrentColorOption[Layer.Invalid].Item2, - (ushort)CharacterCreationValues.GetHairComboContent(isFemale, selectedRace).GetGraphic(CurrentOption[Layer.Hair]), - CurrentColorOption[Layer.Hair].Item2, - (ushort)CharacterCreationValues.GetFacialHairComboContent(selectedRace).GetGraphic(CurrentOption[Layer.Beard]), - CurrentColorOption[Layer.Beard].Item2 - ); - } - else //No beard - { - NetClient.Socket.Send_ChangeRaceRequest( - CurrentColorOption[Layer.Invalid].Item2, - (ushort)CharacterCreationValues.GetHairComboContent(isFemale, selectedRace).GetGraphic(CurrentOption[Layer.Hair]), - CurrentColorOption[Layer.Hair].Item2, - 0, - 0 - ); - } - - //Cleanup - if (hair != null) - { - World.RemoveItem(hair, true); - } - if (beard != null) - { - World.RemoveItem(beard, true); - } - Dispose(); - } - } - - private void UpdateEquipments() - { - Layer layer; - CharacterCreationValues.ComboContent content; - - fakeMobile.Hue = CurrentColorOption[Layer.Invalid].Item2; - - if (beard != null) - { - layer = Layer.Beard; - content = CharacterCreationValues.GetFacialHairComboContent(selectedRace); - - beard.Graphic = (ushort)content.GetGraphic(CurrentOption[layer]); - beard.Hue = CurrentColorOption[layer].Item2; - } - - layer = Layer.Hair; - content = CharacterCreationValues.GetHairComboContent(isFemale, selectedRace); - - hair.Graphic = (ushort)content.GetGraphic(CurrentOption[layer]); - hair.Hue = CurrentColorOption[layer].Item2; - } - - private Item CreateItem(int id, ushort hue, Layer layer) - { - if (id == 0) - { - return null; - } - - Item item = World.GetOrCreateItem(0x4000_0000 + (uint)layer); // use layer as unique Serial - item.Graphic = (ushort)id; - item.Hue = hue; - item.Layer = layer; - // - - return item; - } - - #region Classes - private class ColorSelectedEventArgs : EventArgs - { - public ColorSelectedEventArgs(Layer layer, ushort[] pallet, int selectedIndex) - { - Layer = layer; - Pallet = pallet; - SelectedIndex = selectedIndex; - } - - public Layer Layer { get; } - - private ushort[] Pallet { get; } - - public int SelectedIndex { get; } - - public ushort SelectedHue => Pallet != null && SelectedIndex >= 0 && SelectedIndex < Pallet.Length ? Pallet[SelectedIndex] : (ushort)0xFFFF; - } - - private class CustomColorPicker : Control - { - //private readonly ColorBox _box; - private readonly int _cellH; - private readonly int _cellW; - private readonly ColorBox _colorPicker; - private ColorPickerBox _colorPickerBox; - private readonly int _columns, _rows; - private int _lastSelectedIndex; - private readonly Layer _layer; - private readonly ushort[] _pallet; - - public CustomColorPicker(Layer layer, int label, ushort[] pallet, int rows, int columns) - { - Width = 121; - Height = 25; - _cellW = 125 / columns; - _cellH = 280 / rows; - _columns = columns; - _rows = rows; - _layer = layer; - _pallet = pallet; - - bool isAsianLang = string.Compare(Settings.GlobalSettings.Language, "CHT", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "KOR", StringComparison.InvariantCultureIgnoreCase) == 0 || - string.Compare(Settings.GlobalSettings.Language, "JPN", StringComparison.InvariantCultureIgnoreCase) == 0; - - bool unicode = isAsianLang; - byte font = (byte)(isAsianLang ? 3 : 9); - ushort hue = (ushort)(isAsianLang ? 0xFFFF : 0); - - Add - ( - new Label(ClilocLoader.Instance.GetString(label), unicode, hue, font: font) - { - X = 0, - Y = 0 - } - ); - - Add - ( - _colorPicker = new ColorBox(121, 23, (ushort)((pallet?[0] ?? 1) + 1)) - { - X = 1, - Y = 15 - } - ); - - _colorPicker.MouseUp += ColorPicker_MouseClick; - } - - public ushort HueSelected => _colorPicker.Hue; - - public event EventHandler ColorSelected; - - public void SetSelectedIndex(int index) - { - if (_colorPickerBox != null) - { - _colorPickerBox.SelectedIndex = index; - - SetCurrentHue(); - } - } - - private void SetCurrentHue() - { - _colorPicker.Hue = _colorPickerBox.SelectedHue; - _lastSelectedIndex = _colorPickerBox.SelectedIndex; - - _colorPickerBox.Dispose(); - } - - private void ColorPickerBoxOnMouseUp(object sender, MouseEventArgs e) - { - int column = e.X / _cellW; - int row = e.Y / _cellH; - int selectedIndex = row * _columns + column; - - if (selectedIndex >= 0 && selectedIndex < _colorPickerBox.Hues.Length) - { - ColorSelected?.Invoke(this, new ColorSelectedEventArgs(_layer, _colorPickerBox.Hues, selectedIndex)); - SetCurrentHue(); - } - } - - private void ColorPicker_MouseClick(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtonType.Left) - { - _colorPickerBox?.Dispose(); - _colorPickerBox = null; - - if (_colorPickerBox == null) - { - _colorPickerBox = new ColorPickerBox - ( - 485, - 109, - _rows, - _columns, - _cellW, - _cellH, - _pallet - ) - { - IsModal = true, - LayerOrder = UILayer.Over, - ModalClickOutsideAreaClosesThisControl = true, - ShowLivePreview = false, - SelectedIndex = _lastSelectedIndex - }; - - UIManager.Add(_colorPickerBox); - - _colorPickerBox.ColorSelectedIndex += ColorPickerBoxOnColorSelectedIndex; - _colorPickerBox.MouseUp += ColorPickerBoxOnMouseUp; - } - } - } - - private void ColorPickerBoxOnColorSelectedIndex(object sender, EventArgs e) - { - ColorSelected?.Invoke(this, new ColorSelectedEventArgs(_layer, _colorPickerBox.Hues, _colorPickerBox.SelectedIndex)); - } - } - - /// - /// Partially custom paperdoll gump required, when in-game the fake character created gets automatically removed and breaks the original paperdoll gump. - /// - private class CustomPaperDollGump : PaperDollInteractable - { - private readonly Mobile playerMobile; - private Item hair; - private Item beard; - private bool requestUpdate = false; - - public CustomPaperDollGump(int x, int y, Mobile playerMobile, Item hair, Item beard) : base(x, y, playerMobile, null) - { - this.playerMobile = playerMobile; - this.hair = hair; - this.beard = beard; - } - - private void UpdateUI() - { - if (IsDisposed) - { - return; - } - - Mobile mobile = playerMobile; - - if (mobile == null) - { - Dispose(); - - return; - } - - Clear(); - - #region Add the base gump - the semi-naked paper doll. - ushort body; - ushort hue = mobile.Hue; - - if (mobile.Graphic == 0x0191 || mobile.Graphic == 0x0193) - { - body = 0x000D; - } - else if (mobile.Graphic == 0x025D) - { - body = 0x000E; - } - else if (mobile.Graphic == 0x025E) - { - body = 0x000F; - } - else if (mobile.Graphic == 0x029A || mobile.Graphic == 0x02B6) - { - body = 0x029A; - } - else if (mobile.Graphic == 0x029B || mobile.Graphic == 0x02B7) - { - body = 0x0299; - } - else if (mobile.Graphic == 0x04E5) - { - body = 0xC835; - } - else if (mobile.Graphic == 0x03DB) - { - body = 0x000C; - hue = 0x03EA; - } - else if (mobile.IsFemale) - { - body = 0x000D; - } - else - { - body = 0x000C; - } - - // body - Add - ( - new GumpPic(0, 0, body, hue) - { - IsPartialHue = true - } - ); - - - if (mobile.Graphic == 0x03DB) - { - Add - ( - new GumpPic(0, 0, 0xC72B, mobile.Hue) - { - AcceptMouseInput = true, - IsPartialHue = true - } - ); - } - #endregion - - // equipment - - if (hair != null) - { - ushort id = GetAnimID(mobile.Graphic, hair.ItemData.AnimID, mobile.IsFemale); - - Add - ( - new GumpPicEquipment - ( - hair.Serial, - 0, - 0, - id, - (ushort)(hair.Hue & 0x3FFF), - Layer.Hair - ) - { - AcceptMouseInput = true, - IsPartialHue = hair.ItemData.IsPartialHue, - CanLift = false - } - ); - } - - if (beard != null) - { - ushort id = GetAnimID(mobile.Graphic, beard.ItemData.AnimID, mobile.IsFemale); - - Add - ( - new GumpPicEquipment - ( - beard.Serial, - 0, - 0, - id, - (ushort)(beard.Hue & 0x3FFF), - Layer.Beard - ) - { - AcceptMouseInput = true, - IsPartialHue = beard.ItemData.IsPartialHue, - CanLift = false - } - ); - } - } - - public new void RequestUpdate() - { - requestUpdate = true; - } - - public override void Update() - { - if (requestUpdate) - { - UpdateUI(); - requestUpdate = false; - } - } - } - #endregion - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/RacialAbilitiesBookGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/RacialAbilitiesBookGump.cs deleted file mode 100644 index 12c234b89..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/RacialAbilitiesBookGump.cs +++ /dev/null @@ -1,382 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Network; -using ClassicUO.Resources; -using Microsoft.Xna.Framework; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class RacialAbilitiesBookGump : Gump - { - private static readonly string[] _humanNames = { "Strong Back", "Tough", "Workhorse", "Jack of All Trades" }; - private static readonly string[] _elfNames = - { - "Night Sight", "Infused with Magic", - "Knowledge of Nature", "Difficult to Track", - "Perception", "Wisdom" - }; - private static readonly string[] _gargoyleNames = { "Flying", "Berserk", "Master Artisan", "Deadly Aim", "Mystic Insight" }; - private int _abilityCount = 4; - private int _dictionaryPagesCount = 1; - private GumpPic _pageCornerLeft, _pageCornerRight; - private int _pagesCount = 3; - private int _tooltipOffset = 1112198; - private int _enqueuePage = -1; - - public RacialAbilitiesBookGump(int x, int y) : base(0, 0) - { - X = x; - Y = y; - CanMove = true; - CanCloseWithRightClick = true; - - BuildGump(); - } - - private void BuildGump() - { - Add(new GumpPic(0, 0, 0x2B29, 0)); - - Add(_pageCornerLeft = new GumpPic(50, 8, 0x08BB, 0)); - _pageCornerLeft.LocalSerial = 0; - _pageCornerLeft.Page = int.MaxValue; - _pageCornerLeft.MouseUp += PageCornerOnMouseClick; - _pageCornerLeft.MouseDoubleClick += PageCornerOnMouseDoubleClick; - Add(_pageCornerRight = new GumpPic(321, 8, 0x08BC, 0)); - _pageCornerRight.LocalSerial = 1; - _pageCornerRight.Page = 1; - _pageCornerRight.MouseUp += PageCornerOnMouseClick; - _pageCornerRight.MouseDoubleClick += PageCornerOnMouseDoubleClick; - - int abilityOnPage = 0; - ushort iconStartGraphic = 0; - - GetSummaryBookInfo(ref abilityOnPage, ref iconStartGraphic); - - _pagesCount = _dictionaryPagesCount + (_abilityCount >> 1); - - int offs = 0; - - for (int page = 1, topage = _dictionaryPagesCount - 1; page <= _dictionaryPagesCount; page++) - { - for (int j = 0; j < 2; j++) - { - int indexX = 106; - int dataX = 62; - int y = 0; - - if (j % 2 != 0) - { - indexX = 269; - dataX = 225; - } - - - Label text = new Label(ResGumps.Index, false, 0x0288, font: 6) { X = indexX, Y = 10 }; - Add(text, page); - - for (int i = 0; i < abilityOnPage; i++) - { - if (offs >= _abilityCount) - { - break; - } - - if (offs % 2 == 0) - { - topage++; - } - - bool passive = true; - - text = new HoveredLabel - ( - GetAbilityName(offs, ref passive), - false, - 0x0288, - 0x33, - 0x0288, - font: 9 - ) - { - X = dataX, - Y = 52 + y, - AcceptMouseInput = true, - LocalSerial = (uint) topage - }; - - text.MouseUp += OnClicked; - Add(text, page); - - y += 15; - offs++; - } - } - } - - int page1 = _dictionaryPagesCount - 1; - - for (int i = 0; i < _abilityCount; i++) - { - int iconX = 62; - int iconTextX = 112; - - if (i > 0 && i % 2 != 0) - { - iconX = 225; - iconTextX = 275; - } - else - { - page1++; - } - - - bool passive = true; - string spellName = GetAbilityName(i, ref passive); - - Label text = new Label - ( - spellName, - false, - 0x0288, - 100, - 6 - ) { X = iconTextX, Y = 34 }; - - Add(text, page1); - - if (passive) - { - text = new Label(ResGumps.Passive, false, 0x0288, font: 6) - { - X = iconTextX, - Y = 64 - }; - - Add(text, page1); - } - - ushort graphic = (ushort) (iconStartGraphic + i); - - GumpPic pic = new GumpPic(iconX, 40, graphic, 0) - { - LocalSerial = graphic - }; - - if (!passive) - { - pic.DragBegin += (sender, e) => - { - if (UIManager.DraggingControl != this || UIManager.MouseOverControl != sender) - { - return; - } - - RacialAbilityButton gump = new RacialAbilityButton((ushort) ((GumpPic) sender).LocalSerial) - { - X = Mouse.LClickPosition.X - 20, - Y = Mouse.LClickPosition.Y - 20 - }; - - UIManager.Add(gump); - UIManager.AttemptDragControl(gump, true); - }; - - pic.MouseDoubleClick += (sender, e) => - { - if ((ushort) ((GumpPic) sender).LocalSerial == 0x5DDA && World.Player.Race == RaceType.GARGOYLE) - { - NetClient.Socket.Send_ToggleGargoyleFlying(); - e.Result = true; - } - }; - } - - Add(pic, page1); - pic.SetTooltip(ClilocLoader.Instance.GetString(_tooltipOffset + i), 150); - - Add - ( - new GumpPicTiled - ( - iconX, - 88, - 120, - 4, - 0x0835 - ), - page1 - ); - } - } - - protected override void OnDragBegin(int x, int y) - { - if (UIManager.MouseOverControl?.RootParent == this) - { - UIManager.MouseOverControl.InvokeDragBegin(new Point(x, y)); - } - - base.OnDragBegin(x, y); - } - - protected override void OnDragEnd(int x, int y) - { - if (UIManager.MouseOverControl?.RootParent == this) - { - UIManager.MouseOverControl.InvokeDragEnd(new Point(x, y)); - } - - base.OnDragEnd(x, y); - } - - private void GetSummaryBookInfo(ref int abilityOnPage, ref ushort iconStartGraphic) - { - _dictionaryPagesCount = 2; - abilityOnPage = 3; - - switch (World.Player.Race) - { - case RaceType.HUMAN: - _abilityCount = 4; - iconStartGraphic = 0x5DD0; - _tooltipOffset = 1112198; - - break; - - case RaceType.ELF: - _abilityCount = 6; - iconStartGraphic = 0x5DD4; - _tooltipOffset = 1112202; - - break; - - case RaceType.GARGOYLE: - _abilityCount = 5; - iconStartGraphic = 0x5DDA; - _tooltipOffset = 1112208; - - break; - } - } - - - private string GetAbilityName(int offset, ref bool passive) - { - passive = true; - - switch (World.Player.Race) - { - case RaceType.HUMAN: return _humanNames[offset]; - case RaceType.ELF: return _elfNames[offset]; - - case RaceType.GARGOYLE: - - if (offset == 0) - { - passive = false; - } - - return _gargoyleNames[offset]; - - default: return string.Empty; - } - } - - private void OnClicked(object sender, MouseEventArgs e) - { - if (sender is HoveredLabel l && e.Button == MouseButtonType.Left) - { - _enqueuePage = (int)l.LocalSerial; - } - } - - - private void PageCornerOnMouseClick(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtonType.Left && sender is Control ctrl) - { - SetActivePage(ctrl.LocalSerial == 0 ? ActivePage - 1 : ActivePage + 1); - } - } - - private void PageCornerOnMouseDoubleClick(object sender, MouseDoubleClickEventArgs e) - { - if (e.Button == MouseButtonType.Left && sender is Control ctrl) - { - SetActivePage(ctrl.LocalSerial == 0 ? 1 : _pagesCount); - } - } - - - private void SetActivePage(int page) - { - if (page < 1) - { - page = 1; - } - else if (page > _pagesCount) - { - page = _pagesCount; - } - - ActivePage = page; - _pageCornerLeft.Page = ActivePage != 1 ? 0 : int.MaxValue; - _pageCornerRight.Page = ActivePage != _pagesCount ? 0 : int.MaxValue; - - Client.Game.Audio.PlaySound(0x0055); - } - - public override void Update() - { - base.Update(); - - if (IsDisposed) - { - return; - } - - if (_enqueuePage >= 0 && Time.Ticks - Mouse.LastLeftButtonClickTime >= Mouse.MOUSE_DELAY_DOUBLE_CLICK) - { - SetActivePage(_enqueuePage); - _enqueuePage = -1; - } - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/RacialAbilityButton.cs b/src/ClassicUO.Client/Game/UI/Gumps/RacialAbilityButton.cs deleted file mode 100644 index 0553951b0..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/RacialAbilityButton.cs +++ /dev/null @@ -1,97 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Xml; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Network; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class RacialAbilityButton : Gump - { - public RacialAbilityButton(ushort graphic) : this() - { - LocalSerial = (uint) (7000 + graphic); - - UIManager.GetGump(LocalSerial)?.Dispose(); - - Graphic = graphic; - BuildGump(); - } - - public RacialAbilityButton() : base(0, 0) - { - CanMove = true; - CanCloseWithRightClick = true; - } - - public override GumpType GumpType => GumpType.RacialButton; - public ushort Graphic; - - - private void BuildGump() - { - GumpPic pic = new GumpPic(0, 0, Graphic, 0); - Add(pic); - pic.SetTooltip(ClilocLoader.Instance.GetString(1112198 + (Graphic - 0x5DD0)), 200); - } - - protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button) - { - if (Graphic == 0x5DDA && World.Player.Race == RaceType.GARGOYLE) - { - NetClient.Socket.Send_ToggleGargoyleFlying(); - - return true; - } - - return base.OnMouseDoubleClick(x, y, button); - } - - public override void Save(XmlTextWriter writer) - { - base.Save(writer); - writer.WriteAttributeString("graphic", Graphic.ToString()); - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - Graphic = ushort.Parse(xml.GetAttribute("graphic")); - BuildGump(); - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/ResizableGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/ResizableGump.cs deleted file mode 100644 index 87828fe22..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/ResizableGump.cs +++ /dev/null @@ -1,259 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Renderer; -using Microsoft.Xna.Framework; -using System.Xml; - -namespace ClassicUO.Game.UI.Gumps -{ - public abstract class ResizableGump : AnchorableGump - { - private readonly BorderControl _borderControl; - private readonly Button _button; - private bool _clicked; - private Point _lastSize, _savedSize; - private readonly int _minH; - private readonly int _minW; - protected bool _isLocked = false; - protected bool? _prevCanMove = null, _prevCloseWithRightClick = null, _prevBorder = null; - - public BorderControl BorderControl { get { return _borderControl; } } - - protected ResizableGump - ( - int width, - int height, - int minW, - int minH, - uint local, - uint server, - ushort borderHue = 0 - ) : base(local, server) - { - _borderControl = new BorderControl - ( - 0, - 0, - Width, - Height, - 4 - ) - { - Hue = borderHue - }; - - Add(_borderControl); - _button = new Button(0, 0x837, 0x838, 0x838); - Add(_button); - - _button.MouseDown += (sender, e) => { _clicked = true; }; - - _button.MouseUp += (sender, e) => - { - ResizeWindow(_lastSize); - _clicked = false; - }; - - WantUpdateSize = false; - - Width = _lastSize.X = width; - Height = _lastSize.Y = height; - GroupMatrixHeight = Height; - GroupMatrixWidth = Width; - _savedSize = _lastSize; - - _minW = minW; - _minH = minH; - - OnResize(); - } - - public bool ShowBorder - { - get => _borderControl.IsVisible; - set => _borderControl.IsVisible = _button.IsVisible = value; - } - - - public Point ResizeWindow(Point newSize) - { - if (newSize.X < _minW) - { - newSize.X = _minW; - } - - if (newSize.Y < _minH) - { - newSize.Y = _minH; - } - - //Resize(); - _savedSize = newSize; - - return newSize; - } - - - public override void Update() - { - if (IsDisposed) - { - return; - } - - Point offset = Mouse.LDragOffset; - - _lastSize = _savedSize; - - if (_clicked && offset != Point.Zero) - { - int w = _lastSize.X + offset.X; - int h = _lastSize.Y + offset.Y; - - if (w < _minW) - { - w = _minW; - } - - if (h < _minH) - { - h = _minH; - } - - _lastSize.X = w; - _lastSize.Y = h; - GroupMatrixHeight = Height; - GroupMatrixWidth = Width; - } - - if (Width != _lastSize.X || Height != _lastSize.Y) - { - Width = _lastSize.X; - Height = _lastSize.Y; - OnResize(); - } - - base.Update(); - } - - - public virtual void OnResize() - { - _borderControl.Width = Width; - _borderControl.Height = Height; - _button.X = Width - (_button.Width >> 0) + 2; - _button.Y = Height - (_button.Height >> 0) + 2; - GroupMatrixHeight = Height; - GroupMatrixWidth = Width; - } - - public override void Restore(XmlElement xml) - { - base.Restore(xml); - - SetLockStatus(IsLocked); - } - - protected virtual void SetLockStatus(bool locked) - { - _prevCanMove ??= CanMove; - _prevCloseWithRightClick ??= CanCloseWithRightClick; - _prevBorder ??= ShowBorder; - - _isLocked = locked; - IsLocked = locked; - if (_isLocked) - { - CanMove = false; - CanCloseWithRightClick = false; - ShowBorder = false; - } - else - { - CanMove = _prevCanMove ?? true; - CanCloseWithRightClick = _prevCloseWithRightClick ?? true; - ShowBorder = _prevBorder ?? true; - } - } - - protected override void OnMouseUp(int x, int y, MouseButtonType button) - { - base.OnMouseUp(x, y, button); - - if (button == MouseButtonType.Left && Keyboard.Alt && UIManager.MouseOverControl != null && (UIManager.MouseOverControl == this || UIManager.MouseOverControl.RootParent == this)) - { - ref readonly var texture = ref Client.Game.Gumps.GetGump(0x82C); - if (texture.Texture != null) - { - if (x >= 0 && x <= texture.UV.Width && y >= 0 && y <= texture.UV.Height) - { - SetLockStatus(!_isLocked); - } - } - } - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - - if (Keyboard.Alt && UIManager.MouseOverControl != null && (UIManager.MouseOverControl == this || UIManager.MouseOverControl.RootParent == this)) - { - Vector3 hueVector = ShaderHueTranslator.GetHueVector(0); - - ref readonly var texture = ref Client.Game.Gumps.GetGump(0x82C); - - if (texture.Texture != null) - { - if (_isLocked) - { - hueVector.X = 34; - hueVector.Y = 1; - } - batcher.Draw - ( - texture.Texture, - new Vector2(x, y), - texture.UV, - hueVector - ); - } - } - - return true; - } - } -} \ No newline at end of file diff --git a/src/ClassicUO.Client/Game/UI/Gumps/ResizableJournal.cs b/src/ClassicUO.Client/Game/UI/Gumps/ResizableJournal.cs deleted file mode 100644 index 92f26c5e9..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/ResizableJournal.cs +++ /dev/null @@ -1,734 +0,0 @@ -using ClassicUO.Configuration; -using ClassicUO.Game.Data; -using ClassicUO.Game.Managers; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Renderer; -using ClassicUO.Utility.Collections; -using System; -using System.Collections.Generic; -using Microsoft.Xna.Framework; -using ClassicUO.Game.GameObjects; -using System.Linq; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class ResizableJournal : ResizableGump - { - #region VARS - public static bool ReloadTabs { get; set; } = false; - - private static int BORDER_WIDTH = 4; - private static int MIN_WIDTH = (BORDER_WIDTH * 2) + (TAB_WIDTH * 4); - private const int MIN_HEIGHT = 100; - private const int SCROLL_BAR_WIDTH = 14; - #region TABS - private const int TAB_WIDTH = 80; - private const int TAB_HEIGHT = 30; - #endregion - #endregion - - #region CONTROLS - - #region TABS - private List _tab = new List(); - private List _tabName = new List(); - private List _tabTypes = new List(); - private MessageType[] _currentFilter; - #endregion - - private AlphaBlendControl _background; - private JournalEntriesContainer _journalArea; - private ScrollBar _scrollBarBase; - private NiceButton _newTabButton; - #endregion - - #region OTHER - private static int _lastX = 100, _lastY = 100; - private static int _lastWidth = MIN_WIDTH, _lastHeight = 300; - private readonly GumpPicTiled _backgroundTexture; - #endregion - public ResizableJournal() : base(_lastWidth, _lastHeight, MIN_WIDTH, MIN_HEIGHT, 0, 0) - { - AnchorType = ANCHOR_TYPE.NONE; - CanMove = true; - _prevCanMove = true; - AcceptMouseInput = true; - WantUpdateSize = true; - CanCloseWithRightClick = true; - _prevCloseWithRightClick = true; - if (ProfileManager.CurrentProfile != null) - { - _lastX = ProfileManager.CurrentProfile.JournalPosition.X; - _lastY = ProfileManager.CurrentProfile.JournalPosition.Y; - IsLocked = ProfileManager.CurrentProfile.JournalLocked; - } - X = _lastX; - Y = _lastY; - - - #region Background - _background = new AlphaBlendControl((float)ProfileManager.CurrentProfile.JournalOpacity / 100); - _background.Hue = ProfileManager.CurrentProfile.AltJournalBackgroundHue; - _background.Width = Width - (BORDER_WIDTH * 2); - _background.Height = Height - (BORDER_WIDTH * 2); - _background.X = BORDER_WIDTH; - _background.Y = BORDER_WIDTH; - _background.CanCloseWithRightClick = true; - _background.DragBegin += (sender, e) => - { - InvokeDragBegin(e.Location); - }; - - _backgroundTexture = new GumpPicTiled(0); - #endregion - - #region Journal Area - _scrollBarBase = new ScrollBar( - Width - SCROLL_BAR_WIDTH - BORDER_WIDTH, - BORDER_WIDTH + TAB_HEIGHT, - Height - TAB_HEIGHT - (BORDER_WIDTH * 2)); - - _journalArea = new JournalEntriesContainer( - BORDER_WIDTH, - BORDER_WIDTH + TAB_HEIGHT, - Width - SCROLL_BAR_WIDTH - (BORDER_WIDTH * 2), - Height - (BORDER_WIDTH * 2) - TAB_HEIGHT, - _scrollBarBase, - this); - _journalArea.CanCloseWithRightClick = true; - _journalArea.DragBegin += (sender, e) => { InvokeDragBegin(e.Location); }; - #endregion - - Add(_background); - Add(_backgroundTexture); - Add(_scrollBarBase); - - Add(_journalArea); - - Add(_newTabButton = new NiceButton(0, 0, 20, TAB_HEIGHT, ButtonAction.Activate, "+") { IsSelectable = false }); - _newTabButton.SetTooltip("Add a new tab"); - _newTabButton.MouseUp += (s, e) => - { - if (e.Button == MouseButtonType.Left) - { - UIManager.Add(new InputRequest("Enter a tab name", "Save", "Cancel", (r, entry) => - { - if (r == InputRequest.Result.BUTTON1 && !string.IsNullOrEmpty(entry)) - { - ProfileManager.CurrentProfile.JournalTabs.Add(entry, new MessageType[] { MessageType.Regular }); - ResizableJournal.ReloadTabs = true; - } - }) - { X = X, Y = Y }); - } - }; - - BuildTabs(); - - InitJournalEntries(); - ResizeWindow(ProfileManager.CurrentProfile.ResizeJournalSize); - BuildBorder(); - EventSink.JournalEntryAdded += EventSink_EntryAdded; ; - } - - private void EventSink_EntryAdded(object sender, JournalEntry e) - { - AddJournalEntry(e); - } - - public override GumpType GumpType => GumpType.Journal; - - public enum BorderStyle - { - Default, - Style1, - Style2, - Style3, - Style4, - Style5, - Style6, - Style7, - Style8, - //Style9 - } - - private void BuildTabs() - { - foreach (var tab in _tab) - { - tab.Dispose(); - } - - _tab.Clear(); - _tabName.Clear(); - _tabTypes.Clear(); - - foreach (var tab in ProfileManager.CurrentProfile.JournalTabs) - { - AddTab(tab.Key, tab.Value); - } - if (ProfileManager.CurrentProfile.LastJournalTab < _tab.Count) - { - _tab[ProfileManager.CurrentProfile.LastJournalTab].IsSelected = true; - OnButtonClick(ProfileManager.CurrentProfile.LastJournalTab); //Simulate selecting a tab - } - - for (int i = 0; i < _tab.Count; i++) - Add(_tab[i]); - - _newTabButton.X = (_tab.Count * TAB_WIDTH) + 4; - } - - public void BuildBorder() - { - int graphic = 0, borderSize = 0; - switch ((BorderStyle)ProfileManager.CurrentProfile.JournalStyle) - { - case BorderStyle.Style1: - graphic = 3500; borderSize = 26; - break; - case BorderStyle.Style2: - graphic = 5054; borderSize = 12; - break; - case BorderStyle.Style3: - graphic = 5120; borderSize = 10; - break; - case BorderStyle.Style4: - graphic = 9200; borderSize = 7; - break; - case BorderStyle.Style5: - graphic = 9270; borderSize = 10; - break; - case BorderStyle.Style6: - graphic = 9300; borderSize = 4; - break; - case BorderStyle.Style7: - graphic = 9260; borderSize = 17; - break; - case BorderStyle.Style8: - { - if (Client.Game.Gumps.GetGump(40303).Texture != null) - graphic = 40303; - else - graphic = 83; - borderSize = 16; - break; - } - //case BorderStyle.Style9: - // { - // if (Assets.GumpsLoader.Instance.GetGumpTexture(40313, out var bounds) != null) - // { - // graphic = 40313; - // borderSize = 75; - // } - // else - // { - // graphic = 83; - // borderSize = 16; - // } - // break; - // } - - default: - case BorderStyle.Default: - BorderControl.DefaultGraphics(); - _backgroundTexture.IsVisible = false; - _background.IsVisible = true; - BORDER_WIDTH = 4; - break; - } - - if ((BorderStyle)ProfileManager.CurrentProfile.JournalStyle != BorderStyle.Default) - { - BorderControl.T_Left = (ushort)graphic; - BorderControl.H_Border = (ushort)(graphic + 1); - BorderControl.T_Right = (ushort)(graphic + 2); - BorderControl.V_Border = (ushort)(graphic + 3); - - _backgroundTexture.Graphic = (ushort)(graphic + 4); - _backgroundTexture.IsVisible = true; - _backgroundTexture.Hue = _background.Hue; - BorderControl.Hue = _background.Hue; - BorderControl.Alpha = (float)ProfileManager.CurrentProfile.JournalOpacity / 100; - _background.IsVisible = false; - - BorderControl.V_Right_Border = (ushort)(graphic + 5); - BorderControl.B_Left = (ushort)(graphic + 6); - BorderControl.H_Bottom_Border = (ushort)(graphic + 7); - BorderControl.B_Right = (ushort)(graphic + 8); - BorderControl.BorderSize = borderSize; - BORDER_WIDTH = borderSize; - } - Reposition(); - - if (ProfileManager.CurrentProfile.HideJournalBorder) - BorderControl.IsVisible = false; - else - BorderControl.IsVisible = true; - } - - private void Reposition() - { - if (IsDisposed) - return; - _background.X = BORDER_WIDTH; - _background.Y = BORDER_WIDTH; - _background.Width = Width - (BORDER_WIDTH * 2); - _background.Height = Height - (BORDER_WIDTH * 2); - - _backgroundTexture.X = _background.X; - _backgroundTexture.Y = _background.Y; - _backgroundTexture.Width = _background.Width; - _backgroundTexture.Height = _background.Height; - _backgroundTexture.Alpha = (float)ProfileManager.CurrentProfile.JournalOpacity / 100; - BorderControl.Alpha = (float)ProfileManager.CurrentProfile.JournalOpacity / 100; - - _journalArea.X = BORDER_WIDTH; - _journalArea.Y = TAB_HEIGHT; - _journalArea.Width = Width - SCROLL_BAR_WIDTH - (BORDER_WIDTH * 2); - _journalArea.Height = Height - BORDER_WIDTH - TAB_HEIGHT; - - _lastWidth = Width; - _lastHeight = Height; - - _scrollBarBase.X = Width - SCROLL_BAR_WIDTH - BORDER_WIDTH; - _scrollBarBase.Y = _journalArea.Y; - _scrollBarBase.Height = Height - BORDER_WIDTH - TAB_HEIGHT; - ProfileManager.CurrentProfile.ResizeJournalSize = new Point(Width, Height); - } - - public void UpdateOptions() - { - _backgroundTexture.Alpha = (float)ProfileManager.CurrentProfile.JournalOpacity / 100; - BorderControl.Alpha = (float)ProfileManager.CurrentProfile.JournalOpacity / 100; - _background.Hue = ProfileManager.CurrentProfile.AltJournalBackgroundHue; - - BuildBorder(); - } - - public static void UpdateJournalOptions() - { - foreach(ResizableJournal j in UIManager.Gumps.OfType()) - { - j.UpdateOptions(); - } - } - - protected override void OnMouseWheel(MouseEventType delta) - { - base.OnMouseWheel(delta); - if (_scrollBarBase != null) - _scrollBarBase.InvokeMouseWheel(delta); - } - - public override void OnButtonClick(int buttonID) - { - if (_tab.Count > buttonID) - { - _tab[buttonID].IsSelected = true; - _currentFilter = _tabTypes[buttonID]; - _journalArea.CalculateScrollBarMaxValue(); - _journalArea.Update(); - _scrollBarBase.Value = _scrollBarBase.MaxValue; - ProfileManager.CurrentProfile.LastJournalTab = buttonID; - } - } - - private void AddTab(string Name, MessageType[] filters) - { - NiceButton nb; - _tab.Add(nb = new NiceButton((_tab.Count * TAB_WIDTH) + 4, 0, TAB_WIDTH, TAB_HEIGHT, ButtonAction.Activate, Name, 1) - { - ButtonParameter = _tab.Count, - IsSelectable = true, - CanCloseWithRightClick = false, - ContextMenu = new TabContextEntry(Name) - }); - - nb.MouseUp += (sender, e) => - { - if (e.Button == MouseButtonType.Right) - { - nb.ContextMenu.Show(); - } - }; - _tabName.Add(Name); - _tabTypes.Add(filters); - } - - private void AddJournalEntry(JournalEntry journalEntry) - { - if (journalEntry == null) - return; - _journalArea.AddEntry($"{journalEntry.Name}: {journalEntry.Text}", journalEntry.Hue, journalEntry.Time, journalEntry.TextType, journalEntry.MessageType); - } - - private void InitJournalEntries() - { - foreach (JournalEntry entry in JournalManager.Entries) - { - if (entry == null) - continue; - AddJournalEntry(entry); - } - } - - protected override void UpdateContents() - { - base.UpdateContents(); - _background.Alpha = (float)ProfileManager.CurrentProfile.JournalOpacity / 100; - } - - public override void Update() - { - base.Update(); - - if (X != _lastX || Y != _lastY) - { - _lastX = X; - _lastY = Y; - ProfileManager.CurrentProfile.JournalPosition = Location; - } - if (((Width != _lastWidth || Height != _lastHeight) && !Mouse.LButtonPressed)) - Reposition(); - - if (ReloadTabs) - { - ReloadTabs = false; - - BuildTabs(); - } - } - - public override void Dispose() - { - EventSink.JournalEntryAdded -= EventSink_EntryAdded; - base.Dispose(); - } - - private class JournalEntriesContainer : Control - { - private Deque journalDatas = new Deque(); - - - private readonly ScrollBarBase _scrollBar; - private int lastWidth = 0, lastHeight = 0; - private ResizableJournal _resizableJournal; - - public JournalEntriesContainer(int x, int y, int width, int height, ScrollBarBase scrollBarControl, ResizableJournal resizableJournal) - { - _resizableJournal = resizableJournal; - _scrollBar = scrollBarControl; - _scrollBar.IsVisible = false; - AcceptMouseInput = true; - CanMove = true; - - X = x; - Y = y; - Width = lastWidth = width; - Height = lastHeight = height; - - WantUpdateSize = false; - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - base.Draw(batcher, x, y); - int my = y; - bool hideTimestamp = ProfileManager.CurrentProfile.HideJournalTimestamp; - - if (batcher.ClipBegin(x, y, Width, Height)) - { - foreach (JournalData journalEntry in journalDatas) - { - if (journalEntry == null || string.IsNullOrEmpty(journalEntry.EntryText.Text)) - continue; - - if (!CanBeDrawn(journalEntry.TextType, journalEntry.MessageType)) - continue; - - if (my + journalEntry.EntryText.Height - y >= _scrollBar.Value && my - y <= _scrollBar.Value + _scrollBar.Height) - { - if (!hideTimestamp) - journalEntry.TimeStamp.Draw(batcher, x, my - _scrollBar.Value); - journalEntry.EntryText.Draw(batcher, hideTimestamp ? x : x + (journalEntry.TimeStamp.Width + 5), my - _scrollBar.Value); - } - my += journalEntry.EntryText.Height; - } - - batcher.ClipEnd(); - } - return true; - } - - public override void Update() - { - base.Update(); - - if (!IsVisible) - return; - - _scrollBar.IsVisible = _scrollBar.MaxValue > _scrollBar.MinValue; - if (Width != lastWidth || Height != lastHeight) - { - lastWidth = Width; - lastHeight = Height; - - foreach (JournalData _ in journalDatas) - { - _.EntryText.Width = Width - BORDER_WIDTH - (ProfileManager.CurrentProfile.HideJournalTimestamp ? 0 : _.TimeStamp.Width); - _.EntryText.Update(); - } - - CalculateScrollBarMaxValue(); - } - - } - - public void CalculateScrollBarMaxValue() - { - bool maxValue = _scrollBar.Value == _scrollBar.MaxValue; - int height = 0; - - foreach (JournalData _ in journalDatas) - { - if (_ != null) - if (CanBeDrawn(_.TextType, _.MessageType)) - height += _.EntryText.Height; - } - - - height -= _scrollBar.Height; - - if (height > 0) - { - _scrollBar.MaxValue = height; - - if (maxValue) - { - _scrollBar.Value = _scrollBar.MaxValue; - } - } - else - { - _scrollBar.MaxValue = 0; - _scrollBar.Value = 0; - } - } - - public void AddEntry(string text, ushort hue, DateTime time, TextType text_type, MessageType messageType) - { - bool maxScroll = _scrollBar.Value == _scrollBar.MaxValue; - - while (journalDatas.Count > (ProfileManager.CurrentProfile == null ? 200 : ProfileManager.CurrentProfile.MaxJournalEntries)) - journalDatas.RemoveFromFront().Destroy(); - - TextBox timeS = new TextBox($"{time:t}", ProfileManager.CurrentProfile.SelectedTTFJournalFont, ProfileManager.CurrentProfile.SelectedJournalFontSize - 2, null, 1150, strokeEffect: false); - - journalDatas.AddToBack( - new JournalData( - new TextBox(text, ProfileManager.CurrentProfile.SelectedTTFJournalFont, ProfileManager.CurrentProfile.SelectedJournalFontSize, Width - (ProfileManager.CurrentProfile.HideJournalTimestamp ? 0 : timeS.Width), hue, strokeEffect: false), - timeS, - text_type, - messageType - )); - - if (maxScroll) - { - _scrollBar.Value = _scrollBar.MaxValue; - } - CalculateScrollBarMaxValue(); - } - - private bool CanBeDrawn(TextType type, MessageType messageType) - { - if (_resizableJournal._currentFilter != null) - { - for (int i = 0; i < _resizableJournal._currentFilter.Length; i++) - { - MessageType currentfilter = _resizableJournal._currentFilter[i]; - - if (messageType == MessageType.ChatSystem && currentfilter == MessageType.ChatSystem) - return true; - - if (type == TextType.SYSTEM && currentfilter == MessageType.System) - return true; - - if (type == TextType.SYSTEM && currentfilter != MessageType.System) - continue; - - if (currentfilter == messageType) - return true; - } - return false; - } - - return true; - } - - private void Reset() - { - foreach (JournalData _ in journalDatas) - _.Destroy(); - - journalDatas.Clear(); - } - - public override void Dispose() - { - Reset(); - - base.Dispose(); - } - - public class JournalData - { - public JournalData(TextBox textBox, TextBox timeStamp, TextType textType, MessageType messageType) - { - EntryText = textBox; - TimeStamp = timeStamp; - TextType = textType; - MessageType = messageType; - } - - public void Destroy() - { - EntryText?.Dispose(); - TimeStamp?.Dispose(); - } - - public TextBox EntryText { get; } - public TextBox TimeStamp { get; } - public TextType TextType { get; } - public MessageType MessageType { get; } - } - } - - private class TabContextEntry : ContextMenuControl - { - public TabContextEntry(string name) - { - if (ProfileManager.CurrentProfile.JournalTabs.ContainsKey(name)) - { - MessageType[] selectedTypes = ProfileManager.CurrentProfile.JournalTabs[name]; - - foreach (MessageType item in Enum.GetValues(typeof(MessageType))) - { - string entryName = string.Empty; - switch (item) - { - case MessageType.Regular: - entryName = "Regular"; - break; - case MessageType.System: - entryName = "System"; - break; - case MessageType.Emote: - entryName = "Emote"; - break; - case MessageType.Limit3Spell: - entryName = "Limit3Spell(Sphere)"; - break; - case MessageType.Label: - entryName = "Label"; - break; - case MessageType.Focus: - entryName = "Focus"; - break; - case MessageType.Whisper: - entryName = "Whisper"; - break; - case MessageType.Yell: - entryName = "Yell"; - break; - case MessageType.Spell: - entryName = "Spell"; - break; - case MessageType.Guild: - entryName = "Guild"; - break; - case MessageType.Alliance: - entryName = "Alliance"; - break; - case MessageType.Command: - entryName = "Command"; - break; - case MessageType.Encoded: - entryName = "Encoded"; - break; - case MessageType.ChatSystem: - entryName = "Global Chat"; - break; - case MessageType.Party: - entryName = "Party"; - break; - } - - Add(entryName, - () => - { - if (ProfileManager.CurrentProfile.JournalTabs.ContainsKey(name)) - { - MessageType[] selectedTypes = ProfileManager.CurrentProfile.JournalTabs[name]; - - if (selectedTypes.Contains(item)) - { - ProfileManager.CurrentProfile.JournalTabs[name] = RemoveType(selectedTypes, item); - ResizableJournal.ReloadTabs = true; - } - else - { - ProfileManager.CurrentProfile.JournalTabs[name] = AddType(selectedTypes, item); - ResizableJournal.ReloadTabs = true; - } - } - }, - true, - selectedTypes.Contains(item)); - } - } - - Add("X Delete Tab", () => - { - UIManager.Add(new QuestionGump($"Delete [{name}] tab?", (yes) => - { - if (yes) - { - if (ProfileManager.CurrentProfile.JournalTabs.ContainsKey(name)) - { - ProfileManager.CurrentProfile.JournalTabs.Remove(name); - ResizableJournal.ReloadTabs = true; - } - } - })); - }); - } - - private static MessageType[] RemoveType(MessageType[] array, MessageType removeMe) - { - var modifiedList = new List(); - foreach (var item in array) - { - if (item != removeMe) - { - modifiedList.Add(item); - } - } - - return modifiedList.ToArray(); - } - - private static MessageType[] AddType(MessageType[] array, MessageType addMe) - { - var modifiedList = new List(); - - modifiedList.AddRange(array); - - modifiedList.Add(addMe); - - return modifiedList.ToArray(); - } - } - } -} diff --git a/src/ClassicUO.Client/Game/UI/Gumps/ShopGump.cs b/src/ClassicUO.Client/Game/UI/Gumps/ShopGump.cs deleted file mode 100644 index b341d72cc..000000000 --- a/src/ClassicUO.Client/Game/UI/Gumps/ShopGump.cs +++ /dev/null @@ -1,1213 +0,0 @@ -#region license - -// Copyright (c) 2021, andreakarasho -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by andreakarasho - https://github.com/andreakarasho -// 4. Neither the name of the copyright holder nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Linq; -using ClassicUO.Configuration; -using ClassicUO.Game.GameObjects; -using ClassicUO.Game.UI.Controls; -using ClassicUO.Input; -using ClassicUO.Assets; -using ClassicUO.Network; -using ClassicUO.Renderer; -using ClassicUO.Resources; -using ClassicUO.Utility; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -namespace ClassicUO.Game.UI.Gumps -{ - internal class ShopGump : Gump - { - enum ButtonScroll - { - None = -1, - LeftScrollUp, - LeftScrollDown, - RightScrollUp, - RightScrollDown - } - - // Scroll Delay (in ms) - private const int SCROLL_DELAY = 60; - private uint _lastMouseEventTime = Time.Ticks; - - private ButtonScroll _buttonScroll = ButtonScroll.None; - private readonly Dictionary _shopItems; - private readonly ScrollArea _shopScrollArea, - _transactionScrollArea; - private readonly Label _totalLabel, - _playerGoldLabel; - private readonly DataBox _transactionDataBox; - private readonly Dictionary _transactionItems; - private bool _updateTotal; - private bool _isPressing = false; - private GumpPicTexture _leftMiddle; - private int _initialHeight = 0; - private int _initialHeightRight = 0; - private int _minHeight = 0; - private int _minHeightRight = 0; - private GumpPicTexture _rightMiddle; - private GumpPicTexture _leftBottom; - private Button _expander; - private GumpPicTexture _rightBottom; - private HitBox _accept, - _clear, - _leftDown, - _rightDown; - - private const int LEFT_TOP_HEIGHT = 64; - private const int LEFT_BOTTOM_HEIGHT = 116; - - private const int RIGHT_OFFSET = 32; - private const int RIGHT_BOTTOM_HEIGHT = 93; - - public ShopGump(uint serial, bool isBuyGump, int x, int y) : base(serial, 0) //60 is the base height, original size - { - int height = ProfileManager.CurrentProfile.VendorGumpHeight; - - X = x; - Y = y; - AcceptMouseInput = false; - AcceptKeyboardInput = true; - CanMove = true; - CanCloseWithRightClick = true; - IsBuyGump = isBuyGump; - - _transactionItems = new Dictionary(); - _shopItems = new Dictionary(); - _updateTotal = false; - - WantUpdateSize = true; - - const ushort BUY_GRAPHIC_LEFT = 0x0870; - const ushort BUY_GRAPHIC_RIGHT = 0x0871; - const ushort SELL_GRAPHIC_LEFT = 0x0872; - const ushort SELL_GRAPHIC_RIGHT = 0x0873; - - ushort graphicLeft = isBuyGump ? BUY_GRAPHIC_LEFT : SELL_GRAPHIC_LEFT; - ushort graphicRight = isBuyGump ? BUY_GRAPHIC_RIGHT : SELL_GRAPHIC_RIGHT; - - ref readonly var artInfoLeft = ref Client.Game.Gumps.GetGump(graphicLeft); - ref readonly var artInfoRight = ref Client.Game.Gumps.GetGump(graphicRight); - - Rectangle offset = new Rectangle(0, 0, artInfoLeft.UV.Width, LEFT_TOP_HEIGHT); - GumpPicTexture leftTop = new GumpPicTexture(graphicLeft, 0, 0, offset, false); - Add(leftTop); - - offset.Y += LEFT_TOP_HEIGHT; - offset.Height = artInfoLeft.UV.Height - (LEFT_BOTTOM_HEIGHT + LEFT_TOP_HEIGHT); - _leftMiddle = new GumpPicTexture(graphicLeft, 0, LEFT_TOP_HEIGHT, offset, true); - int diff = height - _leftMiddle.Height; - _leftMiddle.Height = height; - Add(_leftMiddle); - - offset.Y += offset.Height; - offset.Height = LEFT_BOTTOM_HEIGHT; - _leftBottom = new GumpPicTexture( - graphicLeft, - 0, - _leftMiddle.Y + _leftMiddle.Height, - offset, - false - ); - Add(_leftBottom); - - int rightX = artInfoLeft.UV.Width - RIGHT_OFFSET; - int rightY = artInfoLeft.UV.Height / 2 - RIGHT_OFFSET; - offset = new Rectangle(0, 0, artInfoRight.UV.Width, LEFT_TOP_HEIGHT); - GumpPicTexture rightTop = new GumpPicTexture( - graphicRight, - rightX, - rightY, - offset, - false - ); - Add(rightTop); - - offset.Y += LEFT_TOP_HEIGHT; - offset.Height = artInfoRight.UV.Height - (RIGHT_BOTTOM_HEIGHT + LEFT_TOP_HEIGHT); - _rightMiddle = new GumpPicTexture( - graphicRight, - rightX, - rightY + LEFT_TOP_HEIGHT, - offset, - true - ); - _rightMiddle.Height += diff; - Add(_rightMiddle); - - offset.Y += offset.Height; - offset.Height = RIGHT_BOTTOM_HEIGHT; - _rightBottom = new GumpPicTexture( - graphicRight, - rightX, - _rightMiddle.Y + _rightMiddle.Height, - offset, - false - ); - Add(_rightBottom); - - _shopScrollArea = new ScrollArea( - RIGHT_OFFSET, - _leftMiddle.Y, - artInfoLeft.UV.Width - RIGHT_OFFSET * 2 + 5, - _leftMiddle.Height + 50, - false, - _leftMiddle.Height - ); - - Add(_shopScrollArea); - - _transactionScrollArea = new ScrollArea( - RIGHT_OFFSET / 2 + rightTop.X, - LEFT_TOP_HEIGHT + rightTop.Y, - artInfoRight.UV.Width - RIGHT_OFFSET * 2 + RIGHT_OFFSET / 2 + 5, - _rightMiddle.Height, - false - ); - - Add(_transactionScrollArea); - - _transactionDataBox = new DataBox(0, 0, 1, 1); - _transactionDataBox.WantUpdateSize = true; - _transactionScrollArea.Add(_transactionDataBox); - - _totalLabel = new Label("0", true, 0x0386, 0, 1) - { - X = RIGHT_OFFSET + rightTop.X + 32 + 4, - Y = _rightBottom.Y + _rightBottom.Height - 32 * 3 + 15, - }; - - Add(_totalLabel); - - if (isBuyGump) - { - _playerGoldLabel = new Label(World.Player.Gold.ToString(), true, 0x0386, 0, 1) - { - X = _totalLabel.X + 120, - Y = _totalLabel.Y - }; - - Add(_playerGoldLabel); - } - else - { - _totalLabel.X = (rightTop.X + rightTop.Width) - RIGHT_OFFSET * 3; - } - - _expander = new Button(2, 0x082E, 0x82F) - { - ButtonAction = ButtonAction.Activate, - X = artInfoLeft.UV.Width / 2 - 10, - Y = _leftBottom.Y + _leftBottom.Height - 5 - }; - - Add(_expander); - - const float ALPHA_HIT_BUTTON = 0f; - - _accept = new HitBox( - RIGHT_OFFSET + rightTop.X, - (_rightBottom.Y + _rightBottom.Height) - 50, - 34, - 30, - "Accept", - ALPHA_HIT_BUTTON - ); - _clear = new HitBox(_accept.X + 175, _accept.Y, 20, 20, "Clear", ALPHA_HIT_BUTTON); - _accept.MouseUp += (sender, e) => - { - OnButtonClick((int)Buttons.Accept); - }; - _clear.MouseUp += (sender, e) => - { - OnButtonClick((int)Buttons.Clear); - }; - Add(_accept); - Add(_clear); - - HitBox leftUp = new HitBox( - (leftTop.X + leftTop.Width) - 50, - (leftTop.Y + leftTop.Height) - 18, - 18, - 16, - "Scroll Up", - ALPHA_HIT_BUTTON - ); - _leftDown = new HitBox( - leftUp.X, - _leftBottom.Y, - 18, - 16, - "Scroll Down", - ALPHA_HIT_BUTTON - ); - - HitBox rightUp = new HitBox( - (rightTop.X + rightTop.Width - 50), - (rightTop.Y + rightTop.Height) - 18, - 18, - 16, - "Scroll Up", - ALPHA_HIT_BUTTON - ); - _rightDown = new HitBox( - rightUp.X, - _rightBottom.Y, - 18, - 16, - "Scroll Down", - ALPHA_HIT_BUTTON - ); - - leftUp.MouseUp += ButtonMouseUp; - _leftDown.MouseUp += ButtonMouseUp; - rightUp.MouseUp += ButtonMouseUp; - _rightDown.MouseUp += ButtonMouseUp; - leftUp.MouseDown += (sender, e) => - { - _buttonScroll = ButtonScroll.LeftScrollUp; - }; - _leftDown.MouseDown += (sender, e) => - { - _buttonScroll = ButtonScroll.LeftScrollDown; - }; - rightUp.MouseDown += (sender, e) => - { - _buttonScroll = ButtonScroll.RightScrollUp; - }; - _rightDown.MouseDown += (sender, e) => - { - _buttonScroll = ButtonScroll.RightScrollDown; - }; - Add(leftUp); - Add(_leftDown); - Add(rightUp); - Add(_rightDown); - - _minHeight = artInfoLeft.UV.Height - (LEFT_BOTTOM_HEIGHT + LEFT_TOP_HEIGHT); - _minHeightRight = artInfoRight.UV.Height - (RIGHT_BOTTOM_HEIGHT + LEFT_TOP_HEIGHT); - - _expander.MouseDown += (sender, args) => - { - _isPressing = true; - _initialHeight = _leftMiddle.Height; - _initialHeightRight = _rightMiddle.Height; - }; - - _expander.MouseUp += (sender, args) => - { - _isPressing = false; - }; - - //Label name = new Label(World.Player.Name, false, 0x0386, font: 5) - //{ - // X = 322, - // Y = 308 + _middleGumpRight.Height - //}; - - //Add(name); - } - - public bool IsBuyGump { get; } - - //public void SetIfNameIsFromCliloc(Item it, bool fromcliloc) - //{ - // if (_shopItems.TryGetValue(it, out var shopItem)) - // { - // shopItem.NameFromCliloc = fromcliloc; - - // if (fromcliloc) - // { - // shopItem.SetName(ClilocLoader.Instance.Translate(it.Name, $"\t{it.Amount}\t{it.ItemData.Name}", true)); - // } - // } - //} - - private void ButtonMouseUp(object sender, MouseEventArgs e) - { - _buttonScroll = ButtonScroll.None; - } - - public void AddItem( - uint serial, - ushort graphic, - ushort hue, - ushort amount, - uint price, - string name, - bool fromcliloc - ) - { - int count = _shopScrollArea.Children.Count - 1; - - int y = count > 0 ? _shopScrollArea.Children[count].Bounds.Bottom : 0; - - ShopItem shopItem = new ShopItem(serial, graphic, hue, amount, price, name) - { - X = 5, - Y = y + 2, - NameFromCliloc = fromcliloc, - InBuyGump = IsBuyGump - }; - - _shopScrollArea.Add(shopItem); - - shopItem.MouseUp += ShopItem_MouseClick; - shopItem.MouseDoubleClick += ShopItem_MouseDoubleClick; - _shopItems.Add(serial, shopItem); - } - - public void SetNameTo(Item item, string name) - { - if (!string.IsNullOrEmpty(name) && _shopItems.TryGetValue(item, out ShopItem shopItem)) - { - shopItem.SetName(name, false); - } - } - - public override void Update() - { - if (!World.InGame || IsDisposed) - { - return; - } - - int steps = Mouse.LDragOffset.Y; - - if (_isPressing && steps != 0) - { - _leftMiddle.Height = _initialHeight + steps; - - if (_leftMiddle.Height < _minHeight) - { - _leftMiddle.Height = _minHeight; - } - else if (_leftMiddle.Height > 640) - { - _leftMiddle.Height = 640; - } - - _rightMiddle.Height = _initialHeightRight + steps; - - if (_rightMiddle.Height < _minHeightRight) - { - _rightMiddle.Height = _minHeightRight; - } - else if (_rightMiddle.Height > 640 - LEFT_TOP_HEIGHT) - { - _rightMiddle.Height = 640 - LEFT_TOP_HEIGHT; - } - - ProfileManager.CurrentProfile.VendorGumpHeight = _leftMiddle.Height; - - _leftBottom.Y = _leftMiddle.Y + _leftMiddle.Height; - _expander.Y = _leftBottom.Y + _leftBottom.Height - 5; - _rightBottom.Y = _rightMiddle.Y + _rightMiddle.Height; - - _shopScrollArea.Height = _leftMiddle.Height + 50; - _shopScrollArea.ScrollMaxHeight = _leftMiddle.Height; - - _transactionDataBox.Height = _transactionScrollArea.Height = _rightMiddle.Height; - _totalLabel.Y = _rightBottom.Y + _rightBottom.Height - RIGHT_OFFSET * 3 + 15; - _accept.Y = _clear.Y = (_rightBottom.Y + _rightBottom.Height) - 50; - _leftDown.Y = _leftBottom.Y; - _rightDown.Y = _rightBottom.Y; - - if (_playerGoldLabel != null) - { - _playerGoldLabel.Y = _totalLabel.Y; - } - - _transactionDataBox.ReArrangeChildren(); - WantUpdateSize = true; - } - - if (_shopItems.Count == 0) - { - Dispose(); - } - - if (_buttonScroll != ButtonScroll.None) - { - ProcessListScroll(); - } - - if (_updateTotal) - { - long sum = 0; - - foreach (TransactionItem t in _transactionItems.Values) - { - sum += t.Amount * t.Price; - } - - _totalLabel.Text = sum.ToString(); - _updateTotal = false; - } - - if (_playerGoldLabel != null) - { - _playerGoldLabel.Text = World.Player.Gold.ToString(); - } - - base.Update(); - } - - public override bool Draw(UltimaBatcher2D batcher, int x, int y) - { - return base.Draw(batcher, x, y); - } - - private void ProcessListScroll() - { - if (Time.Ticks - _lastMouseEventTime >= SCROLL_DELAY) - { - switch (_buttonScroll) - { - case ButtonScroll.LeftScrollUp: - _shopScrollArea.Scroll(true); - break; - case ButtonScroll.LeftScrollDown: - _shopScrollArea.Scroll(false); - break; - case ButtonScroll.RightScrollUp: - _transactionScrollArea.Scroll(true); - break; - case ButtonScroll.RightScrollDown: - _transactionScrollArea.Scroll(false); - break; - } - _lastMouseEventTime = Time.Ticks; - } - } - - private void ShopItem_MouseDoubleClick(object sender, MouseDoubleClickEventArgs e) - { - ShopItem shopItem = (ShopItem)sender; - - if (shopItem.Amount <= 0) - { - return; - } - - int total = Keyboard.Shift ? shopItem.Amount : 1; - - if ( - _transactionItems.TryGetValue( - shopItem.LocalSerial, - out TransactionItem transactionItem - ) - ) - { - transactionItem.Amount += total; - } - else - { - transactionItem = new TransactionItem( - shopItem.LocalSerial, - shopItem.Graphic, - shopItem.Hue, - total, - shopItem.Price, - shopItem.ShopItemName - ); - - transactionItem.OnIncreaseButtomClicked += TransactionItem_OnIncreaseButtomClicked; - transactionItem.OnDecreaseButtomClicked += TransactionItem_OnDecreaseButtomClicked; - _transactionDataBox.Add(transactionItem); - _transactionItems.Add(shopItem.LocalSerial, transactionItem); - _transactionDataBox.WantUpdateSize = true; - _transactionDataBox.ReArrangeChildren(); - } - - shopItem.Amount -= total; - _updateTotal = true; - } - - private void TransactionItem_OnDecreaseButtomClicked(object sender, EventArgs e) - { - TransactionItem transactionItem = (TransactionItem)sender; - - int total = Keyboard.Shift ? transactionItem.Amount : 1; - - if (transactionItem.Amount > 0) - { - _shopItems[transactionItem.LocalSerial].Amount += total; - - transactionItem.Amount -= total; - } - - if (transactionItem.Amount <= 0) - { - RemoveTransactionItem(transactionItem); - } - - _updateTotal = true; - } - - private void RemoveTransactionItem(TransactionItem transactionItem) - { - _shopItems[transactionItem.LocalSerial].Amount += transactionItem.Amount; - - transactionItem.OnIncreaseButtomClicked -= TransactionItem_OnIncreaseButtomClicked; - transactionItem.OnDecreaseButtomClicked -= TransactionItem_OnDecreaseButtomClicked; - _transactionItems.Remove(transactionItem.LocalSerial); - transactionItem.Dispose(); - _transactionDataBox.WantUpdateSize = true; - _transactionDataBox.ReArrangeChildren(); - _updateTotal = true; - } - - private void TransactionItem_OnIncreaseButtomClicked(object sender, EventArgs e) - { - TransactionItem transactionItem = (TransactionItem)sender; - - if (_shopItems[transactionItem.LocalSerial].Amount > 0) - { - _shopItems[transactionItem.LocalSerial].Amount--; - - transactionItem.Amount++; - } - - _updateTotal = true; - } - - private void ShopItem_MouseClick(object sender, MouseEventArgs e) - { - foreach ( - ShopItem shopItem in _shopScrollArea.Children - .SelectMany(o => o.Children) - .OfType() - ) - { - shopItem.IsSelected = shopItem == sender; - } - } - - public override void OnButtonClick(int buttonID) - { - switch ((Buttons)buttonID) - { - case Buttons.Accept: - Tuple[] items = _transactionItems - .Select(t => new Tuple(t.Key, (ushort)t.Value.Amount)) - .ToArray(); - - if (IsBuyGump) - { - NetClient.Socket.Send_BuyRequest(LocalSerial, items); - } - else - { - NetClient.Socket.Send_SellRequest(LocalSerial, items); - } - - Dispose(); - - break; - - case Buttons.Clear: - - foreach (TransactionItem t in _transactionItems.Values.ToList()) - { - RemoveTransactionItem(t); - } - - break; - } - } - - private enum Buttons - { - Accept, - Clear - } - - private class ShopItem : Control - { - private readonly Label _amountLabel, - _name; - - public ShopItem( - uint serial, - ushort graphic, - ushort hue, - int count, - uint price, - string name - ) - { - LocalSerial = serial; - Graphic = graphic; - Hue = hue; - Price = price; - Name = name; - - ResizePicLine line = new ResizePicLine(0x39) { X = 10, Width = 190 }; - Add(line); - - int offY = 15; - - string itemName = StringHelper.CapitalizeAllWords(Name); - - if (!SerialHelper.IsValid(serial)) - { - return; - } - - string subname = string.Format(ResGumps.Item0Price1, itemName, Price); - - Add( - _name = new Label( - subname, - true, - 0x219, - 110, - 1, - FontStyle.None, - TEXT_ALIGN_TYPE.TS_LEFT, - true - ) - { - X = 55, - Y = offY - } - ); - - int height = Math.Max(_name.Height, 35) + 10; - - if (SerialHelper.IsItem(serial)) - { - height = Math.Max(TileDataLoader.Instance.StaticData[graphic].Height, height); - } - - Add( - _amountLabel = new Label( - count.ToString(), - true, - 0x0219, - 35, - 1, - FontStyle.None, - TEXT_ALIGN_TYPE.TS_RIGHT - ) - { - X = 168, - Y = offY + (height >> 2) - } - ); - - Width = 220; - Height = Math.Max(50, height) + line.Height; - - WantUpdateSize = false; - - if (World.ClientFeatures.TooltipsEnabled) - { - SetTooltip(LocalSerial); - } - - Amount = count; - } - - internal string ShopItemName => _name.Text; - - public int Amount - { - get => int.Parse(_amountLabel.Text); - set => _amountLabel.Text = value.ToString(); - } - - public bool IsSelected - { - set - { - foreach (Label label in Children.OfType