├── .gitignore ├── 3DUtils ├── Camera.cs ├── CameraDriver.cs ├── CameraDriverTransformations.cs ├── DollyController.cs ├── DollyTransition.cs ├── MathUtils.cs ├── Screen.cs └── Transform.cs ├── Effects ├── Grid.fx ├── Grid.xnb ├── HiDef │ ├── Grid.fx │ └── Grid.xnb ├── InnerPixel.fx ├── InnerPixel.xnb ├── Texture.fx └── Texture.xnb ├── Geometry ├── PixelGrid.cs └── Quad.cs ├── Hooks ├── DrawHooks.cs ├── DrawTileHooks.cs ├── Hooks.cs ├── InputHooks.cs └── WaterHooks.cs ├── Images ├── CameraIcon.png └── Noise.png ├── Input ├── CameraDriverBindings.cs ├── Cursor3D.cs └── InputTerraria3D.cs ├── LICENSE ├── Localization └── en-US_Mods.Terraria3D.hjson ├── Properties └── launchSettings.json ├── README.md ├── Rendering ├── CapRenderer.cs ├── GridRenderer.cs ├── InnerPixelRenderer.cs ├── InterfaceRendering.cs ├── RTManager.cs ├── Reflection.cs ├── Renderers.cs ├── Rendering.cs ├── TileDrawReflection.cs └── TileSolidOverrides.cs ├── Scene ├── Layer3D.cs ├── LayerManager.cs ├── LayersBuilder.cs └── Scene3D.cs ├── Serialization ├── CameraData.cs ├── FileUtils.cs ├── LayerData.cs ├── SceneData.cs ├── Settings.cs └── SettingsData.cs ├── Terraria3D.cs ├── Terraria3D.csproj ├── Terraria3D.sln ├── UI ├── Elements │ ├── UICameraControlsPanel.cs │ ├── UILayerEntry.cs │ ├── UIListModifiedScrollAmount.cs │ ├── UIListScrollView.cs │ └── UISlider.cs ├── UISettingsWindow.cs ├── UITerraria3D.cs ├── UIWindow.cs └── UserInterfaces │ ├── GenericUserInterface.cs │ ├── UserInterfaceOverlay.cs │ └── UserInterfaceSettings.cs ├── Utils ├── Loading.cs └── Utils.cs ├── app.config ├── build.txt ├── description.txt └── icon.png /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | lib/ 30 | Effects/Compiler/ 31 | 32 | # Visual Studio 2015/2017 cache/options directory 33 | .vs/ 34 | # Uncomment if you have tasks that create the project's static files in wwwroot 35 | #wwwroot/ 36 | 37 | # Visual Studio 2017 auto generated files 38 | Generated\ Files/ 39 | 40 | # MSTest test Results 41 | [Tt]est[Rr]esult*/ 42 | [Bb]uild[Ll]og.* 43 | 44 | # NUNIT 45 | *.VisualState.xml 46 | TestResult.xml 47 | 48 | # Build Results of an ATL Project 49 | [Dd]ebugPS/ 50 | [Rr]eleasePS/ 51 | dlldata.c 52 | 53 | # Benchmark Results 54 | BenchmarkDotNet.Artifacts/ 55 | 56 | # .NET Core 57 | project.lock.json 58 | project.fragment.lock.json 59 | artifacts/ 60 | 61 | # StyleCop 62 | StyleCopReport.xml 63 | 64 | # Files built by Visual Studio 65 | *_i.c 66 | *_p.c 67 | *_h.h 68 | *.ilk 69 | *.meta 70 | *.obj 71 | *.iobj 72 | *.pch 73 | *.pdb 74 | *.ipdb 75 | *.pgc 76 | *.pgd 77 | *.rsp 78 | *.sbr 79 | *.tlb 80 | *.tli 81 | *.tlh 82 | *.tmp 83 | *.tmp_proj 84 | *_wpftmp.csproj 85 | *.log 86 | *.vspscc 87 | *.vssscc 88 | .builds 89 | *.pidb 90 | *.svclog 91 | *.scc 92 | 93 | # Chutzpah Test files 94 | _Chutzpah* 95 | 96 | # Visual C++ cache files 97 | ipch/ 98 | *.aps 99 | *.ncb 100 | *.opendb 101 | *.opensdf 102 | *.sdf 103 | *.cachefile 104 | *.VC.db 105 | *.VC.VC.opendb 106 | 107 | # Visual Studio profiler 108 | *.psess 109 | *.vsp 110 | *.vspx 111 | *.sap 112 | 113 | # Visual Studio Trace Files 114 | *.e2e 115 | 116 | # TFS 2012 Local Workspace 117 | $tf/ 118 | 119 | # Guidance Automation Toolkit 120 | *.gpState 121 | 122 | # ReSharper is a .NET coding add-in 123 | _ReSharper*/ 124 | *.[Rr]e[Ss]harper 125 | *.DotSettings.user 126 | 127 | # JustCode is a .NET coding add-in 128 | .JustCode 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # The packages folder can be ignored because of Package Restore 188 | **/[Pp]ackages/* 189 | # except build/, which is used as an MSBuild target. 190 | !**/[Pp]ackages/build/ 191 | # Uncomment if necessary however generally it will be regenerated when needed 192 | #!**/[Pp]ackages/repositories.config 193 | # NuGet v3's project.json files produces more ignorable files 194 | *.nuget.props 195 | *.nuget.targets 196 | 197 | # Microsoft Azure Build Output 198 | csx/ 199 | *.build.csdef 200 | 201 | # Microsoft Azure Emulator 202 | ecf/ 203 | rcf/ 204 | 205 | # Windows Store app package directories and files 206 | AppPackages/ 207 | BundleArtifacts/ 208 | Package.StoreAssociation.xml 209 | _pkginfo.txt 210 | *.appx 211 | 212 | # Visual Studio cache files 213 | # files ending in .cache can be ignored 214 | *.[Cc]ache 215 | # but keep track of directories ending in .cache 216 | !?*.[Cc]ache/ 217 | 218 | # Others 219 | ClientBin/ 220 | ~$* 221 | *~ 222 | *.dbmdl 223 | *.dbproj.schemaview 224 | *.jfm 225 | *.pfx 226 | *.publishsettings 227 | orleans.codegen.cs 228 | 229 | # Including strong name files can present a security risk 230 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 231 | #*.snk 232 | 233 | # Since there are multiple workflows, uncomment next line to ignore bower_components 234 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 235 | #bower_components/ 236 | # ASP.NET Core default setup: bower directory is configured as wwwroot/lib/ and bower restore is true 237 | **/wwwroot/lib/ 238 | 239 | # RIA/Silverlight projects 240 | Generated_Code/ 241 | 242 | # Backup & report files from converting an old project file 243 | # to a newer Visual Studio version. Backup files are not needed, 244 | # because we have git ;-) 245 | _UpgradeReport_Files/ 246 | Backup*/ 247 | UpgradeLog*.XML 248 | UpgradeLog*.htm 249 | ServiceFabricBackup/ 250 | *.rptproj.bak 251 | 252 | # SQL Server files 253 | *.mdf 254 | *.ldf 255 | *.ndf 256 | 257 | # Business Intelligence projects 258 | *.rdl.data 259 | *.bim.layout 260 | *.bim_*.settings 261 | *.rptproj.rsuser 262 | 263 | # Microsoft Fakes 264 | FakesAssemblies/ 265 | 266 | # GhostDoc plugin setting file 267 | *.GhostDoc.xml 268 | 269 | # Node.js Tools for Visual Studio 270 | .ntvs_analysis.dat 271 | node_modules/ 272 | 273 | # Visual Studio 6 build log 274 | *.plg 275 | 276 | # Visual Studio 6 workspace options file 277 | *.opt 278 | 279 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 280 | *.vbw 281 | 282 | # Visual Studio LightSwitch build output 283 | **/*.HTMLClient/GeneratedArtifacts 284 | **/*.DesktopClient/GeneratedArtifacts 285 | **/*.DesktopClient/ModelManifest.xml 286 | **/*.Server/GeneratedArtifacts 287 | **/*.Server/ModelManifest.xml 288 | _Pvt_Extensions 289 | 290 | # Paket dependency manager 291 | .paket/paket.exe 292 | paket-files/ 293 | 294 | # FAKE - F# Make 295 | .fake/ 296 | 297 | # JetBrains Rider 298 | .idea/ 299 | *.sln.iml 300 | 301 | # CodeRush personal settings 302 | .cr/personal 303 | 304 | # Python Tools for Visual Studio (PTVS) 305 | __pycache__/ 306 | *.pyc 307 | 308 | # Cake - Uncomment if you are using it 309 | # tools/** 310 | # !tools/packages.config 311 | 312 | # Tabs Studio 313 | *.tss 314 | 315 | # Telerik's JustMock configuration file 316 | *.jmconfig 317 | 318 | # BizTalk build output 319 | *.btp.cs 320 | *.btm.cs 321 | *.odx.cs 322 | *.xsd.cs 323 | 324 | # OpenCover UI analysis results 325 | OpenCover/ 326 | 327 | # Azure Stream Analytics local run output 328 | ASALocalRun/ 329 | 330 | # MSBuild Binary and Structured Log 331 | *.binlog 332 | 333 | # NVidia Nsight GPU debugger configuration file 334 | *.nvuser 335 | 336 | # MFractors (Xamarin productivity tool) working folder 337 | .mfractor/ 338 | 339 | # Local History for Visual Studio 340 | .localhistory/ 341 | 342 | # BeatPulse healthcheck temp database 343 | healthchecksdb -------------------------------------------------------------------------------- /3DUtils/Camera.cs: -------------------------------------------------------------------------------- 1 | using Terraria; 2 | using Microsoft.Xna.Framework; 3 | 4 | namespace Terraria3D; 5 | 6 | public class Camera 7 | { 8 | public Transform Transform { get; private set; } = new Transform(); 9 | public float FieldOfView { get; set; } = 60; 10 | public float NearClipPlane { get; set; } = 0.001f; 11 | public float FarClipPlane { get; set; } = 200f; 12 | 13 | public Camera() { } 14 | 15 | public Camera(Camera sourceCamera) 16 | { 17 | FieldOfView = sourceCamera.FieldOfView; 18 | NearClipPlane = sourceCamera.NearClipPlane; 19 | FarClipPlane = sourceCamera.FarClipPlane; 20 | } 21 | 22 | public void LookAt(Vector3 position) => LookAt(position, Vector3.Up); 23 | public void LookAt(Vector3 position, Vector3 up) 24 | { 25 | Transform.Rotation = MathUtils.LookRotation(Transform.Position - position, up); 26 | } 27 | 28 | public Matrix Projection => Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(FieldOfView), Screen.Aspect, NearClipPlane, FarClipPlane); 29 | public Matrix View => Matrix.Invert(Transform.LocalToWorld); 30 | public Ray ScreenPointToRay(Vector2 screenPosition) 31 | { 32 | Vector3 nearPoint = new Vector3(screenPosition, 0); //new Vector3(screenPosition.X, screenPosition.Y, 0); 33 | Vector3 farPoint = nearPoint + Vector3.Backward; 34 | 35 | nearPoint = Main.graphics.GraphicsDevice.Viewport.Unproject(nearPoint, Projection, View, Matrix.Identity); 36 | farPoint = Main.graphics.GraphicsDevice.Viewport.Unproject(farPoint, Projection, View, Matrix.Identity); 37 | 38 | Vector3 direction = farPoint - nearPoint; 39 | direction.Normalize(); 40 | 41 | return new Ray(nearPoint, direction); 42 | } 43 | } -------------------------------------------------------------------------------- /3DUtils/CameraDriver.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Input; 3 | using System; 4 | using Terraria; 5 | 6 | namespace Terraria3D; 7 | 8 | public partial class CameraDriver 9 | { 10 | public Camera Camera { get; private set; } 11 | public float LookAtDistance { get; private set; } 12 | public float MoveSpeed { get; set; } = 1f; 13 | public float LookSensitivity { get; set; } = 1f; 14 | public CameraMoveMode MoveMode { get; set; } = CameraMoveMode.Relative; 15 | public CameraYStart YStartPosition { get; set; } = CameraYStart.Center; 16 | 17 | private bool _moveModeRelative => MoveMode == CameraMoveMode.Relative; 18 | 19 | private Vector3 _forwardAxis => _moveModeRelative ? Camera.Transform.Forward : Vector3.Forward; 20 | private Vector3 _rightAxis => _moveModeRelative ? Camera.Transform.Right : Vector3.Right; 21 | private Vector3 _upAxis => _moveModeRelative ? Camera.Transform.Up : Vector3.Up; 22 | 23 | public CameraDriver(Camera camera) 24 | { 25 | Camera = camera; 26 | ResetCameraPosition(); 27 | } 28 | 29 | public void Drive(float deltaTime) 30 | { 31 | var mouseDelta = new Vector2(Main.mouseX - Main.lastMouseX, Main.mouseY - Main.lastMouseY); 32 | 33 | if (Main.keyState.IsKeyDown(_resetKey)) 34 | ResetCameraPosition(); 35 | 36 | if (Main.keyState.IsKeyDown(Keys.LeftAlt) && !Main.LocalPlayer.mouseInterface) 37 | { 38 | if (Main.mouseLeft) 39 | MouseOrbit(LookSensitivity * 5f, mouseDelta, deltaTime); 40 | if (Main.mouseMiddle) 41 | PanCamera(LookSensitivity * 0.04f, mouseDelta, deltaTime); 42 | if (Main.mouseRight) 43 | MouseZoom(LookSensitivity * 0.04f, mouseDelta, deltaTime); 44 | } 45 | else 46 | { 47 | FlyCamera(MoveSpeed * 0.2f, deltaTime); 48 | if (!Main.LocalPlayer.mouseInterface) 49 | Rotate(LookSensitivity * 5f, mouseDelta, deltaTime); 50 | ArrowKeyOrbit(45, deltaTime); 51 | } 52 | } 53 | 54 | private Vector3 GetLookAtPoint() => Camera.Transform.Position + Camera.Transform.Forward * LookAtDistance; 55 | 56 | public enum CameraMoveMode 57 | { 58 | Relative, 59 | World 60 | } 61 | public enum CameraYStart 62 | { 63 | Center, 64 | Offset 65 | } 66 | } -------------------------------------------------------------------------------- /3DUtils/CameraDriverTransformations.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Input; 3 | using Terraria; 4 | 5 | namespace Terraria3D; 6 | 7 | public partial class CameraDriver 8 | { 9 | public void ResetCameraPosition() 10 | { 11 | Camera.Transform.Position = YStartPosition == CameraYStart.Offset ? new Vector3(0, 0.08f, 0.4f) : Vector3.Backward * 0.4f; 12 | Camera.LookAt(Vector3.Zero, Vector3.Up); 13 | Camera.FieldOfView = 60; 14 | LookAtDistance = Vector3.Distance(Camera.Transform.Position, Vector3.Zero); 15 | } 16 | 17 | private void FlyCamera(float moveSpeed, float deltaTime) 18 | { 19 | var moveVector = _forwardAxis * _forwardAxisInput.GetValue() * moveSpeed + 20 | _rightAxis * _rightAxisInput.GetValue() * moveSpeed + 21 | _upAxis * _upAxisInput.GetValue() * moveSpeed; 22 | Move(moveVector, deltaTime); 23 | } 24 | 25 | private void PanCamera(float sensitivity, Vector2 mouseDelta, float deltaTime) 26 | { 27 | var moveVector = _rightAxis * -mouseDelta.X * sensitivity + 28 | _upAxis * mouseDelta.Y * sensitivity; 29 | Move(moveVector, deltaTime); 30 | } 31 | 32 | private void Move(Vector3 moveVector, float deltaTime) 33 | => Camera.Transform.Position += moveVector * deltaTime; 34 | 35 | private void MouseOrbit(float sensitivity, Vector2 mouseDelta, float deltaTime) 36 | { 37 | OrbitX(-mouseDelta.Y * sensitivity, deltaTime); 38 | OrbitY(-mouseDelta.X * sensitivity, deltaTime); 39 | } 40 | 41 | private void Rotate(float lookSensitivity, Vector2 mouseDelta, float deltaTime) 42 | { 43 | if (Main.mouseLeft) 44 | { 45 | Camera.Transform.Rotation = Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.ToRadians(-mouseDelta.X * lookSensitivity) * deltaTime) * Camera.Transform.Rotation; 46 | Camera.Transform.Rotation = Quaternion.CreateFromAxisAngle(Camera.Transform.Right, MathHelper.ToRadians(-mouseDelta.Y * lookSensitivity) * deltaTime) * Camera.Transform.Rotation; 47 | } 48 | } 49 | 50 | private void ArrowKeyOrbit(float degreesPerSecond, float deltaTime) 51 | { 52 | var yRot = 0f; 53 | if (Main.keyState.IsKeyDown(Keys.Left)) yRot -= degreesPerSecond; 54 | if (Main.keyState.IsKeyDown(Keys.Right)) yRot += degreesPerSecond; 55 | 56 | var xRot = 0f; 57 | if (Main.keyState.IsKeyDown(Keys.Up)) xRot -= degreesPerSecond; 58 | if (Main.keyState.IsKeyDown(Keys.Down)) xRot += degreesPerSecond; 59 | 60 | OrbitY(yRot, deltaTime); 61 | OrbitX(xRot, deltaTime); 62 | } 63 | 64 | private void OrbitY(float angle, float deltaTime) => Orbit(angle, Vector3.Up, deltaTime); 65 | private void OrbitX(float angle, float deltaTime) => Orbit(angle, Camera.Transform.Right, deltaTime); 66 | 67 | private void Orbit(float angle, Vector3 axis, float deltaTime) 68 | { 69 | var lookAtPoint = GetLookAtPoint(); 70 | var matrix = GetOrbitMatrix(lookAtPoint, Matrix.CreateFromAxisAngle(axis, MathHelper.ToRadians(angle * deltaTime))); 71 | Camera.Transform.Position = Vector3.Transform(Camera.Transform.Position, matrix); 72 | Camera.LookAt(lookAtPoint, Vector3.Up); 73 | } 74 | 75 | private Matrix GetOrbitMatrix(Vector3 center, Matrix rotation) 76 | { 77 | return Matrix.CreateTranslation(-center) * 78 | rotation * 79 | Matrix.CreateTranslation(center); 80 | } 81 | 82 | private void MouseZoom(float sensitivity, Vector2 mouseDelta, float deltaTime) 83 | { 84 | var distance = (mouseDelta.X + mouseDelta.Y) * sensitivity; 85 | Zoom(distance, deltaTime); 86 | } 87 | 88 | // This doesn't change the FOV. It moves the camera along 89 | // the forward axis while keeping the look at point stationary. 90 | private void Zoom(float distance, float deltaTime) 91 | { 92 | var minDistFromLookAtPoint = 0.1f; 93 | var maxDistFromLookAtPoint = 2f; 94 | 95 | var lookAtPoint = GetLookAtPoint(); 96 | Camera.Transform.Position += Camera.Transform.Forward * distance * deltaTime; 97 | LookAtDistance = Vector3.Distance(Camera.Transform.Position, lookAtPoint); 98 | // Check if camera shot past the look at point. 99 | if (Vector3.Dot(Camera.Transform.Forward, Camera.Transform.Position - lookAtPoint) > 0) 100 | Camera.Transform.Position = lookAtPoint - Camera.Transform.Forward * minDistFromLookAtPoint; 101 | else 102 | { 103 | LookAtDistance = MathHelper.Clamp(LookAtDistance, minDistFromLookAtPoint, maxDistFromLookAtPoint); 104 | Camera.Transform.Position = lookAtPoint - Camera.Transform.Forward * LookAtDistance; 105 | } 106 | } 107 | 108 | } -------------------------------------------------------------------------------- /3DUtils/DollyController.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace Terraria3D; 4 | 5 | public class DollyController 6 | { 7 | const float TRANSITION_TIME = 0.2f; 8 | 9 | public Camera TransitionCamera { get; private set; } 10 | public bool DollyInProgress => _transition.InProgress; 11 | 12 | private Camera _camera; 13 | private DollyTransition _transition; 14 | 15 | public DollyController(Camera camera) 16 | { 17 | _camera = camera; 18 | TransitionCamera = new Camera(_camera); 19 | _transition = new DollyTransition(TransitionCamera); 20 | } 21 | 22 | public void Update(float deltaTime) => _transition.Update(deltaTime); 23 | 24 | public void TransitionIn() 25 | => _transition.TransitionIn(TRANSITION_TIME, _camera); 26 | 27 | public async Task TransitionOutAsync() 28 | => await _transition.TransitionOutAsync(TRANSITION_TIME, _camera); 29 | } -------------------------------------------------------------------------------- /3DUtils/DollyTransition.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using System; 3 | using System.Threading.Tasks; 4 | using Terraria; 5 | 6 | namespace Terraria3D; 7 | 8 | public class DollyTransition 9 | { 10 | public bool InProgress { get; private set; } = false; 11 | 12 | private const float Proxy2DFoV = 3; 13 | 14 | private Camera _camera; 15 | 16 | private CameraState _startState; 17 | private CameraState _targetState; 18 | private bool _movingIn = false; 19 | 20 | private float _time; 21 | private float _transitionTime; 22 | 23 | 24 | private TaskCompletionSource _transitionTCS; 25 | 26 | 27 | public DollyTransition(Camera camera) 28 | { 29 | _camera = camera; 30 | } 31 | private float DistFromFov(float fov, float height) 32 | { 33 | return height * 0.5f / (float)Math.Tan(fov * 0.5f); 34 | } 35 | 36 | private CameraState Get2DProxyState() 37 | { 38 | var result = new CameraState(); 39 | result.FieldOfView = MathHelper.ToRadians(Proxy2DFoV); 40 | result.Position = Vector3.Backward * DistFromFov(result.FieldOfView, 1f / Main.GameZoomTarget); 41 | result.Rotation = Quaternion.Identity; 42 | return result; 43 | } 44 | 45 | public async Task TransitionOutAsync(float transitionTime, Camera sceneCamera) 46 | { 47 | TransitionOut(transitionTime, sceneCamera); 48 | await DoTransitionAsync(); 49 | } 50 | 51 | public void TransitionIn(float transitionTime, Camera sceneCamera) 52 | { 53 | if (InProgress) return; 54 | _movingIn = true; 55 | SetupTransition(transitionTime); 56 | _startState = Get2DProxyState(); 57 | _targetState = new CameraState(sceneCamera); 58 | UpdateCamera(0); 59 | } 60 | 61 | public void TransitionOut(float transitionTime, Camera sceneCamera) 62 | { 63 | if (InProgress) return; 64 | _movingIn = false; 65 | SetupTransition(transitionTime); 66 | _startState = new CameraState(sceneCamera); 67 | _targetState = Get2DProxyState(); 68 | } 69 | 70 | private async Task DoTransitionAsync() 71 | { 72 | _transitionTCS = new TaskCompletionSource(); 73 | await _transitionTCS.Task; 74 | } 75 | 76 | private void SetupTransition(float transitionTime) 77 | { 78 | InProgress = true; 79 | _transitionTime = transitionTime; 80 | _time = 0; 81 | } 82 | 83 | private float CircleEaseOut(float t) 84 | { 85 | t -= 1; 86 | return (float)Math.Sqrt(1 - t * t); 87 | } 88 | private float CircleEaseIn(float t) 89 | { 90 | return 1 - (float)Math.Sqrt(1 - t * t); 91 | } 92 | 93 | private void UpdateCamera(float t) 94 | { 95 | t = _movingIn ? CircleEaseOut(t) : CircleEaseIn(t); 96 | var fov = MathHelper.Lerp(_startState.FieldOfView, _targetState.FieldOfView, t); 97 | _camera.FieldOfView = MathHelper.ToDegrees(fov); 98 | 99 | var zPlane = Vector3.Backward * DistFromFov((_movingIn ? _targetState : _startState).FieldOfView, 1f / Main.GameZoomTarget); 100 | var offset = _movingIn ? Vector3.Lerp(zPlane, _targetState.Position, t) - zPlane : 101 | Vector3.Lerp(_startState.Position, zPlane, t) - zPlane; 102 | _camera.Transform.Position = Vector3.Backward * DistFromFov(fov, 1f / Main.GameZoomTarget) + offset; 103 | 104 | var t2 = _movingIn ? CircleEaseIn(t) : CircleEaseOut(t); 105 | _camera.Transform.Rotation = Quaternion.Lerp(_startState.Rotation, _targetState.Rotation, t2); 106 | } 107 | 108 | public void Update(float deltaTime) 109 | { 110 | if(InProgress) 111 | { 112 | var t = _time / _transitionTime; 113 | UpdateCamera(t); 114 | _time += deltaTime; 115 | if (_time >= _transitionTime) 116 | { 117 | InProgress = false; 118 | UpdateCamera(1); 119 | _transitionTCS?.SetResult(true); 120 | _transitionTCS = null; 121 | } 122 | } 123 | } 124 | 125 | private struct CameraState 126 | { 127 | public Vector3 Position { get; set; } 128 | public Quaternion Rotation { get; set; } 129 | public float FieldOfView { get; set; } 130 | 131 | public CameraState(Camera camera) 132 | { 133 | Position = camera.Transform.Position; 134 | Rotation = camera.Transform.Rotation; 135 | FieldOfView = MathHelper.ToRadians(camera.FieldOfView); 136 | } 137 | } 138 | } -------------------------------------------------------------------------------- /3DUtils/MathUtils.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using System; 3 | 4 | namespace Terraria3D; 5 | 6 | public static class MathUtils 7 | { 8 | public static Quaternion LookRotation(Vector3 forward, Vector3 up) 9 | { 10 | forward.Normalize(); 11 | 12 | Vector3 vector = Vector3.Normalize(forward); 13 | Vector3 vector2 = Vector3.Normalize(Vector3.Cross(up, vector)); 14 | Vector3 vector3 = Vector3.Cross(vector, vector2); 15 | var m00 = vector2.X; 16 | var m01 = vector2.Y; 17 | var m02 = vector2.Z; 18 | var m10 = vector3.X; 19 | var m11 = vector3.Y; 20 | var m12 = vector3.Z; 21 | var m20 = vector.X; 22 | var m21 = vector.Y; 23 | var m22 = vector.Z; 24 | 25 | float num8 = (m00 + m11) + m22; 26 | var quaternion = new Quaternion(); 27 | if (num8 > 0f) 28 | { 29 | var num = (float)Math.Sqrt(num8 + 1f); 30 | quaternion.W = num * 0.5f; 31 | num = 0.5f / num; 32 | quaternion.X = (m12 - m21) * num; 33 | quaternion.Y = (m20 - m02) * num; 34 | quaternion.Z = (m01 - m10) * num; 35 | return quaternion; 36 | } 37 | if ((m00 >= m11) && (m00 >= m22)) 38 | { 39 | var num7 = (float)Math.Sqrt(((1f + m00) - m11) - m22); 40 | var num4 = 0.5f / num7; 41 | quaternion.X = 0.5f * num7; 42 | quaternion.Y = (m01 + m10) * num4; 43 | quaternion.Z = (m02 + m20) * num4; 44 | quaternion.W = (m12 - m21) * num4; 45 | return quaternion; 46 | } 47 | if (m11 > m22) 48 | { 49 | var num6 = (float)Math.Sqrt(((1f + m11) - m00) - m22); 50 | var num3 = 0.5f / num6; 51 | quaternion.X = (m10 + m01) * num3; 52 | quaternion.Y = 0.5f * num6; 53 | quaternion.Z = (m21 + m12) * num3; 54 | quaternion.W = (m20 - m02) * num3; 55 | return quaternion; 56 | } 57 | var num5 = (float)Math.Sqrt(((1f + m22) - m00) - m11); 58 | var num2 = 0.5f / num5; 59 | quaternion.X = (m20 + m02) * num2; 60 | quaternion.Y = (m21 + m12) * num2; 61 | quaternion.Z = 0.5f * num5; 62 | quaternion.W = (m01 - m10) * num2; 63 | return quaternion; 64 | } 65 | } -------------------------------------------------------------------------------- /3DUtils/Screen.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework.Graphics; 2 | using Terraria; 3 | 4 | namespace Terraria3D; 5 | 6 | public static class Screen 7 | { 8 | private static GraphicsDevice _graphicsDevice => Main.graphics.GraphicsDevice; 9 | public static int Width => _graphicsDevice.Viewport.Width; 10 | public static int Height => _graphicsDevice.Viewport.Height; 11 | public static float Aspect => (float)Width / Height; 12 | 13 | } -------------------------------------------------------------------------------- /3DUtils/Transform.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | 3 | namespace Terraria3D; 4 | 5 | public class Transform 6 | { 7 | public Vector3 Position { get; set; } = Vector3.Zero; 8 | public Quaternion Rotation { get; set; } = Quaternion.Identity; 9 | public Vector3 Scale { get; set; } = Vector3.One; 10 | 11 | public Matrix LocalToWorld => Matrix.CreateScale(Scale) * 12 | Matrix.CreateFromQuaternion(Rotation) * 13 | Matrix.CreateTranslation(Position); 14 | 15 | public Vector3 Forward => Vector3.Transform(Vector3.Forward, Rotation); 16 | public Vector3 Up => Vector3.Transform(Vector3.Up, Rotation); 17 | public Vector3 Right => Vector3.Transform(Vector3.Right, Rotation); 18 | } -------------------------------------------------------------------------------- /Effects/Grid.fx: -------------------------------------------------------------------------------- 1 | #define REMOVE_INNER 1 2 | #define ADD_NOISE 1 3 | 4 | float4x4 World; 5 | float4x4 View; 6 | float4x4 Projection; 7 | float2 PixelOffset; 8 | float2 CameraPosition; 9 | float Depth; 10 | 11 | #if ADD_NOISE 12 | float NoiseAmount; 13 | #endif 14 | 15 | texture _MainTex; 16 | sampler2D _MainTexSampler = sampler_state 17 | { 18 | Texture = (_MainTex); 19 | MinFilter = Point; 20 | MagFilter = Point; 21 | AddressU = Clamp; 22 | AddressV = Clamp; 23 | }; 24 | 25 | Texture NoiseTexture; 26 | sampler NoiseSampler = sampler_state { 27 | texture = ; 28 | magfilter = POINT; 29 | minfilter = POINT; 30 | mipfilter = POINT; 31 | AddressU = WRAP; 32 | AddressV = WRAP; 33 | }; 34 | 35 | 36 | 37 | struct VertexShaderInput 38 | { 39 | float4 Position : POSITION0; 40 | float2 UV : TEXCOORD0; 41 | float3 Normal : NORMAL; 42 | }; 43 | 44 | struct VertexShaderOutput 45 | { 46 | float4 Position : POSITION0; 47 | float3 LocalPosition : TEXCOORD1; 48 | float2 UV : TEXCOORD0; 49 | float3 Normal : TEXCOORD2; 50 | }; 51 | 52 | VertexShaderOutput VertexShaderFunction(VertexShaderInput input) 53 | { 54 | VertexShaderOutput output; 55 | float4 worldPosition = mul(input.Position, World); 56 | float4 viewPosition = mul(worldPosition, View); 57 | output.Position = mul(viewPosition, Projection); 58 | output.LocalPosition = input.Position; 59 | output.UV = input.UV; 60 | output.Normal = input.Normal; 61 | return output; 62 | } 63 | 64 | 65 | float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0 66 | { 67 | #if REMOVE_INNER 68 | float2 uv = input.UV - input.Normal.xy * PixelOffset.xy * 0.5; 69 | float2 uv2 = uv + input.Normal.xy * PixelOffset; 70 | float4 color1 = tex2D(_MainTexSampler, uv); 71 | float4 color2 = tex2D(_MainTexSampler, uv2); 72 | #else 73 | float2 uv = input.UV - input.Normal.xy * PixelOffset.xy * 0.5; 74 | float4 color1 = tex2D(_MainTexSampler, uv); 75 | float4 color2 = tex2D(_MainTexSampler, uv + input.Normal.xy * PixelOffset); 76 | #endif 77 | 78 | bool color1IsZero = color1.r == 0 && color1.g == 0 && color1.b == 0 && color1.a == 0; 79 | bool color2IsZero = color2.r == 0 && color2.g == 0 && color2.b == 0 && color2.a == 0; 80 | 81 | // If both pixels are transparent, clip it. 82 | clip(-(color1IsZero && color2IsZero)); 83 | 84 | #if REMOVE_INNER 85 | clip(-(!color1IsZero && !color2IsZero && 86 | uv.x > 0 && uv2.x < 1 && uv2.y > 0 && uv.y < 1)); 87 | #endif 88 | 89 | float4 result = color2IsZero ? color1 : color2; 90 | 91 | #if ADD_NOISE 92 | // Noise is 64x64, one noise color per 2 grid cells 93 | const float sampleOffset = 1.0 / 64 / 2; 94 | 95 | float x = dot(input.Normal, float3(0, 1, 0) > 0.5) ? 96 | (input.LocalPosition.x - CameraPosition.x) * sampleOffset : 97 | (input.LocalPosition.y - CameraPosition.y) * sampleOffset; 98 | float y = input.LocalPosition.z * sampleOffset * Depth; 99 | float2 sampleCoords = float2(x, y); 100 | 101 | float noise = tex2D(NoiseSampler, sampleCoords).r; 102 | result.rgb *= lerp(1, 0.5f + noise.r, NoiseAmount); 103 | #endif 104 | 105 | return result; 106 | } 107 | 108 | technique Technique1 109 | { 110 | pass Pass1 111 | { 112 | // Premultiplied Alpha 113 | AlphaBlendEnable = True; 114 | SrcBlend = One; 115 | DestBlend = InvSrcAlpha; 116 | CullMode = None; 117 | 118 | VertexShader = compile vs_2_0 VertexShaderFunction(); 119 | PixelShader = compile ps_2_0 PixelShaderFunction(); 120 | } 121 | } -------------------------------------------------------------------------------- /Effects/Grid.xnb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/prgmatic/Terraria3D/2a84c8fc535ee8ad0496f3fbd2e30de855881f31/Effects/Grid.xnb -------------------------------------------------------------------------------- /Effects/HiDef/Grid.fx: -------------------------------------------------------------------------------- 1 | #define REMOVE_INNER 1 2 | #define ADD_NOISE 1 3 | 4 | float4x4 World; 5 | float4x4 View; 6 | float4x4 Projection; 7 | float2 PixelOffset; 8 | float2 CameraPosition; 9 | float Depth; 10 | bool AO; 11 | 12 | #if ADD_NOISE 13 | float NoiseAmount; 14 | #endif 15 | 16 | texture _MainTex; 17 | sampler2D _MainTexSampler = sampler_state 18 | { 19 | Texture = (_MainTex); 20 | MinFilter = Point; 21 | MagFilter = Point; 22 | AddressU = Clamp; 23 | AddressV = Clamp; 24 | }; 25 | 26 | Texture NoiseTexture; 27 | sampler NoiseSampler = sampler_state { 28 | texture = ; 29 | magfilter = POINT; 30 | minfilter = POINT; 31 | mipfilter = POINT; 32 | AddressU = WRAP; 33 | AddressV = WRAP; 34 | }; 35 | 36 | 37 | 38 | struct VertexShaderInput 39 | { 40 | float4 Position : POSITION0; 41 | float2 UV : TEXCOORD0; 42 | float3 Normal : NORMAL; 43 | }; 44 | 45 | struct VertexShaderOutput 46 | { 47 | float4 Position : POSITION0; 48 | float3 LocalPosition : TEXCOORD1; 49 | float2 UV : TEXCOORD0; 50 | float3 Normal : TEXCOORD2; 51 | }; 52 | 53 | VertexShaderOutput VertexShaderFunction(VertexShaderInput input) 54 | { 55 | VertexShaderOutput output; 56 | float4 worldPosition = mul(input.Position, World); 57 | float4 viewPosition = mul(worldPosition, View); 58 | output.Position = mul(viewPosition, Projection); 59 | output.LocalPosition = input.Position; 60 | output.UV = input.UV; 61 | output.Normal = input.Normal; 62 | return output; 63 | } 64 | 65 | float slerp(float x) 66 | { 67 | return x * x * 3 - x * x * x * 2; 68 | } 69 | 70 | float GetAO(float pos) 71 | { 72 | return lerp(0.5, 1, slerp(pow(frac(pos), 1))); 73 | } 74 | 75 | float DoAOTwoPixel(float localPos, float2 direction, float2 start, float2 uv) 76 | { 77 | float2 offset = float2(start); 78 | offset += direction; 79 | float4 offsetPixel = tex2D(_MainTexSampler, uv + offset * PixelOffset); 80 | if (offsetPixel.a > 0.1) 81 | return GetAO(frac(localPos) * 0.5); 82 | else 83 | { 84 | offset += direction; 85 | offsetPixel = tex2D(_MainTexSampler, uv + offset * PixelOffset); 86 | if (offsetPixel.a > 0.1) 87 | return GetAO(frac(localPos) * 0.5 + 0.5); 88 | } 89 | return 1; 90 | } 91 | 92 | float DoAOOnePixel(float localPos, float2 direction, float2 start, float2 uv) 93 | { 94 | float2 offset = float2(start); 95 | offset += direction; 96 | float4 offsetPixel = tex2D(_MainTexSampler, uv + offset * PixelOffset); 97 | if (offsetPixel.a > 0.1) 98 | return GetAO(localPos); 99 | return 1; 100 | } 101 | 102 | 103 | float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0 104 | { 105 | #if REMOVE_INNER 106 | float2 uv = input.UV - input.Normal.xy * PixelOffset.xy * 0.5; 107 | float2 uv2 = uv + input.Normal.xy * PixelOffset; 108 | float4 color1 = tex2D(_MainTexSampler, uv); 109 | float4 color2 = tex2D(_MainTexSampler, uv2); 110 | #else 111 | float2 uv = input.UV - input.Normal.xy * PixelOffset.xy * 0.5; 112 | float4 color1 = tex2D(_MainTexSampler, uv); 113 | float4 color2 = tex2D(_MainTexSampler, uv + input.Normal.xy * PixelOffset); 114 | #endif 115 | const float epsilon = 0.0001; 116 | bool onEdge = input.UV.x < epsilon || input.UV.x > 1 - epsilon || 117 | input.UV.y < epsilon || input.UV.y > 1 - epsilon; 118 | 119 | bool color1IsZero = color1.r == 0 && color1.g == 0 && color1.b == 0 && color1.a == 0; 120 | bool color2IsZero = color2.r == 0 && color2.g == 0 && color2.b == 0 && color2.a == 0; 121 | 122 | // If both pixels are transparent, clip it. 123 | clip(-(color1IsZero && color2IsZero)); 124 | 125 | #if REMOVE_INNER 126 | clip(-(!color1IsZero && !color2IsZero && !onEdge)); 127 | #endif 128 | 129 | float4 result = color2IsZero ? color1 : color2; 130 | 131 | if (AO && !onEdge) 132 | { 133 | float2 start; 134 | float2 dir; 135 | if (input.Normal.y < -0.5) 136 | { 137 | start = float2(0, color2IsZero ? -1 : 0); 138 | dir = float2(-1, 0); 139 | result.rgb *= DoAOTwoPixel(input.LocalPosition.x, dir, start, uv); 140 | result.rgb *= DoAOTwoPixel(-input.LocalPosition.x, -dir, start, uv); 141 | } 142 | else 143 | { 144 | start = float2(color2IsZero ? 1 : 0, 0); 145 | dir = float2(0, -1); 146 | result.rgb *= DoAOTwoPixel(-input.LocalPosition.y, dir, start, uv); 147 | result.rgb *= DoAOTwoPixel(input.LocalPosition.y, -dir, start, uv); 148 | } 149 | } 150 | 151 | #if ADD_NOISE 152 | // Noise is 64x64, one noise color per 2 grid cells 153 | const float sampleOffset = 1.0 / 64 / 2; 154 | 155 | float x = dot(input.Normal, float3(0, 1, 0) > 0.5) ? 156 | (input.LocalPosition.x - CameraPosition.x) * sampleOffset : 157 | (input.LocalPosition.y - CameraPosition.y) * sampleOffset; 158 | float y = input.LocalPosition.z * sampleOffset * Depth; 159 | float2 sampleCoords = float2(x, y); 160 | 161 | float noise = tex2D(NoiseSampler, sampleCoords).r; 162 | result.rgb *= lerp(1, 0.5f + noise.r, NoiseAmount); 163 | #endif 164 | 165 | return result; 166 | } 167 | 168 | technique Technique1 169 | { 170 | pass Pass1 171 | { 172 | // Premultiplied Alpha 173 | AlphaBlendEnable = True; 174 | SrcBlend = One; 175 | DestBlend = InvSrcAlpha; 176 | CullMode = None; 177 | 178 | VertexShader = compile vs_3_0 VertexShaderFunction(); 179 | PixelShader = compile ps_3_0 PixelShaderFunction(); 180 | } 181 | } -------------------------------------------------------------------------------- /Effects/HiDef/Grid.xnb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/prgmatic/Terraria3D/2a84c8fc535ee8ad0496f3fbd2e30de855881f31/Effects/HiDef/Grid.xnb -------------------------------------------------------------------------------- /Effects/InnerPixel.fx: -------------------------------------------------------------------------------- 1 | float2 PixelOffset; 2 | 3 | sampler s0; 4 | 5 | float4 InnerPixelPS(float2 uv: TEXCOORD0) : COLOR0 6 | { 7 | float4 color = tex2D(s0, uv); 8 | 9 | if (color.a > 0) 10 | { 11 | // Go in 2 pixels 12 | float2 ScaledPixelOffset = PixelOffset * 2; 13 | 14 | // Sample neighboring pixels 15 | float4 sampleLeft = tex2D(s0, uv + float2(-ScaledPixelOffset.x, 0.0)); 16 | float4 sampleRight = tex2D(s0, uv + float2( ScaledPixelOffset.x, 0.0)); 17 | float4 sampleAbove = tex2D(s0, uv + float2(0.0, -ScaledPixelOffset.y)); 18 | float4 sampleBelow = tex2D(s0, uv + float2(0.0, ScaledPixelOffset.y)); 19 | 20 | // Store neighboring pixel states 21 | bool leftPixel = sampleLeft.a > 0.0f; 22 | bool rightPixel = sampleRight.a > 0.0f; 23 | bool abovePixel = sampleAbove.a > 0.0f; 24 | bool belowPixel = sampleBelow.a > 0.0f; 25 | 26 | float2 offset = float2(0, 0); 27 | 28 | if (rightPixel && !leftPixel) 29 | offset.x += ScaledPixelOffset.x; 30 | else if (leftPixel && !rightPixel) 31 | offset.x -= ScaledPixelOffset.x; 32 | if (abovePixel && !belowPixel) 33 | offset.y -= ScaledPixelOffset.y; 34 | else if (belowPixel && !abovePixel) 35 | offset.y += ScaledPixelOffset.y; 36 | float4 newColor = tex2D(s0, uv + offset); 37 | 38 | if (newColor.a > 0) 39 | { 40 | // If inner pixel is black, move in one more pixel 41 | if (newColor.r == 0 && newColor.g == 0 && newColor.b == 0) 42 | { 43 | newColor = tex2D(s0, uv + offset * 2); 44 | if (newColor.a > 0) 45 | color = newColor; 46 | } 47 | else 48 | color = newColor; 49 | } 50 | } 51 | return color; 52 | } 53 | 54 | technique InnerPixel 55 | { 56 | pass Pass0 57 | { 58 | PixelShader = compile ps_2_0 InnerPixelPS(); 59 | } 60 | } -------------------------------------------------------------------------------- /Effects/InnerPixel.xnb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/prgmatic/Terraria3D/2a84c8fc535ee8ad0496f3fbd2e30de855881f31/Effects/InnerPixel.xnb -------------------------------------------------------------------------------- /Effects/Texture.fx: -------------------------------------------------------------------------------- 1 | float4x4 World; 2 | float4x4 View; 3 | float4x4 Projection; 4 | 5 | texture _MainTex; 6 | sampler2D _MainTexSampler = sampler_state 7 | { 8 | Texture = (_MainTex); 9 | MinFilter = Point; 10 | MagFilter = Point; 11 | AddressU = Clamp; 12 | AddressV = Clamp; 13 | }; 14 | 15 | 16 | struct VertexShaderInput 17 | { 18 | float4 Position : POSITION0; 19 | float2 UV : TEXCOORD0; 20 | }; 21 | 22 | struct VertexShaderOutput 23 | { 24 | float4 Position : POSITION0; 25 | float2 UV : TEXCOORD0; 26 | }; 27 | 28 | VertexShaderOutput VertexShaderFunction(VertexShaderInput input) 29 | { 30 | VertexShaderOutput output; 31 | float4 worldPosition = mul(input.Position, World); 32 | float4 viewPosition = mul(worldPosition, View); 33 | output.Position = mul(viewPosition, Projection); 34 | output.UV = input.UV; 35 | return output; 36 | } 37 | 38 | 39 | float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0 40 | { 41 | float4 color = tex2D(_MainTexSampler, input.UV); 42 | //color.a *= 0.5; 43 | if (color.r == 0 && color.g == 0 && color.b == 0 && color.a == 0) 44 | clip(-1); 45 | return color; 46 | } 47 | 48 | technique Technique1 49 | { 50 | pass Pass1 51 | { 52 | // Premultiplied Alpha 53 | AlphaBlendEnable = True; 54 | SrcBlend = One; 55 | DestBlend = InvSrcAlpha; 56 | 57 | VertexShader = compile vs_2_0 VertexShaderFunction(); 58 | PixelShader = compile ps_2_0 PixelShaderFunction(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Effects/Texture.xnb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/prgmatic/Terraria3D/2a84c8fc535ee8ad0496f3fbd2e30de855881f31/Effects/Texture.xnb -------------------------------------------------------------------------------- /Geometry/PixelGrid.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Graphics; 3 | 4 | namespace Terraria3D 5 | { 6 | public class PixelGrid 7 | { 8 | public static VertexPositionNormalTexture[] Create(int width, int height, int targetWidth, int targetHeight) 9 | { 10 | int columns = width + 1; 11 | int rows = height + 1; 12 | 13 | float maxXUV = (float)width / targetWidth; 14 | float maxYUV = (float)height / targetHeight; 15 | 16 | int vertCount = columns * 6 + rows * 6; 17 | 18 | var result = new VertexPositionNormalTexture[vertCount]; 19 | 20 | int index = 0; 21 | for (int x = 0; x < columns; x++) 22 | { 23 | result[index + 0].Position = new Vector3(x, 0, 0); 24 | result[index + 1].Position = new Vector3(x, 0, -1); 25 | result[index + 2].Position = new Vector3(x, height, -1); 26 | 27 | result[index + 3].Position = new Vector3(x, 0, 0); 28 | result[index + 4].Position = new Vector3(x, height, -1); 29 | result[index + 5].Position = new Vector3(x, height, 0); 30 | for (int i = 0; i < 6; i++) 31 | { 32 | result[index + i].Normal = Vector3.Right; 33 | float y = result[index + i].Position.Y > 0.0001f ? maxYUV : 0; 34 | result[index + i].TextureCoordinate = new Vector2((float)x / targetWidth, maxYUV - y); 35 | System.Console.WriteLine(result[index + i].TextureCoordinate); 36 | } 37 | index += 6; 38 | } 39 | 40 | for (int y = 0; y < rows; y++) 41 | { 42 | // flip y 43 | result[index + 0].Position = new Vector3(0, y, 0); 44 | result[index + 1].Position = new Vector3(0, y, -1); 45 | result[index + 2].Position = new Vector3(width, y, -1); 46 | 47 | result[index + 3].Position = new Vector3(0, y, 0); 48 | result[index + 4].Position = new Vector3(width, y, -1); 49 | result[index + 5].Position = new Vector3(width, y, 0); 50 | for (int i = 0; i < 6; i++) 51 | { 52 | result[index + i].Normal = Vector3.Down; 53 | float x = result[index + i].Position.X > 0.0001f ? maxXUV : 0; 54 | result[index + i].TextureCoordinate = new Vector2(x, (float)(height - y) / targetHeight); 55 | } 56 | index += 6; 57 | } 58 | return result; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Geometry/Quad.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Graphics; 3 | 4 | namespace Terraria3D 5 | { 6 | public class Quad 7 | { 8 | public static VertexPositionTexture[] Create() 9 | { 10 | var result = new VertexPositionTexture[6]; 11 | 12 | result[0].Position = new Vector3(-0.5f, -0.5f, 0); 13 | result[1].Position = new Vector3(-0.5f, 0.5f, 0); 14 | result[2].Position = new Vector3(0.5f, 0.5f, 0); 15 | 16 | result[3].Position = new Vector3(-0.5f, -0.5f, 0); 17 | result[4].Position = new Vector3(0.5f, 0.5f, 0); 18 | result[5].Position = new Vector3(0.5f, -0.5f, 0); 19 | 20 | result[0].TextureCoordinate = new Vector2(0, 1); 21 | result[1].TextureCoordinate = new Vector2(0, 0); 22 | result[2].TextureCoordinate = new Vector2(1, 0); 23 | 24 | result[3].TextureCoordinate = new Vector2(0, 1); 25 | result[4].TextureCoordinate = new Vector2(1, 0); 26 | result[5].TextureCoordinate = new Vector2(1, 1); 27 | 28 | return result; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Hooks/DrawHooks.cs: -------------------------------------------------------------------------------- 1 | using System.Drawing; 2 | using Microsoft.Xna.Framework.Graphics; 3 | using Terraria; 4 | using Terraria.Graphics.Effects; 5 | using Mono.Cecil.Cil; 6 | using MonoMod.Cil; 7 | using static Microsoft.Xna.Framework.Color; 8 | using System; 9 | using Terraria.ID; 10 | 11 | namespace Terraria3D; 12 | 13 | public static partial class Hooks 14 | { 15 | private static void ApplyDrawHooks() 16 | { 17 | IL_Main.DoDraw += (il) => 18 | { 19 | var cursor = new ILCursor(il); 20 | cursor.Goto(0); 21 | // 22 | //// TODO: add pre render hook back 23 | PreRenderHook(cursor); 24 | DrawSceneHook(cursor); 25 | }; 26 | } 27 | 28 | // HOOK LOCATION: 29 | // This hook is inserted right before the background is drawn and nothing 30 | // has been drawn to the back buffer yet. 31 | 32 | // HOOK FUNCTION: 33 | // This is where we want to start rending 3D layers to their render targets. 34 | 35 | // SOURCE REFERENCE ===================== 36 | // ... 37 | // TimeLogger.DetailedDrawTime(4); 38 | // } 39 | // } 40 | // bgParallax = 0.1; 41 | // 42 | // bgStartX = (int)(0.0 - Math.IEEERemainder((double)screenPosition.X ... 43 | // ====================================== 44 | private static void PreRenderHook(ILCursor cursor) 45 | { 46 | //{IL_14f8: stfld System.Double Terraria.Main::bgParallax} 47 | // Find TimeLogger.DetailedDrawTime(4) call. 48 | if (cursor.TryGotoNext(i => i.MatchCallvirt("Clear"))) 49 | { 50 | cursor.Index += 1; 51 | // Render layers to targets 52 | cursor.EmitDelegate(() => 53 | { 54 | if (Terraria3D.Enabled) 55 | Terraria3D.Instance.RenderLayersTargets(); 56 | }); 57 | } 58 | } 59 | 60 | // HOOK LOCATION: 61 | // This is a two part hook. Pre draw scene and post draw scene. 62 | // Pre draw scene: Right after the bg is drawn to the back buffer. 63 | // Post draw scene: After world space UI is drawn to the screen. 64 | 65 | // HOOK FUNCTION: 66 | // We inject a branch into in the pre draw hook that allows us to 67 | // jump to the post draw hook. This allows us to skip drawing the 68 | // scene in 2D. The post draw scene is where we render our scene 69 | // if UI is visible. We want to draw the 3D scene here so the 70 | // it does no occlude the user interface. 71 | 72 | // SOURCE REFERENCE ===================== 73 | // Main.spriteBatch.End(); 74 | // Overlays.Scene.Draw(Main.spriteBatch, RenderLayers.Landscape, true); 75 | // 76 | // Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendS 77 | // ====================================== 78 | 79 | // SOURCE REFERENCE ===================== 80 | // Main.spriteBatch.End(); 81 | // 82 | // Main.spriteBatch.Begin(SpriteSortM ... 83 | // PlayerInput.SetZoom_UI(); 84 | // this.DrawFPS(); 85 | // ====================================== 86 | public static void DrawSceneHook(ILCursor cursor) 87 | { 88 | // Find Overlays.Scene.Draw(Main.spriteBatch, RenderLayers.Landscape, true) call. 89 | if (cursor.TryGotoNext(i => i.MatchLdcI4(1), 90 | i => i.MatchLdcI4(1), 91 | i => i.MatchCallvirt("Draw"))) 92 | { 93 | // Move to after Scene.Draw 94 | cursor.Index += 3; 95 | // Make a new cursor so we keep track of where we currently are 96 | var cursor2 = new ILCursor(cursor); 97 | 98 | // Find this.DrawInterface(gameTime) call and then the spriteBatch.End() 99 | // preceding it. 100 | if (cursor2.TryGotoNext(i => i.MatchCall
("DrawInterface")) && 101 | cursor2.TryGotoPrev(i => i.MatchCallvirt("End"))) 102 | { 103 | // Move to after spriteBatch.End(); 104 | cursor2.Index++; 105 | // Inject a method that draws the 3D scene. 106 | cursor2.EmitDelegate(() => 107 | { 108 | // Render the 3D scene 109 | if (Terraria3D.Enabled) 110 | Terraria3D.Instance.DrawScene(); 111 | }); 112 | // Move cursor to the starting instruction of our 113 | // newly injected code. 114 | cursor2.Index -= 4; 115 | 116 | // Back at our original cursor, we inject a branch. 117 | // If we want to skip drawing 2D, we jump the functions 118 | // that we just created with cursor 2. 119 | cursor.EmitDelegate(() => 120 | { 121 | // TODO: Fix end capture 122 | var result = Terraria3D.Enabled && !Main.gameMenu && !Main.mapFullscreen; 123 | if (result && !Main.drawToScreen && Main.netMode != NetmodeID.Server && !Main.gameMenu && !Main.mapFullscreen && Lighting.NotRetro && Filters.Scene.CanCapture()) 124 | Filters.Scene.EndCapture(null, Main.screenTarget, Main.screenTargetSwap, Black); 125 | return result; 126 | }); 127 | cursor.Emit(OpCodes.Brtrue_S, cursor2.Next); 128 | } 129 | } 130 | } 131 | } -------------------------------------------------------------------------------- /Hooks/DrawTileHooks.cs: -------------------------------------------------------------------------------- 1 | using Mono.Cecil.Cil; 2 | using MonoMod.Cil; 3 | using System; 4 | using System.Reflection; 5 | using Mono.Cecil; 6 | using Terraria.GameContent.Drawing; 7 | using Terraria; 8 | 9 | namespace Terraria3D; 10 | 11 | public static partial class Hooks 12 | { 13 | 14 | // HOOK FUNCTION: 15 | // This hook swaps the first call to TileDrawing.IsTileDrawLayerSolid for 16 | // TileSolidOverrides.IsTileSolid. The original method is a instance method 17 | // so we must remove .ldarg0 before calling .IsTileSolid 18 | 19 | // SOURCE REFERENCE ===================== 20 | // if (!tile.active() || IsTileDrawLayerSolid(tile.type) != solidLayer) 21 | // continue; 22 | // ====================================== 23 | 24 | // IL REFERENCE ========================= 25 | // IL_0223: ldloca.s tile 26 | // IL_0225: call instance bool Terraria.Tile::active() 27 | // IL_022a: brfalse.s IL_0242 28 | // IL_022c: ldarg.0 // REMOVED THIS 29 | // IL_022d: ldloca.s tile 30 | // IL_022f: call instance unsigned int16& Terraria.Tile::get_type() 31 | // IL_0234: ldind.u2 32 | // IL_0235: call instance bool Terraria.GameContent.Drawing.TileDrawing::IsTileDrawLayerSolid(unsigned int16) 33 | // ====== CALL ABOVE GETS REPLACED ======= 34 | // IL_023a: ldarg.1 // solidLayer 35 | // IL_023b: ceq 36 | // IL_023d: ldc.i4.0 37 | // IL_023e: ceq 38 | // IL_0240: br.s IL_0243 39 | // IL_0242: ldc.i4.1 40 | // IL_0243: stloc.s V_22 41 | // ====================================== 42 | public static void ApplyDrawTileHooks() 43 | { 44 | Terraria.GameContent.Drawing.IL_TileDrawing.Draw += (il) => 45 | { 46 | var cursor = new ILCursor(il); 47 | cursor.Goto(0); 48 | 49 | if (cursor.TryGotoNext(i => i.MatchCall("IsTileDrawLayerSolid"))) 50 | { 51 | cursor.Remove(); 52 | cursor.Emit(OpCodes.Call, GetIsSolidTileMethod()); 53 | if (cursor.TryGotoPrev(i => i.MatchLdarg(0))) 54 | cursor.Remove(); 55 | } 56 | 57 | MethodReference GetIsSolidTileMethod() 58 | { 59 | var mBase = typeof(TileSolidOverrides).GetMethod("IsTileSolid", 60 | BindingFlags.Static | BindingFlags.Public); 61 | return cursor.Context.Import(mBase); 62 | } 63 | }; 64 | } 65 | } -------------------------------------------------------------------------------- /Hooks/Hooks.cs: -------------------------------------------------------------------------------- 1 | namespace Terraria3D; 2 | 3 | public static partial class Hooks 4 | { 5 | public static void Initialize() 6 | { 7 | ApplyDrawHooks(); 8 | ApplyMouseHook(); 9 | ApplyDrawTileHooks(); 10 | } 11 | } -------------------------------------------------------------------------------- /Hooks/InputHooks.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Mono.Cecil.Cil; 3 | using MonoMod.Cil; 4 | using System; 5 | using Terraria; 6 | using Terraria.UI; 7 | 8 | namespace Terraria3D; 9 | 10 | public static partial class Hooks 11 | { 12 | private static void ApplyMouseHook() 13 | { 14 | // TODO: Hook should happen after this function is called, not in it 15 | // Can't hook DoUpdate, guessing because I don't have the v0.16 16 | // TerrariaHooks.dll 17 | Terraria.GameContent.IL_PortalHelper.UpdatePortalPoints += (il) => 18 | { 19 | var cursor = new ILCursor(il); 20 | cursor.Goto(0).EmitDelegate(() => 21 | { 22 | if (!Terraria3D.Enabled) return; 23 | Main.mouseX = (int)Cursor3D.MousePos3D.X; 24 | Main.mouseY = (int)Cursor3D.MousePos3D.Y; 25 | }); 26 | }; 27 | 28 | Terraria.UI.On_LegacyGameInterfaceLayer.DrawSelf += (orig, self) => 29 | { 30 | if (InterfaceRendering.Drawing3D) 31 | { 32 | var oldX = Main.mouseX; 33 | var oldY = Main.mouseY; 34 | Main.mouseX = (int)Cursor3D.MousePos3D.X; 35 | Main.mouseY = (int)Cursor3D.MousePos3D.Y; 36 | var result = orig(self); 37 | Main.mouseX = oldX; 38 | Main.mouseY = oldY; 39 | return result; 40 | } 41 | return orig(self); 42 | }; 43 | 44 | Terraria.UI.On_GameInterfaceLayer.Draw += (orig, self) => 45 | { 46 | if (!Terraria3D.Enabled || InterfaceRendering.Drawing3D) return orig(self); 47 | if (self.Name.Equals("Vanilla: Mouse Over") || 48 | self.Name.Equals("Vanilla: Interface Logic 4")) 49 | { 50 | var oldX = Main.mouseX; 51 | var oldY = Main.mouseY; 52 | Main.mouseX = (int)Cursor3D.MousePos3D.X; 53 | Main.mouseY = (int)Cursor3D.MousePos3D.Y; 54 | var result = orig(self); 55 | Main.mouseX = oldX; 56 | Main.mouseY = oldY; 57 | return result; 58 | } 59 | else if (self.ScaleType == InterfaceScaleType.Game) 60 | return !Main.hideUI; 61 | return orig(self); 62 | }; 63 | 64 | Terraria.IL_Main.DrawMouseOver += (il) => 65 | { 66 | var cursor = new ILCursor(il); 67 | cursor.Goto(0); 68 | 69 | if(cursor.TryGotoNext(i => i.MatchCall("MouseOver"))) 70 | { 71 | cursor.Index++; 72 | 73 | // Modify X component 74 | cursor.Emit(OpCodes.Ldloca_S, il.Body.Variables[0]); 75 | cursor.EmitDelegate>(() => 76 | { 77 | return (int)(Cursor3D.MousePos3D.X + Main.screenPosition.X); 78 | }); 79 | var x = il.Module.ImportReference(typeof(Rectangle).GetField("X")); 80 | cursor.Emit(OpCodes.Stfld, x); 81 | 82 | // Modify Y component 83 | cursor.Emit(OpCodes.Ldloca_S, il.Body.Variables[0]); 84 | cursor.EmitDelegate>(() => 85 | { 86 | if (Main.player[Main.myPlayer].gravDir == -1f) 87 | return (int)(Main.screenPosition.Y + Main.screenHeight - Cursor3D.MousePos3D.Y); 88 | return (int)(Cursor3D.MousePos3D.Y + Main.screenPosition.Y); 89 | }); 90 | var y = il.Module.ImportReference(typeof(Rectangle).GetField("Y")); 91 | cursor.Emit(OpCodes.Stfld, y); 92 | } 93 | }; 94 | } 95 | } -------------------------------------------------------------------------------- /Hooks/WaterHooks.cs: -------------------------------------------------------------------------------- 1 | using Terraria; 2 | using System; 3 | using Microsoft.Xna.Framework.Graphics; 4 | using System.Linq; 5 | using Mono.Cecil.Cil; 6 | using MonoMod.Cil; 7 | 8 | namespace Terraria3D; 9 | 10 | public static class WaterHooks 11 | { 12 | public static void ApplyWaterHook() 13 | { 14 | IL_Main.DrawTiles += (il) => 15 | { 16 | var loadTextureInstruction = il.Body.Instructions.FirstOrDefault(i => i != null && i.Operand != null && i.Operand.ToString() == "Microsoft.Xna.Framework.Graphics.Texture2D[] Terraria.Main::liquidTexture"); 17 | if (loadTextureInstruction != null) 18 | { 19 | var preDrawWaterCursor = new ILCursor(il); 20 | preDrawWaterCursor.Goto(loadTextureInstruction); 21 | preDrawWaterCursor.Index--; 22 | 23 | var preSetupWaterTileCursor = new ILCursor(preDrawWaterCursor); 24 | if(preSetupWaterTileCursor.TryGotoPrev(i => i.MatchLdarg(1))) 25 | { 26 | var jumpToWaterDrawCursor = new ILCursor(il); 27 | jumpToWaterDrawCursor.Goto(0); 28 | 29 | if (jumpToWaterDrawCursor.TryGotoNext(i => i.MatchCallvirt("active")) && 30 | jumpToWaterDrawCursor.TryGotoNext(i => i.OpCode == OpCodes.Bne_Un)) 31 | { 32 | jumpToWaterDrawCursor.Index++; 33 | jumpToWaterDrawCursor.EmitDelegate>(() => 34 | { 35 | // TODO: Fix Rendering Call 36 | 37 | // if (Rendering.RenderHalfBlockWaterHack) 38 | // Main.NewText("jump to water!"); 39 | //return Rendering.RenderHalfBlockWaterHack; 40 | 41 | return false; 42 | }); 43 | jumpToWaterDrawCursor.Emit(OpCodes.Brtrue_S, preSetupWaterTileCursor.Next); 44 | } 45 | } 46 | 47 | var postDrawWaterCursor = new ILCursor(preDrawWaterCursor); 48 | if (postDrawWaterCursor.TryGotoNext(i => i.MatchCallvirt("Draw"))) 49 | { 50 | postDrawWaterCursor.Index++; 51 | // TODO: Fix rendering call 52 | //preDrawWaterCursor.EmitDelegate>(() => Rendering.RenderHalfBlockWaterHack); 53 | preDrawWaterCursor.Emit(OpCodes.Brfalse_S, postDrawWaterCursor.Next); 54 | } 55 | } 56 | }; 57 | } 58 | } -------------------------------------------------------------------------------- /Images/CameraIcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/prgmatic/Terraria3D/2a84c8fc535ee8ad0496f3fbd2e30de855881f31/Images/CameraIcon.png -------------------------------------------------------------------------------- /Images/Noise.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/prgmatic/Terraria3D/2a84c8fc535ee8ad0496f3fbd2e30de855881f31/Images/Noise.png -------------------------------------------------------------------------------- /Input/CameraDriverBindings.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework.Input; 2 | using Terraria; 3 | using Terraria.GameInput; 4 | 5 | namespace Terraria3D; 6 | 7 | public partial class CameraDriver 8 | { 9 | private static AxisBindings _forwardAxisInput = new AxisBindings("Up", "Down"); 10 | private static AxisBindings _rightAxisInput = new AxisBindings("Right", "Left"); 11 | private static AxisKeys _upAxisInput = new AxisKeys(Keys.E, Keys.Q); 12 | private static Keys _resetKey = Keys.F; 13 | 14 | abstract class Axis 15 | { 16 | public T Positive { get; set; } 17 | public T Negative { get; set; } 18 | 19 | public Axis(T positive, T negative) 20 | { 21 | Positive = positive; 22 | Negative = negative; 23 | } 24 | public abstract float GetValue(); 25 | } 26 | 27 | private class AxisBindings : Axis 28 | { 29 | public AxisBindings(string positive, string negative) : base(positive, negative) { } 30 | 31 | public override float GetValue() 32 | { 33 | float result = 0; 34 | if (PlayerInput.Triggers.Current.KeyStatus[Negative]) result -= 1; 35 | if (PlayerInput.Triggers.Current.KeyStatus[Positive]) result += 1; 36 | return result; 37 | } 38 | } 39 | 40 | private class AxisKeys : Axis 41 | { 42 | public AxisKeys(Keys positive, Keys negative) : base(positive, negative) { } 43 | 44 | public override float GetValue() 45 | { 46 | float result = 0; 47 | if (Main.keyState.IsKeyDown(Negative)) result -= 1; 48 | if (Main.keyState.IsKeyDown(Positive)) result += 1; 49 | return result; 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /Input/Cursor3D.cs: -------------------------------------------------------------------------------- 1 | using Terraria; 2 | using Microsoft.Xna.Framework; 3 | using System.Linq; 4 | 5 | namespace Terraria3D; 6 | 7 | public static class Cursor3D 8 | { 9 | private static Plane _tilePlane = new Plane(Vector3.Backward, 0); 10 | public static Vector2 MousePos3D { get; private set; } 11 | 12 | public static void UpdateMousePos3D() => MousePos3D = Get3DScreenPos(); 13 | 14 | public static Vector2 Get3DScreenPos() 15 | => Get3DScreenPos(Terraria3D.Instance.Scene.Camera, Terraria3D.Instance.Scene.ModelTransform.LocalToWorld); 16 | 17 | public static Vector2 Get3DScreenPos(Camera camera, Matrix modelMatrix) 18 | { 19 | return Get3DScreenPos(camera, Main.MouseScreen * Main.UIScale, modelMatrix); 20 | } 21 | 22 | public static Vector2 Get3DScreenPos(Camera camera, Vector2 mousePos, Matrix modelMatrix) 23 | { 24 | var layers = Terraria3D.Instance.LayerManager.Layers; 25 | var solidLayer = layers.FirstOrDefault(l => l.InputPlane == Layer3D.InputPlaneType.SolidTiles); 26 | var nonSolidLayer = layers.FirstOrDefault(l => l.InputPlane == Layer3D.InputPlaneType.NoneSolidTiles); 27 | 28 | if (solidLayer == null || nonSolidLayer == null) 29 | return Vector2.Zero; 30 | 31 | // Find intersection with front plane 32 | SetTilePlaneDistance(solidLayer.Depth, solidLayer.ZPos, modelMatrix); 33 | var ray = camera.ScreenPointToRay(new Vector2(mousePos.X, mousePos.Y)); 34 | var invMatrix = Matrix.Invert(modelMatrix); 35 | 36 | var intersectPos = GetPlaneIntersectOnScreen(ray, invMatrix); 37 | if (intersectPos.HasValue) 38 | { 39 | var iPos = new Vector2(intersectPos.Value.X, intersectPos.Value.Y); 40 | 41 | // Check tile under current position. If there is no collision, 42 | // hop to the back plane 43 | Vector2 tilePos = (Main.screenPosition + iPos) / 16; 44 | if (TileOnScreen(tilePos)) 45 | { 46 | if (!TileIsCollider(tilePos)) 47 | { 48 | SetTilePlaneDistance(nonSolidLayer.Depth, nonSolidLayer.ZPos, modelMatrix); 49 | intersectPos = GetPlaneIntersectOnScreen(ray, invMatrix); 50 | if (intersectPos.HasValue) 51 | iPos = new Vector2(intersectPos.Value.X, intersectPos.Value.Y); 52 | } 53 | } 54 | return iPos; 55 | } 56 | return Vector2.Zero; 57 | } 58 | 59 | private static void SetTilePlaneDistance(float depth, float zPos, Matrix matrix) 60 | => _tilePlane.D = Vector3.Transform(Vector3.Forward * (depth - zPos), matrix).Z; 61 | 62 | // Apply matrix and flip y 63 | private static Vector2? GetPlaneIntersectOnScreen(Ray ray, Matrix? matrix) 64 | { 65 | var intersect = GetPlaneIntersectPosition(ray); 66 | if (intersect.HasValue) 67 | { 68 | var r = new Vector2(intersect.Value.X, intersect.Value.Y); 69 | if (matrix.HasValue) 70 | r = Vector2.Transform(r, matrix.Value); 71 | r.Y = Screen.Height - r.Y; 72 | return r; 73 | } 74 | return null; 75 | } 76 | 77 | private static Vector3? GetPlaneIntersectPosition(Ray ray) 78 | { 79 | var dist = ray.Intersects(_tilePlane); 80 | if (dist.HasValue) 81 | return ray.Position + ray.Direction * dist.Value; 82 | return null; 83 | } 84 | 85 | private static bool TileOnScreen(Vector2 tilePos) 86 | { 87 | return tilePos.X > 0 && tilePos.X < Main.maxTilesX && 88 | tilePos.Y > 0 && tilePos.Y < Main.maxTilesY; 89 | } 90 | 91 | private static bool TileIsCollider(Vector2 tilePos) 92 | { 93 | // TODO: find alternative for tile.collisionType 94 | Tile tile = Main.tile[(int)tilePos.X, (int)tilePos.Y]; 95 | return tile != null && tile.HasTile && Main.tileSolid[tile.TileType]; 96 | } 97 | } -------------------------------------------------------------------------------- /Input/InputTerraria3D.cs: -------------------------------------------------------------------------------- 1 | using Terraria; 2 | using Terraria.ModLoader; 3 | 4 | namespace Terraria3D; 5 | 6 | public class InputTerraria3D 7 | { 8 | public static bool CameraControlsEnabled { get; set; } 9 | 10 | private static ModKeybind _settingsKeyBinding; 11 | private static ModKeybind _toggleCameraControlsKeyBinding; 12 | private static ModKeybind _toggle3DKeyBinding; 13 | private static ModKeybind _toggleAOBinding; 14 | 15 | public static void Load() 16 | { 17 | // Why 'L'? No clue, I hope it's not already bound to something xD 18 | _settingsKeyBinding = KeybindLoader.RegisterKeybind(Terraria3D.Instance, "Toggle 3D Settings", "L"); 19 | _toggleCameraControlsKeyBinding = KeybindLoader.RegisterKeybind(Terraria3D.Instance, "Toggle Camera Controls", "C"); 20 | _toggle3DKeyBinding = KeybindLoader.RegisterKeybind(Terraria3D.Instance, "Toggle 3D", "K"); 21 | if (Renderers.SM3Enabled) 22 | _toggleAOBinding = KeybindLoader.RegisterKeybind(Terraria3D.Instance, "Toggle AO", "None"); 23 | } 24 | 25 | public static void Unload() 26 | { 27 | _settingsKeyBinding = null; 28 | _toggleCameraControlsKeyBinding = null; 29 | _toggle3DKeyBinding = null; 30 | _toggleAOBinding = null; 31 | } 32 | 33 | public static void Update() 34 | { 35 | Cursor3D.UpdateMousePos3D(); 36 | } 37 | 38 | public static void SetControls(Player player) 39 | { 40 | // If driving the camera, consume player movement 41 | // events. 42 | if (Terraria3D.Enabled && CameraControlsEnabled) 43 | { 44 | player.controlLeft = false; 45 | player.controlRight = false; 46 | player.controlUp = false; 47 | player.controlDown = false; 48 | 49 | player.controlUseItem = false; 50 | player.controlThrow = false; 51 | 52 | player.controlHook = false; 53 | player.controlQuickHeal = false; 54 | player.controlQuickMana = false; 55 | 56 | player.mouseInterface = true; 57 | player.lastMouseInterface = true; 58 | } 59 | } 60 | 61 | public static void ProcessInput() 62 | { 63 | if (_toggle3DKeyBinding.JustPressed) 64 | Terraria3D.Instance.Toggle(); 65 | if (_settingsKeyBinding.JustPressed) 66 | UITerraria3D.SettingsInterface.Visible = !UITerraria3D.SettingsInterface.Visible; 67 | if (!Terraria3D.Enabled) return; 68 | if (_toggleCameraControlsKeyBinding.JustPressed) 69 | CameraControlsEnabled = !CameraControlsEnabled; 70 | if (Renderers.SM3Enabled) 71 | { 72 | if (_toggleAOBinding.JustPressed) 73 | Terraria3D.Instance.Scene.AmbientOcclusion = !Terraria3D.Instance.Scene.AmbientOcclusion; 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Localization/en-US_Mods.Terraria3D.hjson: -------------------------------------------------------------------------------- 1 | Keybinds: { 2 | "Toggle 3D Settings.DisplayName": Toggle 3 D Settings 3 | "Toggle 3D.DisplayName": Toggle 3 D 4 | "Toggle Camera Controls.DisplayName": Toggle Camera Controls 5 | "Toggle AO.DisplayName": Toggle A O 6 | } 7 | -------------------------------------------------------------------------------- /Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "Terraria": { 4 | "commandName": "Executable", 5 | "executablePath": "dotnet", 6 | "commandLineArgs": "$(tMLPath)", 7 | "workingDirectory": "$(tMLSteamPath)" 8 | }, 9 | "TerrariaServer": { 10 | "commandName": "Executable", 11 | "executablePath": "dotnet", 12 | "commandLineArgs": "$(tMLServerPath)", 13 | "workingDirectory": "$(tMLSteamPath)" 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Terraria3D - Alpha (WIP) 2 | ![Screenshot](https://i.imgur.com/c2JSdYU.png) 3 | 4 | Terraria3D is a mod that adds a little more depth to your world. This mod is installed via tModLoader. You can find it in the Mod Browser. Please report issues to the [issue tracker](https://github.com/chatrat12/Terraria3D/issues). 5 | 6 | Join our [discord](https://discord.gg/3QdTHrV)! 7 | ## Usage 8 | This mod requires tModLoader 0.11.3 and can be found in the Mod Browser. 9 | 10 | Once in game, you’ll need pick hot-keys for toggle 3D, open settings window, and toggle camera control in the Controls part of Settings. 11 | 12 | To move the camera press the 'Toggle Camera Controls' key or open your inventory and click the camera icon on bottom left of the screen. 13 | 14 | ## Special Thanks 15 | Special thanks to [0x0ade](https://github.com/0x0ade) for creating [MonoMod](https://monomod.dev/)/[TerrariaHooks](https://github.com/0x0ade/TerrariaHooks) and for creating a fix for SM3. Without TerrariaHooks, Terraria3D would not be possible on tML. 16 | 17 | I would also like to thank everyone who has helped test the mod, report bugs, and being all around chill people. 18 | 19 | ## Disclaimer 20 | The mod is still a work in progress. There is more I would like to polish and you may come across some things that are broken. Bug reports are appreciated :D 21 | 22 | ## Future features 23 | - User ability to define layers and what is rendered on them 24 | -------------------------------------------------------------------------------- /Rendering/CapRenderer.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Graphics; 3 | 4 | namespace Terraria3D; 5 | 6 | public class CapRenderer 7 | { 8 | private GraphicsDevice _graphicsDevice => Terraria.Main.graphics.GraphicsDevice; 9 | 10 | private Effect _effect; 11 | private VertexBuffer _buffer; 12 | 13 | public CapRenderer(Effect effect) 14 | { 15 | _effect = effect; 16 | var quad = Quad.Create(); 17 | _buffer = new VertexBuffer(_graphicsDevice, VertexPositionTexture.VertexDeclaration, quad.Length, BufferUsage.WriteOnly); 18 | _buffer.SetData(quad); 19 | } 20 | 21 | public void Dispose() 22 | { 23 | _buffer?.Dispose(); 24 | } 25 | 26 | public void Draw(Texture texture, Camera camera, Matrix matrix) 27 | { 28 | _effect.Parameters["World"].SetValue(matrix); 29 | _effect.Parameters["View"].SetValue(camera.View); 30 | _effect.Parameters["Projection"].SetValue(camera.Projection); 31 | _effect.Parameters["_MainTex"].SetValue(texture); 32 | 33 | foreach(var pass in _effect.CurrentTechnique.Passes) 34 | { 35 | pass.Apply(); 36 | _graphicsDevice.SetVertexBuffer(_buffer); 37 | _graphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2); 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /Rendering/GridRenderer.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Graphics; 3 | using Terraria; 4 | 5 | namespace Terraria3D; 6 | 7 | public class GridRenderer 8 | { 9 | private GraphicsDevice _graphicsDevice => Terraria.Main.graphics.GraphicsDevice; 10 | 11 | private Effect _effect; 12 | private Texture _noiseTexture; 13 | private VertexPositionNormalTexture[] _grid; 14 | private VertexBuffer _gridBuffer; 15 | private float _width; 16 | private float _height; 17 | 18 | public GridRenderer(Effect effect, Texture noiseTexture, int width, int height, int targetWidth, int targetHeight) 19 | { 20 | _effect = effect; 21 | _noiseTexture = noiseTexture; 22 | _width = width; 23 | _height = height; 24 | 25 | SetGridSize(width, height, targetWidth, targetHeight); 26 | _effect.Parameters["NoiseTexture"].SetValue(_noiseTexture); 27 | } 28 | 29 | public void Dispose() 30 | { 31 | //_effect?.Dispose(); 32 | _noiseTexture?.Dispose(); 33 | _gridBuffer?.Dispose(); 34 | } 35 | 36 | public void SetGridSize(int width, int height, int targetWidth, int targetHeight) 37 | { 38 | _grid = PixelGrid.Create(width, height, targetWidth, targetHeight); 39 | _gridBuffer?.Dispose(); 40 | _gridBuffer = new VertexBuffer(_graphicsDevice, VertexPositionNormalTexture.VertexDeclaration, _grid.Length, BufferUsage.WriteOnly); 41 | _gridBuffer.SetData(_grid); 42 | } 43 | 44 | public void Draw(Texture2D texture, Camera camera, float depth, float noiseAmount = 1, bool ao = true, Matrix? modelMatrix = null) 45 | { 46 | if (modelMatrix == null) 47 | modelMatrix = Matrix.Identity; 48 | 49 | 50 | _effect.Parameters["View"].SetValue(camera.View); 51 | _effect.Parameters["Projection"].SetValue(camera.Projection); 52 | _effect.Parameters["_MainTex"].SetValue(texture); 53 | _effect.Parameters["PixelOffset"].SetValue(new Vector2(1f / texture.Width, 1f / texture.Height)); 54 | _effect.Parameters["World"].SetValue(modelMatrix.Value); 55 | _effect.Parameters["Depth"].SetValue(depth); 56 | _effect.Parameters["NoiseAmount"].SetValue(noiseAmount); 57 | _effect.Parameters["CameraPosition"].SetValue(new Vector2(-Main.screenPosition.X, Main.screenPosition.Y + 1)); 58 | if (Renderers.SM3Enabled) 59 | _effect.Parameters["AO"].SetValue(ao); 60 | 61 | // Read from z buffer when determining the what pixel to render on top 62 | _graphicsDevice.DepthStencilState = DepthStencilState.Default; 63 | _graphicsDevice.BlendState = BlendState.AlphaBlend; 64 | 65 | foreach (var pass in _effect.CurrentTechnique.Passes) 66 | { 67 | pass.Apply(); 68 | _graphicsDevice.SetVertexBuffer(_gridBuffer); 69 | _graphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, _grid.Length / 3); 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /Rendering/InnerPixelRenderer.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Graphics; 3 | using Terraria; 4 | 5 | namespace Terraria3D; 6 | 7 | public class InnerPixelRenderer 8 | { 9 | private GraphicsDevice _graphicsDevice => Main.graphics.GraphicsDevice; 10 | private Effect _effect; 11 | 12 | public InnerPixelRenderer(Effect effect) { _effect = effect; } 13 | 14 | public void Dispose() 15 | { 16 | //_effect?.Dispose(); 17 | } 18 | 19 | public void Draw(RenderTarget2D target, Texture2D texture) 20 | { 21 | _graphicsDevice.SetRenderTarget(target); 22 | _graphicsDevice.Clear(Color.Transparent); 23 | Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointWrap, null, null); 24 | _effect.Parameters["PixelOffset"].SetValue(new Vector2(1f / texture.Width, 1f / texture.Height)); 25 | 26 | foreach (var pass in _effect.CurrentTechnique.Passes) 27 | { 28 | pass.Apply(); 29 | Main.spriteBatch.Draw(texture, Vector2.Zero, Color.White); 30 | } 31 | Main.spriteBatch.End(); 32 | _graphicsDevice.SetRenderTarget(null); 33 | } 34 | } -------------------------------------------------------------------------------- /Rendering/InterfaceRendering.cs: -------------------------------------------------------------------------------- 1 |  2 | using Microsoft.Xna.Framework.Graphics; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using Terraria; 6 | using Terraria.UI; 7 | 8 | namespace Terraria3D; 9 | 10 | public static class InterfaceRendering 11 | { 12 | public static bool Drawing3D { get; private set; } = false; 13 | 14 | public static void RenderGameInterfaces() 15 | { 16 | if (Main.hideUI) return; 17 | Drawing3D = true; 18 | Main.spriteBatch.End(); 19 | var layers = Reflection.GameInterfaceLayers; 20 | if (layers != null) 21 | { 22 | layers = new List(Reflection.GameInterfaceLayers); 23 | foreach (var layer in layers.Where(i => i.ScaleType == InterfaceScaleType.Game) 24 | .Where(i => i.Name != "Vanilla: Mouse Over" && 25 | i.Name != "Vanilla: Interface Logic 4")) 26 | { 27 | layer.Draw(); 28 | } 29 | } 30 | Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullNone, null, Main.Transform); 31 | Drawing3D = false; 32 | } 33 | } -------------------------------------------------------------------------------- /Rendering/RTManager.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Graphics; 3 | 4 | namespace Terraria3D; 5 | 6 | public static class RTManager 7 | { 8 | // I broke NPoT when implementing PoT, may revisit. 9 | private const bool FORCE_POT = false; 10 | 11 | public delegate void ResolutionChangedEvent(int width, int height, int rtWidth, int rtHeight); 12 | public static event ResolutionChangedEvent ResolutionChanged; 13 | 14 | public static bool UsingPoT { get; private set; } = true; 15 | public static int Width { get; private set; } 16 | public static int Height { get; private set; } 17 | 18 | 19 | public static void Load() 20 | { 21 | UsingPoT = (FORCE_POT || Reflection.CurrentGraphicsProfile == GraphicsProfile.Reach); 22 | 23 | UpdateDimensions(); 24 | Terraria.Main.OnResolutionChanged += MainResolutionChanged; 25 | } 26 | 27 | public static void Unload() 28 | => Terraria.Main.OnResolutionChanged -= MainResolutionChanged; 29 | 30 | private static void UpdateDimensions() 31 | { 32 | Width = Screen.Width; 33 | Height = Screen.Height; 34 | if (UsingPoT) 35 | { 36 | Width = Utils.GetSmallestPoT(Width); 37 | Height = Utils.GetSmallestPoT(Height); 38 | } 39 | } 40 | 41 | private static void MainResolutionChanged(Vector2 size) 42 | { 43 | UpdateDimensions(); 44 | ResolutionChanged?.Invoke(Screen.Width, Screen.Height, Width, Height); 45 | } 46 | } -------------------------------------------------------------------------------- /Rendering/Reflection.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework.Graphics; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | using Terraria; 5 | using Terraria.ModLoader; 6 | using Terraria.UI; 7 | 8 | namespace Terraria3D; 9 | 10 | public static class Reflection 11 | { 12 | private static FieldInfo _currentGraphicsProfile => GetField("_currentGraphicsProfile", BindingFlags.Static); 13 | private static FieldInfo _gameInterfaceLayers => GetField("_gameInterfaceLayers", BindingFlags.Instance); 14 | 15 | private static MethodInfo _drawWaters = GetMethod("DrawWaters", BindingFlags.Instance); 16 | private static MethodInfo _drawBackground = GetMethod("DrawBackground", BindingFlags.Instance); 17 | private static MethodInfo _cacheNPCDraws = GetMethod("CacheNPCDraws", BindingFlags.Instance); 18 | private static MethodInfo _cacheProjDraws = GetMethod("CacheProjDraws", BindingFlags.Instance); 19 | private static MethodInfo _drawCachedNPCs = GetMethod("DrawCachedNPCs", BindingFlags.Instance); 20 | private static MethodInfo _drawCachedProjs = GetMethod("DrawCachedProjs", BindingFlags.Instance); 21 | private static MethodInfo _drawBlack = GetMethod("DrawBlack", BindingFlags.Instance); 22 | private static MethodInfo _drawWalls = GetMethod("DrawWalls", BindingFlags.Instance); 23 | private static MethodInfo _drawWoF = GetMethod("DrawWoF", BindingFlags.Instance); 24 | private static MethodInfo _drawGoreBehind = GetMethod("DrawGoreBehind", BindingFlags.Instance); 25 | private static MethodInfo _drawTiles = GetMethod("DrawTiles", BindingFlags.Instance); 26 | private static MethodInfo _drawNPCs = GetMethod("DrawNPCs", BindingFlags.Instance); 27 | private static MethodInfo _sortDrawCacheWorms = GetMethod("SortDrawCacheWorms", BindingFlags.Instance); 28 | private static MethodInfo _drawProjectiles = GetMethod("DrawProjectiles", BindingFlags.Instance); 29 | private static MethodInfo _drawPlayersBehindNPCs = GetMethod("DrawPlayers_BehindNPCs", BindingFlags.Instance); 30 | private static MethodInfo _drawWallTilesNPCS = GetMethod("DoDraw_WallsTilesNPCs", BindingFlags.Instance); 31 | private static MethodInfo _drawPlayersAfterProj = GetMethod("DrawPlayers_AfterProjectiles", BindingFlags.Instance); 32 | private static MethodInfo _drawRain = GetMethod("DrawRain", BindingFlags.Instance); 33 | private static MethodInfo _drawGore = GetMethod("DrawGore", BindingFlags.Instance); 34 | private static MethodInfo _drawDust = GetMethod("DrawDust", BindingFlags.Instance); 35 | private static MethodInfo _drawWires = GetMethod("DrawWires", BindingFlags.Instance); 36 | private static MethodInfo _drawPlayerChatBubbles = GetMethod("DrawPlayerChatBubbles", BindingFlags.Instance); 37 | private static MethodInfo _drawItemTextPopups = GetMethod("DrawItemTextPopups", BindingFlags.NonPublic | BindingFlags.Static); 38 | private static readonly object[] _itemTextParams = { 2 }; 39 | 40 | 41 | 42 | public static GraphicsProfile CurrentGraphicsProfile => (GraphicsProfile)_currentGraphicsProfile.GetValue(null); 43 | public static List GameInterfaceLayers => 44 | (List)_gameInterfaceLayers.GetValue(Main.instance); 45 | public static void DrawWaters(bool bg = false) 46 | => _drawWaters.Invoke(Main.instance, new object[] { bg }); 47 | 48 | public static void DrawBackground() => _drawBackground.Invoke(Main.instance, null); 49 | public static void CacheNPCDraws() => _cacheNPCDraws.Invoke(Main.instance, null); 50 | public static void CacheProjDraws() => _cacheProjDraws.Invoke(Main.instance, null); 51 | public static void DrawCachedNPCs(List npcCache, bool behindTiles) => _drawCachedNPCs.Invoke(Main.instance, new object[] { npcCache, behindTiles }); 52 | public static void DrawBlack(bool force = false) => _drawBlack.Invoke(Main.instance, new object[] { force }); 53 | public static void DrawWalls() => _drawWalls.Invoke(Main.instance, null); 54 | public static void DrawWoF() => _drawWoF.Invoke(Main.instance, null); 55 | public static void DrawGoreBehind() => _drawGoreBehind.Invoke(Main.instance, null); 56 | public static void DrawTiles(bool solidOnly = true, int waterStyleOverride = -1) 57 | => _drawTiles.Invoke(Main.instance, new object[] { solidOnly, false, true, waterStyleOverride }); 58 | public static void DrawCachedProjs(List projCache, bool startSpriteBatch = true) => _drawCachedProjs.Invoke(Main.instance, new object[] { projCache, startSpriteBatch }); 59 | public static void DrawNPCs(bool behindTiles) => _drawNPCs.Invoke(Main.instance, new object[] { behindTiles }); 60 | public static void SortDrawCashWorms() => _sortDrawCacheWorms.Invoke(Main.instance, null); 61 | public static void DrawProjectiles() => _drawProjectiles.Invoke(Main.instance, null); 62 | public static void DrawPlayersBehindNPCs() => _drawPlayersBehindNPCs.Invoke(Main.instance, null); 63 | public static void DrawWallsTilesNPCs() => _drawWallTilesNPCS.Invoke(Main.instance, null); 64 | public static void DrawPlayersAfterProj() => _drawPlayersAfterProj.Invoke(Main.instance, null); 65 | public static void DrawRain() => _drawRain.Invoke(Main.instance, null); 66 | public static void DrawGore() => _drawGore.Invoke(Main.instance, null); 67 | public static void DrawDust() => _drawDust.Invoke(Main.instance, null); 68 | public static void DrawWires() => _drawWires.Invoke(Main.instance, null); 69 | public static void DrawPlayerChatBubbles() => _drawPlayerChatBubbles.Invoke(Main.instance, null); 70 | public static void DrawItemTextPopups() => _drawItemTextPopups.Invoke(null, _itemTextParams); 71 | 72 | private static FieldInfo GetField(string fieldName, BindingFlags bindingFlags) 73 | => typeof(Main).GetField(fieldName, BindingFlags.NonPublic | bindingFlags); 74 | 75 | private static MethodInfo GetMethod(string methodName, BindingFlags bindingFlags) 76 | => typeof(Main).GetMethod(methodName, BindingFlags.NonPublic | bindingFlags); 77 | } -------------------------------------------------------------------------------- /Rendering/Renderers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Xna.Framework.Graphics; 3 | using ReLogic.Content; 4 | using Terraria; 5 | using Terraria.ModLoader; 6 | 7 | namespace Terraria3D; 8 | 9 | public static class Renderers 10 | { 11 | public static GridRenderer GridRenderer { get; private set; } 12 | public static CapRenderer CapRenderer { get; private set; } 13 | public static InnerPixelRenderer InnerPixelRenderer { get; private set; } 14 | public static bool SM3Enabled => Main.graphics.GraphicsProfile == GraphicsProfile.HiDef; 15 | 16 | private static Effect _gridEffect => SM3Enabled ? GetEffect("Terraria3D/Effects/HiDef/Grid") : GetEffect("Terraria3D/Effects/Grid"); 17 | 18 | 19 | public static void Load() 20 | { 21 | RTManager.Load(); 22 | GridRenderer = new GridRenderer(_gridEffect, GetTexture("Terraria3D/Images/Noise"), Screen.Width, Screen.Height, RTManager.Width, RTManager.Height); 23 | CapRenderer = new CapRenderer(GetEffect("Terraria3D/Effects/Texture")); 24 | InnerPixelRenderer = new InnerPixelRenderer(GetEffect("Terraria3D/Effects/InnerPixel")); 25 | RTManager.ResolutionChanged += ResolutionChanged; 26 | } 27 | 28 | public static void Unload() 29 | { 30 | GridRenderer?.Dispose(); 31 | CapRenderer?.Dispose(); 32 | InnerPixelRenderer?.Dispose(); 33 | 34 | GridRenderer = null; 35 | CapRenderer = null; 36 | InnerPixelRenderer = null; 37 | 38 | RTManager.ResolutionChanged -= ResolutionChanged; 39 | RTManager.Unload(); 40 | } 41 | 42 | private static Effect GetEffect(string name) 43 | => ModContent.Request(name, AssetRequestMode.ImmediateLoad).Value; 44 | private static Texture2D GetTexture(string name) 45 | => ModContent.Request(name, AssetRequestMode.ImmediateLoad).Value; 46 | private static void ResolutionChanged(int w, int h, int rtW, int rtH) => GridRenderer.SetGridSize(w, h, rtW, rtH); 47 | } -------------------------------------------------------------------------------- /Rendering/Rendering.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Graphics; 3 | using System; 4 | using Terraria; 5 | using Terraria.GameContent.Events; 6 | using Terraria.GameContent.UI; 7 | using Terraria.GameContent; 8 | using ReLogic.Graphics; 9 | 10 | namespace Terraria3D; 11 | 12 | public static class Rendering 13 | { 14 | public static bool RenderHalfBlockWaterHack { get; set; } = false; 15 | 16 | public static void PreRenderSetup() 17 | { 18 | DoLighting(); 19 | UpdateState(); 20 | CacheDraws(); 21 | } 22 | 23 | public static void UpdateState() 24 | { 25 | if (Main.magmaBGFrameCounter >= 8) 26 | { 27 | Main.magmaBGFrameCounter = 0; 28 | Main.magmaBGFrame++; 29 | if (Main.magmaBGFrame >= 3) 30 | { 31 | Main.magmaBGFrame = 0; 32 | } 33 | } 34 | 35 | if (!Main.gamePaused) 36 | { 37 | Main.essScale += (float) Main.essDir * 0.01f; 38 | if (Main.essScale > 1f) 39 | { 40 | Main.essDir = -1; 41 | Main.essScale = 1f; 42 | } 43 | 44 | if ((double) Main.essScale < 0.7) 45 | { 46 | Main.essDir = 1; 47 | Main.essScale = 0.7f; 48 | } 49 | } 50 | } 51 | 52 | public static void DoLighting() 53 | { 54 | var firstTileX = (int) Math.Floor((double) (Main.screenPosition.X / 16f)) - 1; 55 | var lastTileX = (int) Math.Floor((double) ((Main.screenPosition.X + (float) Main.screenWidth) / 16f)) + 2; 56 | var firstTileY = (int) Math.Floor((double) (Main.screenPosition.Y / 16f)) - 1; 57 | var lastTileY = (int) Math.Floor((double) ((Main.screenPosition.Y + (float) Main.screenHeight) / 16f)) + 2; 58 | if (!Main.drawSkip) 59 | { 60 | Lighting.LightTiles(firstTileX, lastTileX, firstTileY, lastTileY); 61 | } 62 | } 63 | 64 | public static void DrawBackgroundWater() 65 | { 66 | if (Main.drawToScreen) 67 | Reflection.DrawWaters(true); 68 | else 69 | { 70 | Main.spriteBatch.Draw(Main.instance.backWaterTarget, Main.sceneBackgroundPos - Main.screenPosition, 71 | Microsoft.Xna.Framework.Color.White); 72 | TimeLogger.DetailedDrawTime(11); 73 | } 74 | } 75 | 76 | public static void DrawSceneBackground() 77 | { 78 | float x = 79 | (Main.sceneBackgroundPos.X - Main.screenPosition.X + (float) Main.offScreenRange) * Main.caveParallax - 80 | (float) Main.offScreenRange; 81 | if (Main.drawToScreen) 82 | { 83 | Main.tileBatch.Begin(); 84 | Reflection.DrawBackground(); 85 | Main.tileBatch.End(); 86 | } 87 | else 88 | Main.spriteBatch.Draw(Main.instance.backgroundTarget, 89 | new Vector2(x, Main.sceneBackgroundPos.Y - Main.screenPosition.Y), Color.White); 90 | } 91 | 92 | //public static void DrawSandstorm() => Sandstorm.DrawGrains(Main.spriteBatch); 93 | 94 | public static void CacheDraws() 95 | { 96 | Reflection.CacheNPCDraws(); 97 | Reflection.CacheProjDraws(); 98 | } 99 | 100 | public static void DrawMoonMoon() 101 | => Reflection.DrawCachedNPCs(Main.instance.DrawCacheNPCsMoonMoon, true); 102 | 103 | public static void DrawFirstFractals() 104 | => Reflection.DrawCachedNPCs(Main.instance.DrawCacheFirstFractals, true); 105 | 106 | public static void DrawBlack() 107 | { 108 | if (Main.drawToScreen) 109 | Reflection.DrawBlack(); 110 | else 111 | Main.spriteBatch.Draw(Main.instance.blackTarget, Main.sceneTilePos - Main.screenPosition, Color.White); 112 | } 113 | 114 | public static void DrawWalls() 115 | { 116 | if (Main.drawToScreen) 117 | { 118 | Main.tileBatch.Begin(); 119 | Reflection.DrawWalls(); 120 | Main.tileBatch.End(); 121 | } 122 | else 123 | Main.spriteBatch.Draw(Main.instance.wallTarget, Main.sceneWallPos - Main.screenPosition, Color.White); 124 | } 125 | 126 | public static void DrawWallOfFlesh() => Reflection.DrawWoF(); 127 | 128 | public static void DrawGoreBehind() 129 | { 130 | if (Main.drawBackGore) 131 | Reflection.DrawGoreBehind(); 132 | } 133 | 134 | public static void DrawMoonLordDeath() 135 | { 136 | MoonlordDeathDrama.DrawPieces(Main.spriteBatch); 137 | MoonlordDeathDrama.DrawExplosions(Main.spriteBatch); 138 | } 139 | 140 | public static void DrawNPCsBehindNonSoldTiles() 141 | => Reflection.DrawCachedNPCs(Main.instance.DrawCacheNPCsBehindNonSolidTiles, true); 142 | 143 | public static void DrawWallTilesNPC() 144 | => Reflection.DrawWallsTilesNPCs(); 145 | 146 | public static void DrawNonSolidTiles() 147 | { 148 | if (Main.drawToScreen) 149 | { 150 | Main.instance.TilesRenderer.PreDrawTiles(false, false, true); 151 | Reflection.DrawTiles(false); 152 | } 153 | else 154 | Main.spriteBatch.Draw(Main.instance.tile2Target, Main.sceneTile2Pos - Main.screenPosition, Color.White); 155 | } 156 | 157 | public static void DrawWaterFalls() 158 | { 159 | Main.instance.waterfallManager.Draw(Main.spriteBatch); 160 | } 161 | 162 | public static void DrawProjsBehindNPCsAndTiles() => 163 | Reflection.DrawCachedProjs(Main.instance.DrawCacheProjsBehindNPCsAndTiles, false); 164 | 165 | public static void DrawNPCsBehindTiles() => Reflection.DrawNPCs(true); 166 | 167 | public static void DrawSolidTiles() 168 | { 169 | if (Main.drawToScreen) 170 | { 171 | Main.instance.TilesRenderer.PreDrawTiles(false, false, true); 172 | Reflection.DrawTiles(true); 173 | } 174 | else 175 | Main.spriteBatch.Draw(Main.instance.tileTarget, Main.sceneTilePos - Main.screenPosition, Color.White); 176 | } 177 | 178 | public static void DrawHitTileAnimation() => 179 | Main.player[Main.myPlayer].hitTile.DrawFreshAnimations(Main.spriteBatch); 180 | 181 | public static void DrawTileEntities(bool solidLayer) 182 | { 183 | } 184 | 185 | public static void DrawNPCsInfrontOfTiles() => Reflection.DrawNPCs(false); 186 | 187 | public static void DrawProjsOverPlayers() => Reflection.DrawCachedProjs(Main.instance.DrawCacheProjsOverPlayers, false); 188 | 189 | public static void DrawNPCProjectiles() => Reflection.DrawCachedNPCs(Main.instance.DrawCacheNPCProjectiles, false); 190 | 191 | public static void SortDrawCacheWorm() => Reflection.SortDrawCashWorms(); 192 | 193 | public static void DrawProjsBehindNPCs() => 194 | Reflection.DrawCachedNPCs(Main.instance.DrawCacheProjsBehindNPCs, false); 195 | 196 | public static void DrawProjsBehindProjectiles() => 197 | Reflection.DrawCachedProjs(Main.instance.DrawCacheProjsBehindProjectiles, false); 198 | 199 | public static void DrawProjectiles() 200 | { 201 | Main.spriteBatch.End(); 202 | Reflection.DrawProjectiles(); 203 | Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, Main.DefaultSamplerState, 204 | DepthStencilState.None, RasterizerState.CullNone, null, Main.Transform); 205 | } 206 | 207 | public static void DrawPlayersBehindNPCs() 208 | { 209 | Main.spriteBatch.End(); 210 | Reflection.DrawPlayersBehindNPCs(); 211 | Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, Main.DefaultSamplerState, 212 | DepthStencilState.None, RasterizerState.CullNone, null, Main.Transform); 213 | } 214 | 215 | public static void DrawPlayersAfterProjs() 216 | { 217 | Main.spriteBatch.End(); 218 | Reflection.DrawPlayersAfterProj(); 219 | Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, Main.DefaultSamplerState, 220 | DepthStencilState.None, RasterizerState.CullNone, null, Main.Transform); 221 | } 222 | 223 | public static void DrawNPCsOverPlayer() => Reflection.DrawCachedNPCs(Main.instance.DrawCacheNPCsOverPlayers, false); 224 | 225 | public static void DrawItems() => Main.instance.DrawItems(); 226 | 227 | public static void DrawRain() => Reflection.DrawRain(); 228 | 229 | public static void DrawGore() => Reflection.DrawGore(); 230 | 231 | public static void DrawDust() 232 | { 233 | Main.spriteBatch.End(); 234 | Reflection.DrawDust(); 235 | var sampler = Main.drawToScreen ? SamplerState.LinearClamp : SamplerState.PointClamp; 236 | Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, sampler, DepthStencilState.None, 237 | RasterizerState.CullCounterClockwise, null, Main.Transform); 238 | } 239 | 240 | public static void DrawForegroundWater() 241 | { 242 | if (Main.drawToScreen) 243 | Reflection.DrawWaters(false); 244 | else 245 | Main.spriteBatch.Draw(Main.waterTarget, Main.sceneWaterPos - Main.screenPosition, Color.White); 246 | } 247 | 248 | public static void DrawWires() 249 | { 250 | if (WiresUI.Settings.DrawWires) 251 | Reflection.DrawWires(); 252 | } 253 | 254 | public static void DrawProjsOverWireUI() => 255 | Reflection.DrawCachedProjs(Main.instance.DrawCacheProjsOverWiresUI, false); 256 | 257 | public static void DrawInfernoRings() => Main.instance.DrawInfernoRings(); 258 | 259 | public static void DrawMoonlordDeathFront() => MoonlordDeathDrama.DrawWhite(Main.spriteBatch); 260 | 261 | public static void DrawScreenObstructions() => ScreenObstruction.Draw(Main.spriteBatch); 262 | 263 | public static void DrawChatOverPlayerHeads() 264 | { 265 | if (Main.hideUI) return; 266 | Reflection.DrawPlayerChatBubbles(); 267 | } 268 | 269 | public static void DrawCombatText() 270 | { 271 | if (Main.hideUI) return; 272 | float targetScale = CombatText.TargetScale; 273 | var combatText = Main.combatText; 274 | var spriteBatch = Main.spriteBatch; 275 | for (int l = 0; l < 100; l++) 276 | { 277 | if (!combatText[l].active) 278 | continue; 279 | 280 | int num10 = 0; 281 | if (combatText[l].crit) 282 | num10 = 1; 283 | 284 | Vector2 vector2 = FontAssets.CombatText[num10].Value.MeasureString(combatText[l].text); 285 | Vector2 origin = new Vector2(vector2.X * 0.5f, vector2.Y * 0.5f); 286 | float num11 = combatText[l].scale / targetScale; 287 | float num12 = (int) combatText[l].color.R; 288 | float num13 = (int) combatText[l].color.G; 289 | float num14 = (int) combatText[l].color.B; 290 | float num15 = (int) combatText[l].color.A; 291 | num12 *= num11 * combatText[l].alpha * 0.3f; 292 | num14 *= num11 * combatText[l].alpha * 0.3f; 293 | num13 *= num11 * combatText[l].alpha * 0.3f; 294 | num15 *= num11 * combatText[l].alpha; 295 | Microsoft.Xna.Framework.Color color = 296 | new Microsoft.Xna.Framework.Color((int) num12, (int) num13, (int) num14, (int) num15); 297 | for (int m = 0; m < 5; m++) 298 | { 299 | float num16 = 0f; 300 | float num17 = 0f; 301 | switch (m) 302 | { 303 | case 0: 304 | num16 -= targetScale; 305 | break; 306 | case 1: 307 | num16 += targetScale; 308 | break; 309 | case 2: 310 | num17 -= targetScale; 311 | break; 312 | case 3: 313 | num17 += targetScale; 314 | break; 315 | default: 316 | num12 = (float) (int) combatText[l].color.R * num11 * combatText[l].alpha; 317 | num14 = (float) (int) combatText[l].color.B * num11 * combatText[l].alpha; 318 | num13 = (float) (int) combatText[l].color.G * num11 * combatText[l].alpha; 319 | num15 = (float) (int) combatText[l].color.A * num11 * combatText[l].alpha; 320 | color = new Microsoft.Xna.Framework.Color((int) num12, (int) num13, (int) num14, (int) num15); 321 | break; 322 | } 323 | 324 | if (Main.player[Main.myPlayer].gravDir == -1f) 325 | { 326 | float num18 = combatText[l].position.Y - Main.screenPosition.Y; 327 | num18 = (float) Main.screenHeight - num18; 328 | spriteBatch.DrawString(FontAssets.CombatText[num10].Value, combatText[l].text, 329 | new Vector2(combatText[l].position.X - Main.screenPosition.X + num16 + origin.X, 330 | num18 + num17 + origin.Y), color, combatText[l].rotation, origin, combatText[l].scale, 331 | SpriteEffects.None, 0f); 332 | } 333 | else 334 | { 335 | spriteBatch.DrawString(FontAssets.CombatText[num10].Value, combatText[l].text, 336 | new Vector2(combatText[l].position.X - Main.screenPosition.X + num16 + origin.X, 337 | combatText[l].position.Y - Main.screenPosition.Y + num17 + origin.Y), color, 338 | combatText[l].rotation, origin, combatText[l].scale, SpriteEffects.None, 0f); 339 | } 340 | } 341 | } 342 | } 343 | 344 | public static void DrawItemText() 345 | { 346 | if (Main.hideUI) return; 347 | var scale = 1f; 348 | for (int num78 = 0; num78 < 20; num78++) 349 | { 350 | if (Main.popupText[num78].active) 351 | { 352 | string text = Main.popupText[num78].name; 353 | if (Main.popupText[num78].stack > 1) 354 | { 355 | text = string.Concat(new object[] 356 | { 357 | text, 358 | " (", 359 | Main.popupText[num78].stack, 360 | ")" 361 | }); 362 | } 363 | Vector2 vector7 = ((DynamicSpriteFont)FontAssets.MouseText).MeasureString(text); 364 | Vector2 origin2 = new Vector2(vector7.X * 0.5f, vector7.Y * 0.5f); 365 | float num79 = 1f; 366 | float num80 = (float)Main.popupText[num78].color.R; 367 | float num81 = (float)Main.popupText[num78].color.G; 368 | float num82 = (float)Main.popupText[num78].color.B; 369 | float num83 = (float)Main.popupText[num78].color.A; 370 | num80 *= num79 * Main.popupText[num78].alpha * 0.3f; 371 | num82 *= num79 * Main.popupText[num78].alpha * 0.3f; 372 | num81 *= num79 * Main.popupText[num78].alpha * 0.3f; 373 | num83 *= num79 * Main.popupText[num78].alpha; 374 | Microsoft.Xna.Framework.Color color10 = new Microsoft.Xna.Framework.Color((int)num80, (int)num81, (int)num82, (int)num83); 375 | for (int num84 = 0; num84 < 5; num84++) 376 | { 377 | float num85 = 0f; 378 | float num86 = 0f; 379 | if (num84 == 0) 380 | { 381 | num85 -= scale * 2f; 382 | } 383 | else if (num84 == 1) 384 | { 385 | num85 += scale * 2f; 386 | } 387 | else if (num84 == 2) 388 | { 389 | num86 -= scale * 2f; 390 | } 391 | else if (num84 == 3) 392 | { 393 | num86 += scale * 2f; 394 | } 395 | else 396 | { 397 | num80 = (float)Main.popupText[num78].color.R * num79 * Main.popupText[num78].alpha; 398 | num82 = (float)Main.popupText[num78].color.B * num79 * Main.popupText[num78].alpha; 399 | num81 = (float)Main.popupText[num78].color.G * num79 * Main.popupText[num78].alpha; 400 | num83 = (float)Main.popupText[num78].color.A * num79 * Main.popupText[num78].alpha; 401 | color10 = new Microsoft.Xna.Framework.Color((int)num80, (int)num81, (int)num82, (int)num83); 402 | } 403 | if (num84 < 4) 404 | { 405 | num83 = (float)Main.popupText[num78].color.A * num79 * Main.popupText[num78].alpha; 406 | color10 = new Microsoft.Xna.Framework.Color(0, 0, 0, (int)num83); 407 | } 408 | float num87 = Main.popupText[num78].position.Y - Main.screenPosition.Y + num86; 409 | if (Main.player[Main.myPlayer].gravDir == -1f) 410 | { 411 | num87 = (float)Main.screenHeight - num87; 412 | } 413 | Main.spriteBatch.DrawString((DynamicSpriteFont)FontAssets.MouseText, text, new Vector2(Main.popupText[num78].position.X - Main.screenPosition.X + num85 + origin2.X, num87 + origin2.Y), color10, Main.popupText[num78].rotation, origin2, scale, SpriteEffects.None, 0f); 414 | } 415 | } 416 | } 417 | } 418 | } -------------------------------------------------------------------------------- /Rendering/TileDrawReflection.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using Terraria; 3 | using Terraria.GameContent.Drawing; 4 | 5 | namespace Terraria3D; 6 | 7 | public static class TileDrawReflection 8 | { 9 | private static MethodInfo _drawMultiTileVines = GetMethod("DrawMultiTileVines", BindingFlags.Instance); 10 | private static MethodInfo _drawMultiTileGrass = GetMethod("DrawMultiTileGrass", BindingFlags.Instance); 11 | private static MethodInfo _drawVoidLenses = GetMethod("DrawVoidLenses", BindingFlags.Instance); 12 | private static MethodInfo _drawTeleportationPylons = GetMethod("DrawTeleportationPylons", BindingFlags.Instance); 13 | private static MethodInfo _drawMasterTrophies = GetMethod("DrawMasterTrophies", BindingFlags.Instance); 14 | private static MethodInfo _drawGrass = GetMethod("DrawGrass", BindingFlags.Instance); 15 | private static MethodInfo _drawVines = GetMethod("DrawVines", BindingFlags.Instance); 16 | private static MethodInfo _drawTrees = GetMethod("DrawTrees", BindingFlags.Instance); 17 | private static MethodInfo _drawReverseVines = GetMethod("DrawReverseVines", BindingFlags.Instance); 18 | private static MethodInfo _drawHatRacks = GetMethod("DrawEntities_HatRacks", BindingFlags.Instance); 19 | private static MethodInfo _drawDisplayDolls = GetMethod("DrawEntities_DisplayDolls", BindingFlags.Instance); 20 | 21 | public static void DrawNonSolidLayers() 22 | { 23 | DrawMultiTileVines(); 24 | DrawMultiTileGrass(); 25 | DrawVoidLenses(); 26 | DrawTeleportationPylons(); 27 | DrawMasterTrophies(); 28 | DrawGrass(); 29 | DrawTrees(); 30 | DrawVines(); 31 | DrawReverseVines(); 32 | } 33 | 34 | public static void DrawSolidLayers() 35 | { 36 | DrawHatRacks(); 37 | DrawDisplayDolls(); 38 | } 39 | 40 | private static void DrawMultiTileVines() => _drawMultiTileVines.Invoke(Main.instance.TilesRenderer, null); 41 | private static void DrawMultiTileGrass() => _drawMultiTileGrass.Invoke(Main.instance.TilesRenderer, null); 42 | private static void DrawVoidLenses() => _drawVoidLenses.Invoke(Main.instance.TilesRenderer, null); 43 | private static void DrawTeleportationPylons() => _drawTeleportationPylons.Invoke(Main.instance.TilesRenderer, null); 44 | private static void DrawMasterTrophies() => _drawMasterTrophies.Invoke(Main.instance.TilesRenderer, null); 45 | private static void DrawGrass() => _drawGrass.Invoke(Main.instance.TilesRenderer, null); 46 | private static void DrawVines() => _drawVines.Invoke(Main.instance.TilesRenderer, null); 47 | private static void DrawTrees() => _drawTrees.Invoke(Main.instance.TilesRenderer, null); 48 | private static void DrawReverseVines() => _drawReverseVines.Invoke(Main.instance.TilesRenderer, null); 49 | private static void DrawHatRacks() => _drawHatRacks.Invoke(Main.instance.TilesRenderer, null); 50 | private static void DrawDisplayDolls() => _drawDisplayDolls.Invoke(Main.instance.TilesRenderer, null); 51 | 52 | private static MethodInfo GetMethod(string methodName, BindingFlags bindingFlags) 53 | => typeof(TileDrawing).GetMethod(methodName, BindingFlags.NonPublic | bindingFlags); 54 | } -------------------------------------------------------------------------------- /Rendering/TileSolidOverrides.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Terraria; 3 | using Terraria.GameContent.Drawing; 4 | using Terraria.ID; 5 | 6 | namespace Terraria3D; 7 | 8 | public static class TileSolidOverrides 9 | { 10 | private static readonly Dictionary _overrides = new Dictionary() 11 | { 12 | {TileID.OpenDoor, false } 13 | }; 14 | 15 | public static bool MoveSolidTopToSolid { get; set; } = true; 16 | 17 | public static bool IsTileSolid(ushort tileType) 18 | { 19 | var result = Main.tileSolid[tileType]; 20 | 21 | if (TileID.Sets.DrawTileInSolidLayer[tileType].HasValue) 22 | result = TileID.Sets.DrawTileInSolidLayer[tileType].Value; 23 | 24 | if (MoveSolidTopToSolid) 25 | { 26 | if (Main.tileSolidTop[tileType]) 27 | result = true; 28 | } 29 | 30 | if (_overrides.ContainsKey(tileType)) 31 | return _overrides[tileType]; 32 | return result; 33 | } 34 | } -------------------------------------------------------------------------------- /Scene/Layer3D.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Graphics; 3 | using System; 4 | using Terraria; 5 | 6 | namespace Terraria3D; 7 | 8 | public class Layer3D 9 | { 10 | public string Name { get; set; } = "Un-named"; 11 | public float ZPos { get; set; } = 0; 12 | public float Depth { get; set; } = 16; 13 | public float NoiseAmount { get; set; } = 1; 14 | public bool Enabled { get; set; } = true; 15 | public bool UseInnerPixel { get; set; } = true; 16 | public Action RenderFunction { get; set; } = null; 17 | public InputPlaneType InputPlane { get; set; } = InputPlaneType.None; 18 | 19 | public int TargetWidth => _renderTarget.Width; 20 | public int TargetHeght => _renderTarget.Height; 21 | 22 | private RenderTarget2D _renderTarget; 23 | private RenderTarget2D _innerPixelTarget; 24 | 25 | public Layer3D() 26 | { 27 | UpdateRenderTarget(); 28 | RTManager.ResolutionChanged += (w, h, rtW, rtH) => UpdateRenderTarget(); 29 | } 30 | 31 | public void RenderToTarget() 32 | { 33 | Main.graphics.GraphicsDevice.SetRenderTarget(_renderTarget); 34 | Main.graphics.GraphicsDevice.Clear(Color.Transparent); 35 | Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullNone, null, Main.Transform); 36 | RenderFunction(); 37 | Main.spriteBatch.End(); 38 | if(UseInnerPixel) 39 | Renderers.InnerPixelRenderer.Draw(_innerPixelTarget, _renderTarget); 40 | Main.graphics.GraphicsDevice.SetRenderTarget(null); 41 | } 42 | 43 | public void Dispose() 44 | { 45 | _renderTarget?.Dispose(); 46 | _innerPixelTarget?.Dispose(); 47 | } 48 | 49 | public void DrawExtrusion(Camera camera, bool ao, Matrix matrix) 50 | { 51 | if (!Enabled) return; 52 | matrix = Matrix.CreateScale(1, 1, Depth) * Matrix.CreateTranslation(0, 0, Depth - ZPos) * matrix; 53 | Renderers.GridRenderer.Draw(UseInnerPixel ? _innerPixelTarget : _renderTarget, camera, Depth, NoiseAmount, ao, matrix); 54 | } 55 | public void DrawCap(Camera camera, Matrix matrix) 56 | { 57 | if (!Enabled) return; 58 | matrix = Matrix.CreateTranslation(0, 0, Depth - ZPos) * matrix; 59 | Renderers.CapRenderer.Draw(_renderTarget, camera, matrix); 60 | } 61 | 62 | private void UpdateRenderTarget() 63 | { 64 | Dispose(); 65 | _renderTarget = Utils.CreateRenderTarget(RTManager.UsingPoT); 66 | _innerPixelTarget = Utils.CreateRenderTarget(RTManager.UsingPoT); 67 | } 68 | 69 | public enum InputPlaneType 70 | { 71 | None, 72 | SolidTiles, 73 | NoneSolidTiles, 74 | } 75 | } -------------------------------------------------------------------------------- /Scene/LayerManager.cs: -------------------------------------------------------------------------------- 1 | namespace Terraria3D; 2 | 3 | public class LayerManager 4 | { 5 | public Layer3D[] Layers => _layers; 6 | private Layer3D[] _layers; 7 | 8 | public LayerManager() 9 | { 10 | Rebuild(); 11 | } 12 | 13 | public void Rebuild() 14 | { 15 | LayerBuilder.PopulateLayers(ref _layers); 16 | } 17 | 18 | public void Dispose() 19 | { 20 | foreach (var layer in _layers) 21 | layer?.Dispose(); 22 | } 23 | } -------------------------------------------------------------------------------- /Scene/LayersBuilder.cs: -------------------------------------------------------------------------------- 1 |  2 | 3 | namespace Terraria3D; 4 | 5 | public static class LayerBuilder 6 | { 7 | public static void PopulateLayers(ref Layer3D[] layers) 8 | { 9 | if (layers != null) 10 | { 11 | foreach (var layer in layers) 12 | layer?.Dispose(); 13 | } 14 | layers = new Layer3D[] 15 | { 16 | new Layer3D() 17 | { 18 | Name = "Background", 19 | ZPos = 4, 20 | Depth = 4, 21 | RenderFunction = () => 22 | { 23 | Rendering.DrawBlack(); 24 | Rendering.DrawBackgroundWater(); 25 | Rendering.DrawSceneBackground(); 26 | Rendering.DrawWalls(); 27 | 28 | } 29 | }, 30 | // Solid tiles 31 | new Layer3D() 32 | { 33 | Name = "Solid Tiles", 34 | Depth = 32, 35 | InputPlane = Layer3D.InputPlaneType.SolidTiles, 36 | RenderFunction = () => 37 | { 38 | Rendering.DrawSolidTiles(); 39 | } 40 | }, 41 | // Non Solid tiles 42 | new Layer3D() 43 | { 44 | Name = "Non Solid Tiles", 45 | Depth = 8, 46 | InputPlane = Layer3D.InputPlaneType.NoneSolidTiles, 47 | RenderFunction = () => 48 | { 49 | Rendering.DrawNonSolidTiles(); 50 | Rendering.DrawWaterFalls(); 51 | TileDrawReflection.DrawNonSolidLayers(); 52 | 53 | } 54 | }, 55 | //Player 56 | new Layer3D() 57 | { 58 | Name = "Characters", 59 | ZPos = -18, 60 | Depth = 6, 61 | NoiseAmount = 0, 62 | RenderFunction = () => 63 | { 64 | Rendering.DrawFirstFractals(); 65 | Rendering.DrawMoonMoon(); 66 | Rendering.DrawNPCsBehindTiles(); 67 | Rendering.SortDrawCacheWorm(); 68 | Rendering.DrawWallOfFlesh(); 69 | Rendering.DrawNPCsBehindNonSoldTiles(); 70 | Rendering.DrawNPCsInfrontOfTiles(); 71 | Rendering.DrawPlayersBehindNPCs(); 72 | Rendering.DrawPlayersAfterProjs(); 73 | Rendering.DrawNPCsOverPlayer(); 74 | Rendering.DrawProjsOverPlayers(); 75 | } 76 | }, 77 | // Proj 78 | new Layer3D() 79 | { 80 | Name = "Projectiles", 81 | ZPos = -20, 82 | Depth = 2, 83 | NoiseAmount = 0, 84 | RenderFunction = () => 85 | { 86 | Rendering.DrawProjsBehindNPCsAndTiles(); 87 | Rendering.DrawProjsBehindNPCs(); 88 | Rendering.DrawProjsBehindProjectiles(); 89 | Rendering.DrawProjectiles(); 90 | Rendering.DrawInfernoRings(); 91 | Rendering.DrawProjsOverWireUI(); 92 | Rendering.DrawNPCProjectiles(); 93 | } 94 | }, 95 | // Items Gore 96 | new Layer3D() 97 | { 98 | Name = "Gore - Weather - Items", 99 | ZPos = -12, 100 | Depth = 6, 101 | NoiseAmount = 0, 102 | RenderFunction = () => 103 | { 104 | Rendering.DrawGoreBehind(); 105 | Rendering.DrawGore(); 106 | Rendering.DrawDust(); 107 | Rendering.DrawRain(); 108 | Rendering.DrawMoonLordDeath(); 109 | Rendering.DrawMoonlordDeathFront(); 110 | Rendering.DrawItems(); 111 | } 112 | }, 113 | new Layer3D() 114 | { 115 | Name = "Water Foreground", 116 | Depth = 32, 117 | RenderFunction = Rendering.DrawForegroundWater 118 | }, 119 | new Layer3D() 120 | { 121 | Name = "Wires - UI", 122 | ZPos = -32, 123 | Depth = 4, 124 | RenderFunction = () => 125 | { 126 | Rendering.DrawWires(); 127 | Rendering.DrawHitTileAnimation(); 128 | Rendering.DrawItemText(); 129 | Rendering.DrawCombatText(); 130 | Rendering.DrawChatOverPlayerHeads(); 131 | InterfaceRendering.RenderGameInterfaces(); 132 | } 133 | } 134 | }; 135 | } 136 | } -------------------------------------------------------------------------------- /Scene/Scene3D.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using System.Linq; 3 | using Terraria; 4 | 5 | namespace Terraria3D 6 | { 7 | public class Scene3D 8 | { 9 | public Camera Camera { get; private set; } = new Camera(); 10 | public CameraDriver CameraDriver { get; private set; } 11 | public DollyController DollyController { get; private set; } 12 | public Transform ModelTransform { get; private set; } = new Transform(); 13 | public bool AmbientOcclusion { get; set; } = true; 14 | public Camera ActiveCamera => DollyController.DollyInProgress ? DollyController.TransitionCamera : Camera; 15 | 16 | private bool _canSkipDrawing => Main.gameMenu || Main.mapFullscreen; 17 | 18 | public Scene3D() 19 | { 20 | CameraDriver = new CameraDriver(Camera); 21 | DollyController = new DollyController(Camera); 22 | } 23 | 24 | public void Update(GameTime gameTime) 25 | { 26 | if (!Terraria3D.Enabled) return; 27 | DollyController.Update((float)gameTime.ElapsedGameTime.TotalSeconds); 28 | if (InputTerraria3D.CameraControlsEnabled && !DollyController.DollyInProgress) 29 | CameraDriver.Drive((float)gameTime.ElapsedGameTime.TotalSeconds); 30 | } 31 | 32 | public void RenderLayers(Layer3D[] layers) 33 | { 34 | if (!Terraria3D.Enabled || _canSkipDrawing) return; 35 | // Disable zoom 36 | Utils.SetZoom(1); 37 | Rendering.PreRenderSetup(); 38 | foreach (var layer in layers) 39 | layer.RenderToTarget(); 40 | // Restore zoom 41 | Utils.RestoreOldZoom(); 42 | } 43 | 44 | public void DrawToScreen(Layer3D[] layers) 45 | { 46 | if (!Terraria3D.Enabled || _canSkipDrawing) return; 47 | DrawExtrusionAndCap(layers); 48 | } 49 | 50 | private void DrawExtrusions(Layer3D[] layers) 51 | { 52 | foreach (var layer in layers) 53 | layer.DrawExtrusion(ActiveCamera, AmbientOcclusion, _extrusionMatrix); 54 | } 55 | 56 | private void DrawCaps(Layer3D[] layers) 57 | { 58 | foreach (var layer in layers.OrderBy(l => l.Depth - l.ZPos)) 59 | layer.DrawCap(ActiveCamera, _capMatrix); 60 | } 61 | 62 | private void DrawExtrusionAndCap(Layer3D[] layers) 63 | { 64 | foreach (var layer in layers.OrderBy(l => l.Depth - l.ZPos)) 65 | { 66 | layer.DrawExtrusion(ActiveCamera, AmbientOcclusion, _extrusionMatrix); 67 | layer.DrawCap(ActiveCamera, _capMatrix); 68 | } 69 | } 70 | 71 | private Matrix _extrusionMatrix 72 | { 73 | get 74 | { 75 | ModelTransform.Scale = Vector3.One / Screen.Height; 76 | ModelTransform.Position = new Vector3(-Screen.Width * 0.5f, -Screen.Height * 0.5f, 0) * ModelTransform.Scale.X; 77 | return ModelTransform.LocalToWorld; 78 | } 79 | } 80 | 81 | private Matrix _capMatrix 82 | { 83 | get 84 | { 85 | float s = (float)RTManager.Height / Screen.Height; 86 | var scale = Matrix.CreateScale((float)RTManager.Width / RTManager.Height, 1, 1) * 87 | Matrix.CreateScale(s, s, 1f / Screen.Height); 88 | var translation = Matrix.CreateTranslation(0.5f - ((float)Screen.Width / RTManager.Width) * 0.5f, 89 | -0.5f + ((float)Screen.Height / RTManager.Height) * 0.5f, 0); 90 | return translation * scale; 91 | } 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Serialization/CameraData.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | 3 | namespace Terraria3D.Serialization; 4 | 5 | public class CameraData 6 | { 7 | public Vector3 Position { get; set; } 8 | public Quaternion Rotation { get; set; } 9 | public float FieldOfView { get; set; } 10 | public CameraDriver.CameraYStart YStartPosition { get; set; } 11 | public CameraDriver.CameraMoveMode MoveMode { get; set; } 12 | 13 | public void Apply(Scene3D scene) 14 | { 15 | scene.Camera.Transform.Position = Position; 16 | scene.Camera.Transform.Rotation = Rotation; 17 | scene.Camera.FieldOfView = MathHelper.Clamp(FieldOfView, 3, 179); 18 | scene.CameraDriver.YStartPosition = YStartPosition; 19 | scene.CameraDriver.MoveMode = MoveMode; 20 | } 21 | 22 | public void Record(Scene3D scene) 23 | { 24 | Position = scene.Camera.Transform.Position; 25 | Rotation = scene.Camera.Transform.Rotation; 26 | FieldOfView = scene.Camera.FieldOfView; 27 | YStartPosition = scene.CameraDriver.YStartPosition; 28 | MoveMode = scene.CameraDriver.MoveMode; 29 | } 30 | } -------------------------------------------------------------------------------- /Serialization/FileUtils.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using Terraria; 7 | 8 | namespace Terraria3D.Serialization; 9 | 10 | public static class FileUtils 11 | { 12 | public static string GetJSON(string relativePath) 13 | { 14 | var path = GetPath(relativePath); 15 | if (!File.Exists(path)) 16 | throw new FileNotFoundException(string.Empty, path); 17 | return File.ReadAllText(path); 18 | } 19 | 20 | public static void SaveJSON(string json, string relativePath) 21 | { 22 | var path = GetPath(relativePath); 23 | var directory = Path.GetDirectoryName(path); 24 | if (!Directory.Exists(directory)) 25 | throw new DirectoryNotFoundException(directory); 26 | File.WriteAllText(path, json); 27 | } 28 | 29 | private static string GetPath(string relativePath) 30 | => Path.Combine(Main.SavePath, relativePath + ".json"); 31 | } -------------------------------------------------------------------------------- /Serialization/LayerData.cs: -------------------------------------------------------------------------------- 1 | namespace Terraria3D.Serialization; 2 | 3 | public class LayerData 4 | { 5 | public string Name { get; set; } 6 | public bool Enabled { get; set; } 7 | public float Depth { get; set; } 8 | public float ZPos { get; set; } 9 | public float Noise { get; set; } 10 | public bool UseInnerPixel { get; set; } 11 | 12 | public LayerData() { } 13 | public LayerData(Layer3D layer) 14 | { 15 | Record(layer); 16 | } 17 | 18 | public void Apply(Layer3D layer) 19 | { 20 | layer.Enabled = Enabled; 21 | layer.Depth = Depth; 22 | layer.ZPos = ZPos; 23 | layer.NoiseAmount = Noise; 24 | layer.UseInnerPixel = UseInnerPixel; 25 | } 26 | 27 | public void Record(Layer3D layer) 28 | { 29 | Name = layer.Name; 30 | Enabled = layer.Enabled; 31 | Depth = layer.Depth; 32 | ZPos = layer.ZPos; 33 | Noise = layer.NoiseAmount; 34 | UseInnerPixel = layer.UseInnerPixel; 35 | } 36 | } -------------------------------------------------------------------------------- /Serialization/SceneData.cs: -------------------------------------------------------------------------------- 1 | namespace Terraria3D.Serialization; 2 | 3 | public class SceneData 4 | { 5 | public CameraData Camera { get; set; } = new CameraData(); 6 | public bool AmbientOcclusionEnabled { get; set; } 7 | 8 | public void Record(Scene3D scene) 9 | { 10 | Camera.Record(scene); 11 | AmbientOcclusionEnabled = scene.AmbientOcclusion; 12 | } 13 | 14 | public void Apply(Scene3D scene) 15 | { 16 | Camera.Apply(scene); 17 | scene.AmbientOcclusion = AmbientOcclusionEnabled; 18 | } 19 | } -------------------------------------------------------------------------------- /Serialization/Settings.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using Terraria3D.Serialization; 3 | using System.IO; 4 | using Terraria; 5 | 6 | namespace Terraria3D; 7 | 8 | public static class Settings 9 | { 10 | public delegate void SettingsLoadedEvent(SettingsData data); 11 | public static event SettingsLoadedEvent SettingsLoaded; 12 | public static event SettingsLoadedEvent SettingsSaved; 13 | 14 | public static void Load() 15 | { 16 | try 17 | { 18 | var json = FileUtils.GetJSON(Terraria3D.Instance.DisplayName); 19 | var settings = JsonConvert.DeserializeObject(json); 20 | settings.Apply(Terraria3D.Instance); 21 | SettingsLoaded?.Invoke(settings); 22 | } 23 | // If not settings file is found, no sweat. Don't do anything. 24 | catch(FileNotFoundException) { } 25 | catch(DirectoryNotFoundException) { } 26 | catch 27 | { 28 | Terraria3D.Instance.Scene.CameraDriver.ResetCameraPosition(); 29 | Main.NewText(string.Format("{0}: Could not load settings from last session.", Terraria3D.Instance.DisplayName)); 30 | } 31 | } 32 | 33 | public static void Save() 34 | { 35 | var settings = new SettingsData(); 36 | settings.Record(Terraria3D.Instance); 37 | var json = JsonConvert.SerializeObject(settings, Formatting.Indented); 38 | FileUtils.SaveJSON(json, Terraria3D.Instance.DisplayName); 39 | SettingsSaved?.Invoke(settings); 40 | } 41 | } -------------------------------------------------------------------------------- /Serialization/SettingsData.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | namespace Terraria3D.Serialization; 4 | 5 | public class SettingsData 6 | { 7 | public bool Enabled { get; set; } 8 | public SceneData Scene { get; set; } = new SceneData(); 9 | public LayerData[] LayerData { get; set; } 10 | 11 | public void Apply(Terraria3D mod) 12 | { 13 | Terraria3D.Enabled = Enabled; 14 | Scene.Apply(mod.Scene); 15 | ApplyLayers(mod.LayerManager.Layers); 16 | } 17 | 18 | public void Record(Terraria3D mod) 19 | { 20 | Enabled = Terraria3D.Enabled; 21 | Scene.Record(mod.Scene); 22 | RecordLayers(mod.LayerManager.Layers); 23 | } 24 | 25 | private void ApplyLayers(Layer3D[] layers) 26 | { 27 | foreach(var layer in layers) 28 | LayerData.Where(ld => ld.Name.Equals(layer.Name)).FirstOrDefault()?.Apply(layer); 29 | } 30 | private void RecordLayers(Layer3D[] layers) 31 | { 32 | LayerData = new LayerData[layers.Length]; 33 | for (int i = 0; i < layers.Length; i++) 34 | LayerData[i] = new LayerData(layers[i]); 35 | } 36 | } -------------------------------------------------------------------------------- /Terraria3D.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using Terraria; 6 | using Terraria.GameInput; 7 | using Terraria.ModLoader; 8 | using Terraria.ModLoader.IO; 9 | using Terraria.UI; 10 | 11 | namespace Terraria3D; 12 | 13 | public class Terraria3D : Mod 14 | { 15 | public static bool Enabled { get; set; } = true; 16 | public static Terraria3D Instance { get; private set; } 17 | public Scene3D Scene { get; set; } 18 | public LayerManager LayerManager { get; set; } 19 | 20 | private Test _t = new Test(); 21 | 22 | public async void Toggle() 23 | { 24 | if (Scene.DollyController.DollyInProgress) return; 25 | if(Enabled) 26 | { 27 | await Scene.DollyController.TransitionOutAsync(); 28 | Enabled = false; 29 | } 30 | else 31 | { 32 | Enabled = true; 33 | Scene.DollyController.TransitionIn(); 34 | } 35 | 36 | } 37 | 38 | public override void Load() 39 | { 40 | if (Main.dedServ) return; 41 | Instance = this; 42 | Enabled = true; 43 | Loading.Load(this); 44 | //_t.Load(); 45 | } 46 | 47 | public override void Unload() 48 | { 49 | if (Main.dedServ) return; 50 | Instance = null; 51 | Enabled = false; 52 | Loading.Unload(this); 53 | } 54 | 55 | // Drawing 56 | public void RenderLayersTargets() => Scene.RenderLayers(LayerManager.Layers); 57 | public void DrawScene() => Scene.DrawToScreen(LayerManager.Layers); 58 | } 59 | 60 | public class Test : ModSystem 61 | { 62 | public override void UpdateUI(GameTime gameTime) 63 | { 64 | InputTerraria3D.Update(); 65 | UITerraria3D.Update(gameTime); 66 | Terraria3D.Instance.Scene.Update(gameTime); 67 | } 68 | 69 | public override void ModifyInterfaceLayers(List layers) => UITerraria3D.ModifyInterfaceLayers(layers); 70 | } 71 | 72 | public class PlayerHooks : ModPlayer 73 | { 74 | public override void ProcessTriggers(TriggersSet triggersSet) => InputTerraria3D.ProcessInput(); 75 | public override void SetControls() => InputTerraria3D.SetControls(Player); 76 | public override void OnEnterWorld() 77 | { 78 | // Hack for overhaul to stop black tiles from persisting. 79 | Settings.Load(); 80 | if (Main.instance.blackTarget != null && !Main.instance.blackTarget.IsDisposed) 81 | { 82 | Main.graphics.GraphicsDevice.SetRenderTarget(Main.instance.blackTarget); 83 | Main.graphics.GraphicsDevice.Clear(Color.Transparent); 84 | Main.graphics.GraphicsDevice.SetRenderTarget(null); 85 | } 86 | } 87 | 88 | public override void SaveData(TagCompound tag) 89 | { 90 | Settings.Save(); 91 | //return base.SaveData(tag); 92 | } 93 | public override void LoadData(TagCompound tag) 94 | { 95 | Settings.Load(); 96 | } 97 | } -------------------------------------------------------------------------------- /Terraria3D.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Terraria3D 6 | net6.0 7 | AnyCPU 8 | latest 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Terraria3D.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28010.2003 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Terraria3D", "Terraria3D.csproj", "{8298EAB6-0586-4BDA-9483-83624B66B13A}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {8298EAB6-0586-4BDA-9483-83624B66B13A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {8298EAB6-0586-4BDA-9483-83624B66B13A}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {8298EAB6-0586-4BDA-9483-83624B66B13A}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {8298EAB6-0586-4BDA-9483-83624B66B13A}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {3F12DEC0-BA73-408D-9D08-665AE2E35E1C} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /UI/Elements/UICameraControlsPanel.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Graphics; 3 | using Terraria.GameContent.UI.Elements; 4 | 5 | namespace Terraria3D; 6 | 7 | public class UICameraControlsPanel : UIPanel 8 | { 9 | public bool Visible { get; set; } = true; 10 | 11 | private float _height = 0; 12 | private UITextPanel _moveCameraModeButton; 13 | private UITextPanel _startYOffsetButton; 14 | private CameraDriver _cameraDriver => Terraria3D.Instance.Scene.CameraDriver; 15 | 16 | public UICameraControlsPanel() 17 | { 18 | AddLine("Camera Controls", 1.5f); 19 | AddControlLine("F", "Reset"); 20 | AddControlLine("WASD", " Move"); 21 | AddControlLine("QE", " Move Vertically"); 22 | AddControlLine("Left Click", " Rotate"); 23 | AddControlLine("Alt + Left Click", " Orbit"); 24 | AddControlLine("Alt + Middle Click", " Pan"); 25 | AddControlLine("Alt + Right Click", " Zoom"); 26 | AddControlLine("Arrow Keys", "Orbit"); 27 | _moveCameraModeButton = AddButtonWithLabel("Move Mode"); 28 | UpdateMoveCameraModeButtonText(); 29 | _moveCameraModeButton.OnLeftClick += (evt, listener) => 30 | { 31 | if (evt.Target == _moveCameraModeButton) 32 | { 33 | _cameraDriver.MoveMode = _cameraDriver.MoveMode == CameraDriver.CameraMoveMode.Relative ? 34 | CameraDriver.CameraMoveMode.World : 35 | CameraDriver.CameraMoveMode.Relative; 36 | UpdateMoveCameraModeButtonText(); 37 | } 38 | }; 39 | _startYOffsetButton = AddButtonWithLabel("Start Y Pos"); 40 | UpdateStartYOffsetButtonText(); 41 | _startYOffsetButton.OnLeftClick += (evt, listener) => 42 | { 43 | if(evt.Target == _startYOffsetButton) 44 | { 45 | _cameraDriver.YStartPosition = _cameraDriver.YStartPosition == CameraDriver.CameraYStart.Center ? 46 | CameraDriver.CameraYStart.Offset : 47 | CameraDriver.CameraYStart.Center; 48 | 49 | _cameraDriver.ResetCameraPosition(); 50 | UpdateStartYOffsetButtonText(); 51 | } 52 | }; 53 | 54 | Width.Pixels = 250; 55 | Height.Pixels = _height + PaddingTop + PaddingBottom; 56 | 57 | Settings.SettingsLoaded += SettingsLoaded; 58 | } 59 | 60 | public void Dispose() => Settings.SettingsLoaded -= SettingsLoaded; 61 | 62 | public void SettingsLoaded(Serialization.SettingsData settings) 63 | { 64 | UpdateMoveCameraModeButtonText(); 65 | UpdateStartYOffsetButtonText(); 66 | } 67 | 68 | private void AddLine(string text, float textScale = 1, bool large = false) 69 | { 70 | var uiText = new UIText(text, textScale, large); 71 | uiText.Top.Pixels = _height; 72 | uiText.MarginBottom = 10; 73 | uiText.Recalculate(); 74 | _height += uiText.GetOuterDimensions().Height; 75 | Append(uiText); 76 | } 77 | 78 | private void AddControlLine(string control, string action) 79 | { 80 | var controlText = new UIText(control); 81 | controlText.Top.Pixels = _height; 82 | controlText.MarginTop = 5; 83 | controlText.Recalculate(); 84 | _height += controlText.GetOuterDimensions().Height; 85 | 86 | var actionText = new UIText(action); 87 | actionText.Top = controlText.Top; 88 | actionText.HAlign = 1; 89 | 90 | Append(controlText); 91 | Append(actionText); 92 | } 93 | 94 | private UITextPanel AddButtonWithLabel(string labelText) 95 | { 96 | var button = new UITextPanel(string.Empty); 97 | button.HAlign = 1; 98 | button.Top.Pixels = _height; 99 | button.MarginTop = 5; 100 | button.Recalculate(); 101 | _height += button.GetOuterDimensions().Height; 102 | 103 | var label = new UIText(labelText); 104 | label.Top.Pixels = button.Top.Pixels + 15; 105 | Append(button); 106 | Append(label); 107 | return button; 108 | } 109 | 110 | private void UpdateMoveCameraModeButtonText() 111 | => _moveCameraModeButton.SetText(_cameraDriver.MoveMode == CameraDriver.CameraMoveMode.Relative ? "Camera" : "World"); 112 | private void UpdateStartYOffsetButtonText() 113 | => _startYOffsetButton.SetText(_cameraDriver.YStartPosition == CameraDriver.CameraYStart.Offset ? "Offset" : "Center"); 114 | 115 | public override void Update(GameTime gameTime) 116 | { 117 | if (Visible) 118 | base.Update(gameTime); 119 | } 120 | 121 | public override void Draw(SpriteBatch spriteBatch) 122 | { 123 | if (Visible) 124 | base.Draw(spriteBatch); 125 | } 126 | } -------------------------------------------------------------------------------- /UI/Elements/UILayerEntry.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Graphics; 3 | using ReLogic.Content; 4 | using Terraria.GameContent.UI.Elements; 5 | using Terraria.Graphics; 6 | using Terraria.ModLoader; 7 | using Terraria.ModLoader.UI; 8 | 9 | namespace Terraria3D.UI.Elements; 10 | 11 | public class UILayerEntry : UIPanel 12 | { 13 | private static Texture2D _dividerTexture = UICommon.DividerTexture.Value; 14 | 15 | public Layer3D Layer 16 | { 17 | get => _layer; 18 | set => SetLayer(value); 19 | } 20 | 21 | private Layer3D _layer; 22 | 23 | private UIText _layerName = new(string.Empty); 24 | private UISlider _depthSlider = new(0, 128); 25 | private UISlider _zPosSlider = new(-64, 64); 26 | private UISlider _noiseSlider = new(); 27 | 28 | private UIText _depthText = new("Depth"); 29 | private UIText _zPosText = new("ZPos"); 30 | private UIText _noiseText = new("Noise"); 31 | 32 | private UIText _innerPixelText = new("Inner Pixel"); 33 | 34 | private UITextPanel _enableButton = new("Enabled"); 35 | private UITextPanel _innerPixelButton = new("On"); 36 | 37 | private int _index; 38 | 39 | public UILayerEntry(int index) 40 | { 41 | _index = index; 42 | 43 | Width.Set(0, 1); 44 | SetPadding(6f); 45 | 46 | _layerName.Left.Pixels = 5; 47 | _layerName.Top.Pixels = 5; 48 | 49 | _depthSlider.Left.Pixels = 65; 50 | _depthSlider.Top.Pixels = 40; 51 | _depthSlider.Width.Pixels = 200; 52 | 53 | _zPosSlider.Left = _depthSlider.Left; 54 | _zPosSlider.Top.Pixels = _depthSlider.Top.Pixels + 25; 55 | _zPosSlider.Width = _depthSlider.Width; 56 | 57 | _noiseSlider.Left = _depthSlider.Left; 58 | _noiseSlider.Top.Pixels = _zPosSlider.Top.Pixels + 25; 59 | _noiseSlider.Width = _depthSlider.Width; 60 | 61 | _enableButton.HAlign = 1; 62 | _enableButton.VAlign = 1; 63 | _enableButton.Top.Pixels = -40; 64 | _enableButton.Left.Pixels = -70; 65 | 66 | _innerPixelButton.HAlign = 1; 67 | _innerPixelButton.VAlign = 1; 68 | _innerPixelButton.Top.Pixels = -5; 69 | _innerPixelButton.Left.Pixels = -5; 70 | 71 | _innerPixelText.HAlign = 1; 72 | _innerPixelText.VAlign = 1; 73 | _innerPixelText.Top.Pixels = _innerPixelButton.Top.Pixels + -10; 74 | _innerPixelText.Left.Pixels = -60; 75 | 76 | Height.Set(_noiseSlider.Top.Pixels + _noiseSlider.Height.Pixels + 20, 0); 77 | 78 | _depthText.Left = _layerName.Left; 79 | _depthText.Top = _depthSlider.Top; 80 | 81 | _zPosText.Left = _layerName.Left; 82 | _zPosText.Top = _zPosSlider.Top; 83 | 84 | _noiseText.Left = _layerName.Left; 85 | _noiseText.Top = _noiseSlider.Top; 86 | 87 | Append(_layerName); 88 | Append(_depthSlider); 89 | Append(_zPosSlider); 90 | Append(_noiseSlider); 91 | Append(_enableButton); 92 | Append(_innerPixelButton); 93 | Append(_innerPixelText); 94 | Append(_depthText); 95 | Append(_zPosText); 96 | Append(_noiseText); 97 | 98 | _depthSlider.ValueChanged += (_, value) => { if (_layer != null) _layer.Depth = value; }; 99 | _zPosSlider .ValueChanged += (_, value) => { if (_layer != null) _layer.ZPos = value; }; 100 | _noiseSlider.ValueChanged += (_, value) => { if (_layer != null) _layer.NoiseAmount = value; }; 101 | _enableButton.OnLeftClick += (_, _) => 102 | { 103 | _layer.Enabled = !_layer.Enabled; 104 | _enableButton.SetText(_layer.Enabled ? "Enabled" : "Disabled"); 105 | }; 106 | _innerPixelButton.OnLeftClick += (_, _) => 107 | { 108 | _layer.UseInnerPixel = !_layer.UseInnerPixel; 109 | _innerPixelButton.SetText(_layer.UseInnerPixel ? "On" : "Off"); 110 | }; 111 | } 112 | 113 | public void SetLayer(Layer3D layer) 114 | { 115 | _layer = layer; 116 | if (layer != null) 117 | { 118 | _layerName.SetText(layer.Name); 119 | _depthSlider.Value = layer.Depth; 120 | _zPosSlider.Value = layer.ZPos; 121 | _noiseSlider.Value = layer.NoiseAmount; 122 | _enableButton.SetText(_layer.Enabled ? "Enabled" : "Disabled"); 123 | _innerPixelButton.SetText(_layer.UseInnerPixel ? "On" : "Off"); 124 | } 125 | } 126 | 127 | protected override void DrawSelf(SpriteBatch spriteBatch) 128 | { 129 | base.DrawSelf(spriteBatch); 130 | var innerDimensions = GetInnerDimensions(); 131 | //draw divider 132 | Vector2 drawPos = new Vector2(innerDimensions.X + 5f, innerDimensions.Y + 30f); 133 | spriteBatch.Draw(_dividerTexture, drawPos, null, Color.White, 0f, Vector2.Zero, new Vector2((innerDimensions.Width - 10f) / 8f, 1f), SpriteEffects.None, 0f); 134 | } 135 | 136 | public override int CompareTo(object obj) 137 | { 138 | var other = obj as UILayerEntry; 139 | if (other != null) 140 | return _index - other._index; 141 | return 0; 142 | } 143 | 144 | } -------------------------------------------------------------------------------- /UI/Elements/UIListModifiedScrollAmount.cs: -------------------------------------------------------------------------------- 1 | using Terraria.GameContent.UI.Elements; 2 | using Terraria.UI; 3 | 4 | namespace Terraria3D.UI.Elements; 5 | 6 | public class UIListModifiedScrollAmount : UIList 7 | { 8 | public float ScrollModifier { get; set; } = 1; 9 | 10 | public override void ScrollWheel(UIScrollWheelEvent evt) 11 | { 12 | evt = new UIScrollWheelEvent(evt.Target, evt.MousePosition, (int)(evt.ScrollWheelValue * ScrollModifier)); 13 | base.ScrollWheel(evt); 14 | } 15 | } -------------------------------------------------------------------------------- /UI/Elements/UIListScrollView.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Terraria.GameContent.UI.Elements; 3 | using Terraria.UI; 4 | using Terraria.ModLoader.UI; 5 | 6 | namespace Terraria3D.UI.Elements; 7 | 8 | public class UIListScrollView : UIPanel 9 | { 10 | public UIListModifiedScrollAmount List { get; private set; } = new UIListModifiedScrollAmount(); 11 | public UIScrollbar ScrollBar { get; private set; } = new UIScrollbar(); 12 | 13 | public UIListScrollView() 14 | { 15 | List.ScrollModifier = 0.5f; 16 | 17 | ScrollBar.Height.Set(0, 1); 18 | ScrollBar.HAlign = 1f; 19 | 20 | List.SetScrollbar(ScrollBar); 21 | List.Width.Set(-30, 1); 22 | List.Height.Set(0, 1); 23 | 24 | Append(List); 25 | Append(ScrollBar); 26 | } 27 | } -------------------------------------------------------------------------------- /UI/Elements/UISlider.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Graphics; 3 | using Terraria.GameContent; 4 | using ReLogic.Content; 5 | using Terraria; 6 | using Terraria.Graphics; 7 | using Terraria.ModLoader; 8 | using Terraria.ModLoader.UI; 9 | using Terraria.UI; 10 | 11 | namespace Terraria3D.UI.Elements; 12 | 13 | public class UISlider : UIElement 14 | { 15 | protected static Texture2D _handleTexture = Terraria.GameContent.TextureAssets.ColorSlider.Value; 16 | protected static Texture2D _barTexture = Main.Assets.Request("Images/UI/ScrollbarInner", AssetRequestMode.ImmediateLoad).Value; 17 | 18 | public delegate void UISliderValueEvent(UISlider sender, float value); 19 | public event UISliderValueEvent ValueChanged; 20 | 21 | public float MinValue { get; } = 0; 22 | public float MaxValue { get; } = 1; 23 | public float Value 24 | { 25 | get { return _value; } 26 | set { _value = MathHelper.Clamp(value, MinValue, MaxValue); } 27 | } 28 | private float _value = 0; 29 | private bool _isDragging = false; 30 | 31 | public UISlider(float min = 0, float max = 1) 32 | { 33 | MinValue = min; 34 | MaxValue = max; 35 | Height.Set(20, 0); 36 | MaxHeight.Set(20, 0); 37 | Width.Set(100, 0); 38 | PaddingTop = 5f; 39 | PaddingBottom = 5f; 40 | } 41 | 42 | private void DrawBar(SpriteBatch spriteBatch, Texture2D texture, Rectangle dimensions, Color color) 43 | { 44 | var rot = MathHelper.ToRadians(-90); 45 | spriteBatch.Draw(texture, new Rectangle(dimensions.X - 6, dimensions.Y, dimensions.Height, 6), new Rectangle?(new Rectangle(0, 0, texture.Width, 6)), color, rot, Vector2.UnitX * dimensions.Height, SpriteEffects.None, 0); 46 | spriteBatch.Draw(texture, new Rectangle(dimensions.X, dimensions.Y, dimensions.Height, dimensions.Width), new Rectangle?(new Rectangle(0, 6, texture.Width, 4)), color, rot, Vector2.UnitX * dimensions.Height, SpriteEffects.None, 0); 47 | spriteBatch.Draw(texture, new Rectangle(dimensions.X + dimensions.Width, dimensions.Y, dimensions.Height, 6), new Rectangle?(new Rectangle(0, texture.Height - 6, texture.Width, 6)), color, rot, Vector2.UnitX * dimensions.Height, SpriteEffects.None, 0); 48 | } 49 | 50 | private void DrawHandle(SpriteBatch spriteBatch, Rectangle dimensions) 51 | { 52 | var x = (_value - MinValue) / (MaxValue - MinValue); 53 | x = MathHelper.Lerp(dimensions.Left, dimensions.Right, x); 54 | var pos = new Vector2(x - _handleTexture.Width * 0.5f, dimensions.Y - 2); 55 | spriteBatch.Draw(_handleTexture, pos, Color.White); 56 | } 57 | 58 | protected override void DrawSelf(SpriteBatch spriteBatch) 59 | { 60 | if (_isDragging) 61 | MoveSliderUnderMouse(); 62 | 63 | var dimensions = GetDimensions().ToRectangle(); 64 | 65 | DrawBar(spriteBatch, _barTexture, dimensions, Color.White * (_isDragging || ContainsPoint(Main.MouseScreen) ? 1f : 0.85f)); 66 | DrawHandle(spriteBatch, dimensions); 67 | } 68 | 69 | public override void LeftMouseDown(UIMouseEvent evt) 70 | { 71 | base.LeftMouseDown(evt); 72 | _isDragging = true; 73 | MoveSliderUnderMouse(); 74 | } 75 | 76 | public override void LeftMouseUp(UIMouseEvent evt) 77 | { 78 | base.LeftMouseUp(evt); 79 | _isDragging = false; 80 | } 81 | 82 | private void MoveSliderUnderMouse() 83 | { 84 | var prevValue = _value; 85 | var pos = UserInterface.ActiveInstance.MousePosition.X - GetInnerDimensions().X; 86 | Value = MathHelper.Lerp(MinValue, MaxValue, pos / Width.Pixels); 87 | if (prevValue != _value) 88 | ValueChanged?.Invoke(this, _value); 89 | } 90 | } -------------------------------------------------------------------------------- /UI/UISettingsWindow.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework.Graphics; 2 | using Terraria; 3 | using Terraria.GameContent.UI.Elements; 4 | using Terraria.GameInput; 5 | using Terraria3D.Serialization; 6 | using Terraria3D.UI.Elements; 7 | 8 | namespace Terraria3D; 9 | 10 | public class UISettingsWindow : UIWindow 11 | { 12 | private UIListScrollView _scrollView = new UIListScrollView(); 13 | private UIText _resetButton = new UIText("Reset"); 14 | private UIText _toggleAOButton = new UIText("Toggle AO"); 15 | 16 | 17 | public UISettingsWindow(string text) 18 | { 19 | Width.Set(600, 0); 20 | Height.Set(-200, 1); 21 | VAlign = 0.5f; 22 | HAlign = 0.5f; 23 | 24 | 25 | _scrollView.Width.Set(0, 1); 26 | _scrollView.Height.Set(-30, 1); 27 | 28 | _resetButton.VAlign = 1; 29 | _resetButton.Top.Set(-5, 0); 30 | _resetButton.OnLeftClick += (evt, listener) => Reset(); 31 | 32 | _toggleAOButton.VAlign = 1; 33 | _toggleAOButton.Top = _resetButton.Top; 34 | _toggleAOButton.Left.Pixels = 60; 35 | _toggleAOButton.OnLeftClick += (evt, listener) => Terraria3D.Instance.Scene.AmbientOcclusion = !Terraria3D.Instance.Scene.AmbientOcclusion; 36 | 37 | 38 | Append(_scrollView); 39 | Append(_resetButton); 40 | if (Renderers.SM3Enabled) 41 | Append(_toggleAOButton); 42 | 43 | Settings.SettingsLoaded += SettingsLoaded; 44 | } 45 | 46 | public override void OnActivate() 47 | { 48 | base.OnActivate(); 49 | RebuildLayerList(); 50 | } 51 | 52 | public void Dispose() => Settings.SettingsLoaded -= SettingsLoaded; 53 | 54 | private void SettingsLoaded(SettingsData data) => RebuildLayerList(); 55 | 56 | private void RebuildLayerList() 57 | { 58 | _scrollView.List.Clear(); 59 | var layers = Terraria3D.Instance.LayerManager.Layers; 60 | for (int i = 0; i < layers.Length; i++) 61 | _scrollView.List.Add(new UILayerEntry(i) { Layer = layers[i] }); 62 | } 63 | 64 | private void Reset() 65 | { 66 | Terraria3D.Instance.LayerManager.Rebuild(); 67 | RebuildLayerList(); 68 | } 69 | 70 | protected override void DrawSelf(SpriteBatch spriteBatch) 71 | { 72 | // Block cursor from clicking world. 73 | if (ContainsPoint(Main.MouseScreen) && !PlayerInput.IgnoreMouseInterface) 74 | Main.LocalPlayer.mouseInterface = true; 75 | base.DrawSelf(spriteBatch); 76 | } 77 | } -------------------------------------------------------------------------------- /UI/UITerraria3D.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Xna.Framework; 3 | using System.Collections.Generic; 4 | using Terraria.UI; 5 | 6 | namespace Terraria3D; 7 | 8 | public static class UITerraria3D 9 | { 10 | public static UserInterfaceSettings SettingsInterface { get; private set; } 11 | public static UserInterfaceOverlay OverlayInterface { get; private set; } 12 | 13 | 14 | public static void Load() 15 | { 16 | //Console.Write("Adding interface"); 17 | SettingsInterface = new UserInterfaceSettings("Settings"); 18 | OverlayInterface = new UserInterfaceOverlay("Overlay"); 19 | } 20 | 21 | public static void Unload() 22 | { 23 | SettingsInterface.Dispose(); 24 | OverlayInterface.Dispose(); 25 | SettingsInterface = null; 26 | OverlayInterface = null; 27 | } 28 | 29 | public static void Update(GameTime gameTime) 30 | { 31 | SettingsInterface.UpdateIfVisible(gameTime); 32 | OverlayInterface.UpdateIfVisible(gameTime); 33 | } 34 | 35 | public static void ModifyInterfaceLayers(List layers) 36 | { 37 | //Console.Write("Adding interface"); 38 | SettingsInterface.InsertIntoLayers("Vanilla: Mouse Text", layers); 39 | OverlayInterface.InsertIntoLayers("Vanilla: Mouse Text", layers); 40 | } 41 | } -------------------------------------------------------------------------------- /UI/UIWindow.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using System.Reflection; 3 | using Terraria.GameContent.UI.Elements; 4 | using Terraria.GameInput; 5 | using Terraria.UI; 6 | 7 | namespace Terraria3D; 8 | 9 | public class UIWindow : UIPanel 10 | { 11 | public bool Draggable { get; set; } 12 | private bool _dragging = false; 13 | private Vector2 _prevMousePos; 14 | 15 | public UIWindow() 16 | { 17 | Draggable = true; 18 | OnLeftMouseDown += UIWindow_OnMouseDown; 19 | OnLeftMouseUp += UIWindow_OnMouseUp; 20 | Activate(); 21 | } 22 | 23 | void UIWindow_OnMouseDown(UIMouseEvent evt, UIElement listeningElement) 24 | { 25 | if (evt.Target == this) 26 | _dragging = true; 27 | } 28 | void UIWindow_OnMouseUp(UIMouseEvent evt, UIElement listeningElement) 29 | { 30 | _dragging = false; 31 | } 32 | 33 | public override void Recalculate() 34 | { 35 | if (_dragging) 36 | { 37 | Left.Set(Left.Pixels + PlayerInput.MouseX - _prevMousePos.X, 0); 38 | Top.Set(Top.Pixels + PlayerInput.MouseY - _prevMousePos.Y, 0); 39 | 40 | var parentDimensions = Parent.GetDimensions().ToRectangle(); 41 | Left.Pixels = MathHelper.Clamp(Left.Pixels, 0, parentDimensions.Right - Width.Pixels); 42 | Top.Pixels = MathHelper.Clamp(Top.Pixels, 0, parentDimensions.Bottom - Height.Pixels); 43 | } 44 | _prevMousePos = new Vector2(PlayerInput.MouseX, PlayerInput.MouseY); 45 | base.Recalculate(); 46 | } 47 | } -------------------------------------------------------------------------------- /UI/UserInterfaces/GenericUserInterface.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using System.Collections.Generic; 3 | using Terraria; 4 | using Terraria.UI; 5 | 6 | namespace Terraria3D; 7 | 8 | public class GenericUserInterface : UserInterface 9 | { 10 | public UIState State { get; protected set; } 11 | public string LayerName { get; private set; } 12 | public bool Visible { get; set; } = true; 13 | 14 | public GenericUserInterface(string layerName) 15 | { 16 | State = CreateState(); 17 | SetState(State); 18 | State.Activate(); 19 | LayerName = string.Format("{0}: {1}", Terraria3D.Instance.DisplayName, layerName); 20 | } 21 | 22 | protected virtual UIState CreateState() => new UIState(); 23 | 24 | public virtual void Dispose() 25 | { 26 | SetState(null); 27 | State.Deactivate(); 28 | State = null; 29 | } 30 | 31 | public void UpdateIfVisible(GameTime gameTime) 32 | { 33 | if (Visible) 34 | Update(gameTime); 35 | } 36 | 37 | public void InsertIntoLayers(string layerName, List layers, 38 | InterfaceScaleType scaleType = InterfaceScaleType.UI) 39 | { 40 | int layerIndex = layers.FindIndex(layer => layer.Name.Equals(layerName)); 41 | if (layerIndex != -1) 42 | { 43 | layers.Insert(layerIndex, new LegacyGameInterfaceLayer(LayerName, () => 44 | { 45 | if (Visible) 46 | Draw(Main.spriteBatch, new GameTime()); 47 | return true; 48 | }, scaleType)); 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /UI/UserInterfaces/UserInterfaceOverlay.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Graphics; 3 | using ReLogic.Content; 4 | using Terraria; 5 | using Terraria.GameContent.UI.Elements; 6 | using Terraria.ModLoader; 7 | using Terraria.UI; 8 | 9 | namespace Terraria3D; 10 | 11 | public class UserInterfaceOverlay : GenericUserInterface 12 | { 13 | public UserInterfaceOverlay(string layerName) : base(layerName) { State.Recalculate(); } 14 | protected override UIState CreateState() => new OverlayState(); 15 | 16 | public override void Dispose() 17 | { 18 | base.Dispose(); 19 | (State as OverlayState)?.Dispose(); 20 | } 21 | } 22 | 23 | class OverlayState : UIState 24 | { 25 | private static Texture2D _cameraIcon => ModContent.Request("Terraria3D/Images/CameraIcon", AssetRequestMode.ImmediateLoad).Value; 26 | 27 | private UIImage _editCameraIcon = new UIImage(_cameraIcon); 28 | private UICameraControlsPanel _controlsPanel = new UICameraControlsPanel(); 29 | private UIText _editCameraHoverTip = new UIText("Edit Camera"); 30 | private UITextPanel _toggleControlsPanelButton = new UITextPanel("Hide Controls"); 31 | 32 | public OverlayState() : base() 33 | { 34 | _editCameraIcon.Recalculate(); 35 | _editCameraIcon.VAlign = 1; 36 | _editCameraIcon.Left.Pixels = 20; 37 | _editCameraIcon.Top.Pixels = -20; 38 | _editCameraIcon.OnLeftClick += (evt, listener) => 39 | InputTerraria3D.CameraControlsEnabled = !InputTerraria3D.CameraControlsEnabled; 40 | 41 | _controlsPanel.VAlign = 1; 42 | _controlsPanel.Left.Pixels = 20; 43 | _controlsPanel.Top.Pixels = -100; 44 | 45 | _editCameraHoverTip.VAlign = 1; 46 | _editCameraHoverTip.Left.Pixels = 20; 47 | _editCameraHoverTip.Top.Pixels = -70; 48 | 49 | _toggleControlsPanelButton.VAlign = 1; 50 | _toggleControlsPanelButton.Left.Pixels = 80; 51 | _toggleControlsPanelButton.Top.Pixels = -15; 52 | _toggleControlsPanelButton.OnLeftClick += (evt, listener) => 53 | { 54 | if (InputTerraria3D.CameraControlsEnabled) 55 | { 56 | _controlsPanel.Visible = !_controlsPanel.Visible; 57 | _toggleControlsPanelButton.SetText(_controlsPanel.Visible ? "Hide Controls" : "ShowControls"); 58 | } 59 | }; 60 | 61 | 62 | Append(_controlsPanel); 63 | Append(_editCameraIcon); 64 | Append(_editCameraHoverTip); 65 | Append(_toggleControlsPanelButton); 66 | } 67 | 68 | public void Dispose() => _controlsPanel.Dispose(); 69 | 70 | protected override void DrawChildren(SpriteBatch spriteBatch) 71 | { 72 | if (!Terraria3D.Enabled) return; 73 | if (!Main.playerInventory && !InputTerraria3D.CameraControlsEnabled) return; 74 | 75 | if (InputTerraria3D.CameraControlsEnabled) 76 | { 77 | _controlsPanel.Draw(spriteBatch); 78 | _toggleControlsPanelButton.Draw(spriteBatch); 79 | } 80 | _editCameraIcon.Draw(spriteBatch); 81 | if (_editCameraIcon.ContainsPoint(Main.MouseScreen)) 82 | _editCameraHoverTip.Draw(spriteBatch); 83 | } 84 | } -------------------------------------------------------------------------------- /UI/UserInterfaces/UserInterfaceSettings.cs: -------------------------------------------------------------------------------- 1 | using Terraria.UI; 2 | 3 | namespace Terraria3D; 4 | 5 | public class UserInterfaceSettings : GenericUserInterface 6 | { 7 | private UISettingsWindow _settingsWindow; 8 | 9 | public UserInterfaceSettings(string layerName) : base (layerName) 10 | { 11 | Visible = false; 12 | _settingsWindow = new UISettingsWindow("Settings"); 13 | State.Append(_settingsWindow); 14 | } 15 | 16 | public override void Dispose() 17 | { 18 | base.Dispose(); 19 | _settingsWindow?.Dispose(); 20 | _settingsWindow = null; 21 | } 22 | } -------------------------------------------------------------------------------- /Utils/Loading.cs: -------------------------------------------------------------------------------- 1 | using Terraria; 2 | using Terraria.ID; 3 | 4 | namespace Terraria3D; 5 | 6 | public static class Loading 7 | { 8 | public static void Load(Terraria3D instance) 9 | { 10 | Main.QueueMainThreadAction(() => 11 | { 12 | Renderers.Load(); 13 | instance.Scene = new Scene3D(); 14 | instance.LayerManager = new LayerManager(); 15 | UITerraria3D.Load(); 16 | Settings.Load(); 17 | Hooks.Initialize(); 18 | InputTerraria3D.Load(); 19 | }); 20 | 21 | } 22 | 23 | public static void Unload(Terraria3D instance) 24 | { 25 | Main.QueueMainThreadAction(() => 26 | { 27 | UITerraria3D.Unload(); 28 | instance.Scene = null; 29 | instance.LayerManager?.Dispose(); 30 | instance.LayerManager = null; 31 | Renderers.Unload(); 32 | InputTerraria3D.Unload(); 33 | }); 34 | } 35 | } -------------------------------------------------------------------------------- /Utils/Utils.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Graphics; 3 | using System; 4 | using Terraria; 5 | 6 | namespace Terraria3D; 7 | 8 | public static class Utils 9 | { 10 | private static float _prevZoom; 11 | 12 | public static RenderTarget2D CreateRenderTarget(bool PoT = false) 13 | => CreateRenderTarget(Screen.Width, Screen.Height, PoT); 14 | 15 | // PoT: Make power of two 16 | public static RenderTarget2D CreateRenderTarget(int width, int height, bool PoT = false) 17 | { 18 | if(PoT) 19 | { 20 | width = GetSmallestPoT(width); 21 | height = GetSmallestPoT(height); 22 | } 23 | var g = Main.graphics.GraphicsDevice; 24 | return new RenderTarget2D(g, width, height, false, g.PresentationParameters.BackBufferFormat, DepthFormat.Depth24); 25 | } 26 | 27 | public static int GetSmallestPoT(int value) 28 | { 29 | return (int)Math.Pow(2, Math.Ceiling(Math.Log(value, 2))); 30 | } 31 | 32 | public static RenderTarget2D GetCurrentRenderTarget() 33 | { 34 | RenderTarget2D result = null; 35 | var bindings = Main.graphics.GraphicsDevice.GetRenderTargets(); 36 | if (bindings.Length > 0) 37 | result = bindings[0].RenderTarget as RenderTarget2D; 38 | return result; 39 | } 40 | 41 | public static void SetZoom(float zoom) 42 | { 43 | _prevZoom = Main.GameZoomTarget; 44 | Main.GameZoomTarget = zoom; 45 | UpdateGameViewMatrixZoom(); 46 | } 47 | public static void RestoreOldZoom() 48 | { 49 | Main.GameZoomTarget = _prevZoom; 50 | UpdateGameViewMatrixZoom(); 51 | } 52 | public static void UpdateGameViewMatrixZoom() 53 | => Main.GameViewMatrix.Zoom = new Vector2(Main.ForcedMinimumZoom * MathHelper.Clamp(Main.GameZoomTarget, 1f, 2f)); 54 | } -------------------------------------------------------------------------------- /app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /build.txt: -------------------------------------------------------------------------------- 1 | author = Matt Thompson - chatrat12 & SimonR - DoctorBones 2 | version = 1.0.6 3 | displayName = Terraria3D 4 | includePDB = false 5 | languageVersion = 10 6 | side = Client 7 | homepage = https://github.com/chatrat12/Terraria3D 8 | buildIgnore = README.md, LICENSE, packages/*, properties/*, .gitattributes, .gitignore, .git/, .vs/, .idea/, bin/, obj/, lib/*, Effects/Compiler/*, Thumbs.db, *.csproj, *.fx, *.config, *.user -------------------------------------------------------------------------------- /description.txt: -------------------------------------------------------------------------------- 1 | Thank you for checking out Terraria3D. This mod has been updated for 1.4 but has issues. It's hard to find time to work on this. 2 | 3 | Issues: 4 | - Jitters if resolution has an odd number in it. 5 | - Visual glitches if terraria start limiting blocks on screen for high resolution monitors. 6 | - Some things may not render accurately. Mileage may very in different color modes. 7 | 8 | Check out keybindings to open the settings menu. 9 | 10 | FAQ 11 | Q: How do I move the camera? 12 | A: You can either bind the 'Toggle Camera Controls' hotkey or you can open up your inventory and then click the camera icon on the bottom left of the screen. 13 | Q: This sucks! My FPS went in the toilet! Optimize your mod! 14 | A: I'm sorry to hear that. Unfortunately the 3D does not come free. You will need a decent dedicated graphics processor to run this mod effectively. There is not much head room for optimization unfortunately. 15 | -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/prgmatic/Terraria3D/2a84c8fc535ee8ad0496f3fbd2e30de855881f31/icon.png --------------------------------------------------------------------------------