From 8f089dc2ab6cc094fca7780d5597ef3118066ba8 Mon Sep 17 00:00:00 2001 From: Halofreak1990 Date: Sat, 4 Dec 2010 16:14:34 +0000 Subject: [PATCH] Added the current XFX directory tree. WARNING!!! This revision cannot compile correctly. It is updated to reflect the many changes within the XFX project. --- XFX.sln | 51 + include/Audio.h | 27 + include/Audio/AudioCategory.h | 19 + include/Audio/AudioEmitter.h | 33 + include/Audio/AudioEngine.h | 39 + include/Audio/AudioListener.h | 32 + include/Audio/AudioStopOptions.h | 22 + include/Audio/Cue.h | 40 + include/Audio/SoundState.h | 14 + include/Audio/Soundbank.h | 26 + include/Audio/WaveBank.h | 30 + include/Audio/XACT.h | 28 + include/Audio/wave.h | 31 + include/BoundingBox.h | 61 + include/BoundingFrustrum.h | 85 + include/BoundingSphere.h | 34 + include/Content/ContentLoadException.h | 23 + include/Content/ContentManager.h | 58 + include/Content/ContentReader.h | 74 + include/Enums.h | 110 + include/Game.h | 168 + include/GameComponentCollection.h | 31 + include/GameComponentCollectionEventArgs.h | 30 + include/GamePadCapabilities.h | 45 + include/GamePadDPad.h | 37 + include/GamePadThumbSticks.h | 34 + include/GamePadTriggers.h | 31 + include/GameServiceContainer.h | 28 + include/GameTime.h | 42 + include/GamerServices/Enums.h | 104 + include/GamerServices/GamerServices.h | 0 .../GamerServices/GamerServicesComponent.h | 30 + include/GamerServices/Guide.h | 44 + include/Graphics.h | 32 + include/Graphics/BasicDirectionalLight.h | 30 + include/Graphics/BasicEffect.h | 60 + include/Graphics/Color.h | 198 + include/Graphics/DepthStencilBuffer.h | 51 + include/Graphics/DisplayMode.h | 41 + include/Graphics/DisplayModeCollection.h | 19 + include/Graphics/Effect.h | 67 + include/Graphics/Enums.h | 773 +++ include/Graphics/GraphicsAdapter.h | 64 + include/Graphics/GraphicsDevice.h | 95 + include/Graphics/GraphicsDeviceCapabilities.h | 182 + include/Graphics/GraphicsResource.h | 54 + include/Graphics/IGraphicsDeviceService.h | 33 + include/Graphics/IPackedVector.h | 33 + include/Graphics/PackedVector/IPackedVector.h | 44 + include/Graphics/PresentationParameters.h | 65 + include/Graphics/SpriteBatch.h | 65 + include/Graphics/Texture.h | 58 + include/Graphics/Texture2D.h | 74 + include/Graphics/TextureCollection.h | 39 + include/Graphics/TextureCreationParameters.h | 48 + include/Graphics/TextureInformation.h | 44 + include/Graphics/VertexElement.h | 41 + .../Graphics/VertexPositionNormalTexture.h | 44 + include/Graphics/VertexPositionTexture.h | 43 + include/Graphics/Viewport.h | 36 + include/GraphicsDeviceInformation.h | 31 + include/GraphicsDeviceManager.h | 60 + include/Input.h | 34 + include/Input/Enums.h | 111 + include/Input/GamePad.h | 32 + include/Input/GamePadButtons.h | 68 + include/Input/GamePadState.h | 39 + include/Input/Keyboard.h | 41 + include/Input/Mouse.h | 48 + include/Interfaces.h | 74 + include/Keys.h | 250 + include/MathHelper.h | 43 + include/Matrix.h | 144 + include/Media/Enums.h | 58 + include/Media/Video.h | 32 + include/Media/VideoPlayer.h | 53 + include/Net/Enums.h | 87 + include/Net/NetworkException.h | 39 + include/Plane.h | 65 + include/Point.h | 32 + include/Quaternion.h | 76 + include/Ray.h | 47 + include/Rectangle.h | 50 + include/Storage.h | 13 + include/Storage/StorageContainer.h | 47 + include/Storage/StorageDevice.h | 40 + .../StorageDeviceNotConnectedException.h | 29 + include/System.h | 30 + include/System/Array.h | 27 + include/System/BitConverter.h | 47 + include/System/Buffer.h | 31 + include/System/Collections/Generic/Comparer.h | 34 + .../System/Collections/Generic/Dictionary.h | 123 + .../Collections/Generic/EqualityComparer.h | 28 + .../System/Collections/Generic/Interfaces.h | 111 + .../Generic/KeyNotFoundException.h | 33 + .../System/Collections/Generic/KeyValuePair.h | 37 + include/System/Collections/Generic/List.h | 72 + include/System/Collections/IList.h | 24 + include/System/Collections/Interfaces.h | 12 + include/System/DateTime.h | 130 + include/System/Delegates.h | 26 + include/System/Enums.h | 95 + include/System/Environment.h | 41 + include/System/EventArgs.h | 26 + include/System/Exception.h | 239 + include/System/Globalization/Calendar.h | 27 + include/System/Globalization/CultureInfo.h | 17 + include/System/Globalization/DaylightTime.h | 31 + include/System/Globalization/Enums.h | 124 + include/System/IO/BinaryReader.h | 61 + include/System/IO/Directory.h | 51 + include/System/IO/DirectoryInfo.h | 45 + include/System/IO/Enums.h | 97 + include/System/IO/FileStream.h | 71 + include/System/IO/FileSystemInfo.h | 16 + include/System/IO/IOException.h | 68 + include/System/IO/MemoryStream.h | 63 + include/System/IO/Path.h | 55 + include/System/IO/Stream.h | 63 + include/System/IO/StreamAsyncResult.h | 45 + include/System/IO/StreamReader.h | 57 + include/System/IO/StreamWriter.h | 69 + include/System/IO/TextReader.h | 36 + include/System/IO/TextWriter.h | 66 + include/System/IO/file.h | 63 + include/System/Interfaces.h | 71 + include/System/Math.h | 87 + include/System/Object.h | 28 + include/System/OperatingSystem.h | 36 + include/System/Stack.h | 43 + include/System/String.h | 87 + include/System/Text/ASCIIEncoding.h | 35 + include/System/Text/Decoder.h | 42 + include/System/Text/Encoder.h | 29 + include/System/Text/Encoding.h | 68 + include/System/Threading/Enums.h | 48 + include/System/Threading/Thread.h | 63 + include/System/Threading/ThreadState.h | 35 + include/System/Threading/WaitHandle.h | 37 + include/System/TimeSpan.h | 79 + include/System/TimeZone.h | 40 + include/System/Types.h | 50 + include/System/Version.h | 51 + include/System/XKUtils/APICompat.h | 50 + include/System/XKUtils/XKCRC.h | 77 + include/System/XKUtils/XKEEPROM.h | 270 + include/System/XKUtils/XKFlash.h | 40 + include/System/XKUtils/XKGeneral.h | 95 + include/System/XKUtils/XKHDD.h | 344 ++ include/System/XKUtils/XKRC4.h | 103 + include/System/XKUtils/XKSHA1.h | 140 + include/System/XKUtils/XKStrings.h | 45 + include/System/XKUtils/XKUtils.h | 296 + include/System/XKUtils/flashtypes.h | 175 + include/System/Xml/XPath/XPathException.h | 19 + include/System/Xml/Xsl/XsltException.h | 30 + include/System/misc.h | 20 + include/Thread.h | 61 + include/ThreadState.h | 30 + include/Vector2.h | 102 + include/Vector3.h | 116 + include/Vector4.h | 111 + include/XFX.h | 43 + src/Layout XFX.txt | 64 + src/libSystem.Xml/libSystem.Xml.vcproj | 160 + src/libSystem.Xml/makefile | 53 + src/libSystem/IDisposable.h | 19 + src/libSystem/IServiceProvider.h | 14 + src/libSystem/System.h | 35 + src/libSystem/Thread.h | 63 + src/libSystem/ThreadState.h | 30 + src/libSystem/TimeSpan.h | 48 + src/libSystem/libSystem.vcproj | 150 + src/libXFX.Game/DrawableGameComponent.cpp | 105 + src/libXFX.Game/Game.cpp | 207 + src/libXFX.Game/GameComponent.cpp | 120 + src/libXFX.Game/GameTime.cpp | 64 + src/libXFX.Game/GamerServicesComponent.cpp | 49 + src/libXFX.Game/GraphicsDeviceManager.cpp | 93 + src/libXFX.Game/libXFX.Game.vcproj | 197 + src/libXFX.Game/makefile | 55 + src/libXFX/BasicEffect.cpp | 68 + src/libXFX/BoundingBox.cpp | 309 + src/libXFX/BoundingFrustrum.cpp | 467 ++ src/libXFX/BoundingSphere.cpp | 67 + src/libXFX/Color.cpp | 284 + src/libXFX/ContentManager.cpp | 180 + src/libXFX/ContentReader.cpp | 86 + src/libXFX/DepthStencilBuffer.cpp | 73 + src/libXFX/DisplayMode.cpp | 80 + src/libXFX/GamePad.cpp | 171 + src/libXFX/GraphicsAdapter.cpp | 150 + src/libXFX/GraphicsDevice.cpp | 170 + src/libXFX/GraphicsDeviceCapabilities.cpp | 96 + src/libXFX/GraphicsResource.cpp | 85 + src/libXFX/Keyboard.cpp | 100 + src/libXFX/MathHelper.cpp | 111 + src/libXFX/Matrix.cpp | 1315 +++++ src/libXFX/Mouse.cpp | 99 + src/libXFX/PBKit/nv20_shader.h | 132 + src/libXFX/PBKit/nv_objects.h | 1782 ++++++ src/libXFX/PBKit/outer.h | 524 ++ src/libXFX/PBKit/pbKit.cpp | 5224 +++++++++++++++++ src/libXFX/PBKit/pbKit.h | 101 + src/libXFX/PBKit/ps.h | 13 + src/libXFX/PBKit/vs.h | 14 + src/libXFX/Plane.cpp | 325 + src/libXFX/Point.cpp | 73 + src/libXFX/PresentationParameters.cpp | 139 + src/libXFX/Quaternion.cpp | 682 +++ src/libXFX/Ray.cpp | 262 + src/libXFX/Rectangle.cpp | 160 + src/libXFX/SpriteBatch.cpp | 325 + src/libXFX/StorageContainer.cpp | 110 + src/libXFX/StorageDevice.cpp | 55 + .../StorageDeviceNotConnectedException.cpp | 48 + src/libXFX/Texture.cpp | 98 + src/libXFX/Texture2D.cpp | 155 + src/libXFX/TextureCreationParameters.cpp | 107 + src/libXFX/TextureInformation.cpp | 106 + src/libXFX/Vector2.cpp | 526 ++ src/libXFX/Vector3.cpp | 672 +++ src/libXFX/Vector4.cpp | 650 ++ src/libXFX/VertexElement.cpp | 65 + src/libXFX/VertexPositionNormalTexture.cpp | 66 + src/libXFX/VertexPositionTexture.cpp | 68 + src/libXFX/VideoPlayer.cpp | 58 + src/libXFX/Viewport.cpp | 82 + src/libXFX/libXFX.vcproj | 629 ++ src/libXFX/makefile | 65 + src/libXFX/usb/hub.cpp | 1199 ++++ src/libXFX/usb/hub.h | 406 ++ src/libXFX/usb/ohci.cpp | 733 +++ src/libXFX/usb/ohci.h | 240 + src/libXFX/usb/pad.cpp | 404 ++ src/libXFX/usb/pad.h | 84 + src/libXFX/usb/xinput.cpp | 354 ++ src/libXFX/usb/xinput.h | 86 + src/libmscorlib/Array.cpp | 77 + src/libmscorlib/BinaryReader.cpp | 255 + src/libmscorlib/BitConverter.cpp | 166 + src/libmscorlib/Buffer.cpp | 83 + src/libmscorlib/Calendar.cpp | 49 + src/libmscorlib/Comparer.cpp | 12 + src/libmscorlib/DateTime.cpp | 417 ++ src/libmscorlib/Decoder.cpp | 141 + src/libmscorlib/Dictionary.cpp | 328 ++ src/libmscorlib/Directory.cpp | 62 + src/libmscorlib/Encoder.cpp | 58 + src/libmscorlib/Encoding.cpp | 36 + src/libmscorlib/Environment.cpp | 81 + src/libmscorlib/Exception.cpp | 82 + src/libmscorlib/File.cpp | 218 + src/libmscorlib/FileStream.cpp | 361 ++ src/libmscorlib/HashHelpers.cpp | 77 + src/libmscorlib/HashHelpers.h | 32 + src/libmscorlib/IOException.cpp | 88 + src/libmscorlib/KeyNotFoundException.cpp | 52 + src/libmscorlib/KeyValuePair.cpp | 63 + src/libmscorlib/Math.cpp | 309 + src/libmscorlib/MemoryStream.cpp | 513 ++ src/libmscorlib/Object.cpp | 43 + src/libmscorlib/Path.cpp | 161 + src/libmscorlib/Stream.cpp | 142 + src/libmscorlib/StreamAsyncResult.cpp | 89 + src/libmscorlib/StreamReader.cpp | 36 + src/libmscorlib/StreamWriter.cpp | 60 + src/libmscorlib/String.cpp | 365 ++ src/libmscorlib/SystemException.cpp | 196 + src/libmscorlib/TextureCollection.cpp | 77 + src/libmscorlib/Thread.cpp | 139 + src/libmscorlib/TimeSpan.cpp | 320 + src/libmscorlib/Version.cpp | 127 + src/libmscorlib/libmscorlib.vcproj | 548 ++ src/libmscorlib/makefile | 53 + src/libmscorlib/misc.cpp | 182 + 277 files changed, 39181 insertions(+) create mode 100644 XFX.sln create mode 100644 include/Audio.h create mode 100644 include/Audio/AudioCategory.h create mode 100644 include/Audio/AudioEmitter.h create mode 100644 include/Audio/AudioEngine.h create mode 100644 include/Audio/AudioListener.h create mode 100644 include/Audio/AudioStopOptions.h create mode 100644 include/Audio/Cue.h create mode 100644 include/Audio/SoundState.h create mode 100644 include/Audio/Soundbank.h create mode 100644 include/Audio/WaveBank.h create mode 100644 include/Audio/XACT.h create mode 100644 include/Audio/wave.h create mode 100644 include/BoundingBox.h create mode 100644 include/BoundingFrustrum.h create mode 100644 include/BoundingSphere.h create mode 100644 include/Content/ContentLoadException.h create mode 100644 include/Content/ContentManager.h create mode 100644 include/Content/ContentReader.h create mode 100644 include/Enums.h create mode 100644 include/Game.h create mode 100644 include/GameComponentCollection.h create mode 100644 include/GameComponentCollectionEventArgs.h create mode 100644 include/GamePadCapabilities.h create mode 100644 include/GamePadDPad.h create mode 100644 include/GamePadThumbSticks.h create mode 100644 include/GamePadTriggers.h create mode 100644 include/GameServiceContainer.h create mode 100644 include/GameTime.h create mode 100644 include/GamerServices/Enums.h create mode 100644 include/GamerServices/GamerServices.h create mode 100644 include/GamerServices/GamerServicesComponent.h create mode 100644 include/GamerServices/Guide.h create mode 100644 include/Graphics.h create mode 100644 include/Graphics/BasicDirectionalLight.h create mode 100644 include/Graphics/BasicEffect.h create mode 100644 include/Graphics/Color.h create mode 100644 include/Graphics/DepthStencilBuffer.h create mode 100644 include/Graphics/DisplayMode.h create mode 100644 include/Graphics/DisplayModeCollection.h create mode 100644 include/Graphics/Effect.h create mode 100644 include/Graphics/Enums.h create mode 100644 include/Graphics/GraphicsAdapter.h create mode 100644 include/Graphics/GraphicsDevice.h create mode 100644 include/Graphics/GraphicsDeviceCapabilities.h create mode 100644 include/Graphics/GraphicsResource.h create mode 100644 include/Graphics/IGraphicsDeviceService.h create mode 100644 include/Graphics/IPackedVector.h create mode 100644 include/Graphics/PackedVector/IPackedVector.h create mode 100644 include/Graphics/PresentationParameters.h create mode 100644 include/Graphics/SpriteBatch.h create mode 100644 include/Graphics/Texture.h create mode 100644 include/Graphics/Texture2D.h create mode 100644 include/Graphics/TextureCollection.h create mode 100644 include/Graphics/TextureCreationParameters.h create mode 100644 include/Graphics/TextureInformation.h create mode 100644 include/Graphics/VertexElement.h create mode 100644 include/Graphics/VertexPositionNormalTexture.h create mode 100644 include/Graphics/VertexPositionTexture.h create mode 100644 include/Graphics/Viewport.h create mode 100644 include/GraphicsDeviceInformation.h create mode 100644 include/GraphicsDeviceManager.h create mode 100644 include/Input.h create mode 100644 include/Input/Enums.h create mode 100644 include/Input/GamePad.h create mode 100644 include/Input/GamePadButtons.h create mode 100644 include/Input/GamePadState.h create mode 100644 include/Input/Keyboard.h create mode 100644 include/Input/Mouse.h create mode 100644 include/Interfaces.h create mode 100644 include/Keys.h create mode 100644 include/MathHelper.h create mode 100644 include/Matrix.h create mode 100644 include/Media/Enums.h create mode 100644 include/Media/Video.h create mode 100644 include/Media/VideoPlayer.h create mode 100644 include/Net/Enums.h create mode 100644 include/Net/NetworkException.h create mode 100644 include/Plane.h create mode 100644 include/Point.h create mode 100644 include/Quaternion.h create mode 100644 include/Ray.h create mode 100644 include/Rectangle.h create mode 100644 include/Storage.h create mode 100644 include/Storage/StorageContainer.h create mode 100644 include/Storage/StorageDevice.h create mode 100644 include/Storage/StorageDeviceNotConnectedException.h create mode 100644 include/System.h create mode 100644 include/System/Array.h create mode 100644 include/System/BitConverter.h create mode 100644 include/System/Buffer.h create mode 100644 include/System/Collections/Generic/Comparer.h create mode 100644 include/System/Collections/Generic/Dictionary.h create mode 100644 include/System/Collections/Generic/EqualityComparer.h create mode 100644 include/System/Collections/Generic/Interfaces.h create mode 100644 include/System/Collections/Generic/KeyNotFoundException.h create mode 100644 include/System/Collections/Generic/KeyValuePair.h create mode 100644 include/System/Collections/Generic/List.h create mode 100644 include/System/Collections/IList.h create mode 100644 include/System/Collections/Interfaces.h create mode 100644 include/System/DateTime.h create mode 100644 include/System/Delegates.h create mode 100644 include/System/Enums.h create mode 100644 include/System/Environment.h create mode 100644 include/System/EventArgs.h create mode 100644 include/System/Exception.h create mode 100644 include/System/Globalization/Calendar.h create mode 100644 include/System/Globalization/CultureInfo.h create mode 100644 include/System/Globalization/DaylightTime.h create mode 100644 include/System/Globalization/Enums.h create mode 100644 include/System/IO/BinaryReader.h create mode 100644 include/System/IO/Directory.h create mode 100644 include/System/IO/DirectoryInfo.h create mode 100644 include/System/IO/Enums.h create mode 100644 include/System/IO/FileStream.h create mode 100644 include/System/IO/FileSystemInfo.h create mode 100644 include/System/IO/IOException.h create mode 100644 include/System/IO/MemoryStream.h create mode 100644 include/System/IO/Path.h create mode 100644 include/System/IO/Stream.h create mode 100644 include/System/IO/StreamAsyncResult.h create mode 100644 include/System/IO/StreamReader.h create mode 100644 include/System/IO/StreamWriter.h create mode 100644 include/System/IO/TextReader.h create mode 100644 include/System/IO/TextWriter.h create mode 100644 include/System/IO/file.h create mode 100644 include/System/Interfaces.h create mode 100644 include/System/Math.h create mode 100644 include/System/Object.h create mode 100644 include/System/OperatingSystem.h create mode 100644 include/System/Stack.h create mode 100644 include/System/String.h create mode 100644 include/System/Text/ASCIIEncoding.h create mode 100644 include/System/Text/Decoder.h create mode 100644 include/System/Text/Encoder.h create mode 100644 include/System/Text/Encoding.h create mode 100644 include/System/Threading/Enums.h create mode 100644 include/System/Threading/Thread.h create mode 100644 include/System/Threading/ThreadState.h create mode 100644 include/System/Threading/WaitHandle.h create mode 100644 include/System/TimeSpan.h create mode 100644 include/System/TimeZone.h create mode 100644 include/System/Types.h create mode 100644 include/System/Version.h create mode 100644 include/System/XKUtils/APICompat.h create mode 100644 include/System/XKUtils/XKCRC.h create mode 100644 include/System/XKUtils/XKEEPROM.h create mode 100644 include/System/XKUtils/XKFlash.h create mode 100644 include/System/XKUtils/XKGeneral.h create mode 100644 include/System/XKUtils/XKHDD.h create mode 100644 include/System/XKUtils/XKRC4.h create mode 100644 include/System/XKUtils/XKSHA1.h create mode 100644 include/System/XKUtils/XKStrings.h create mode 100644 include/System/XKUtils/XKUtils.h create mode 100644 include/System/XKUtils/flashtypes.h create mode 100644 include/System/Xml/XPath/XPathException.h create mode 100644 include/System/Xml/Xsl/XsltException.h create mode 100644 include/System/misc.h create mode 100644 include/Thread.h create mode 100644 include/ThreadState.h create mode 100644 include/Vector2.h create mode 100644 include/Vector3.h create mode 100644 include/Vector4.h create mode 100644 include/XFX.h create mode 100644 src/Layout XFX.txt create mode 100644 src/libSystem.Xml/libSystem.Xml.vcproj create mode 100644 src/libSystem.Xml/makefile create mode 100644 src/libSystem/IDisposable.h create mode 100644 src/libSystem/IServiceProvider.h create mode 100644 src/libSystem/System.h create mode 100644 src/libSystem/Thread.h create mode 100644 src/libSystem/ThreadState.h create mode 100644 src/libSystem/TimeSpan.h create mode 100644 src/libSystem/libSystem.vcproj create mode 100644 src/libXFX.Game/DrawableGameComponent.cpp create mode 100644 src/libXFX.Game/Game.cpp create mode 100644 src/libXFX.Game/GameComponent.cpp create mode 100644 src/libXFX.Game/GameTime.cpp create mode 100644 src/libXFX.Game/GamerServicesComponent.cpp create mode 100644 src/libXFX.Game/GraphicsDeviceManager.cpp create mode 100644 src/libXFX.Game/libXFX.Game.vcproj create mode 100644 src/libXFX.Game/makefile create mode 100644 src/libXFX/BasicEffect.cpp create mode 100644 src/libXFX/BoundingBox.cpp create mode 100644 src/libXFX/BoundingFrustrum.cpp create mode 100644 src/libXFX/BoundingSphere.cpp create mode 100644 src/libXFX/Color.cpp create mode 100644 src/libXFX/ContentManager.cpp create mode 100644 src/libXFX/ContentReader.cpp create mode 100644 src/libXFX/DepthStencilBuffer.cpp create mode 100644 src/libXFX/DisplayMode.cpp create mode 100644 src/libXFX/GamePad.cpp create mode 100644 src/libXFX/GraphicsAdapter.cpp create mode 100644 src/libXFX/GraphicsDevice.cpp create mode 100644 src/libXFX/GraphicsDeviceCapabilities.cpp create mode 100644 src/libXFX/GraphicsResource.cpp create mode 100644 src/libXFX/Keyboard.cpp create mode 100644 src/libXFX/MathHelper.cpp create mode 100644 src/libXFX/Matrix.cpp create mode 100644 src/libXFX/Mouse.cpp create mode 100644 src/libXFX/PBKit/nv20_shader.h create mode 100644 src/libXFX/PBKit/nv_objects.h create mode 100644 src/libXFX/PBKit/outer.h create mode 100644 src/libXFX/PBKit/pbKit.cpp create mode 100644 src/libXFX/PBKit/pbKit.h create mode 100644 src/libXFX/PBKit/ps.h create mode 100644 src/libXFX/PBKit/vs.h create mode 100644 src/libXFX/Plane.cpp create mode 100644 src/libXFX/Point.cpp create mode 100644 src/libXFX/PresentationParameters.cpp create mode 100644 src/libXFX/Quaternion.cpp create mode 100644 src/libXFX/Ray.cpp create mode 100644 src/libXFX/Rectangle.cpp create mode 100644 src/libXFX/SpriteBatch.cpp create mode 100644 src/libXFX/StorageContainer.cpp create mode 100644 src/libXFX/StorageDevice.cpp create mode 100644 src/libXFX/StorageDeviceNotConnectedException.cpp create mode 100644 src/libXFX/Texture.cpp create mode 100644 src/libXFX/Texture2D.cpp create mode 100644 src/libXFX/TextureCreationParameters.cpp create mode 100644 src/libXFX/TextureInformation.cpp create mode 100644 src/libXFX/Vector2.cpp create mode 100644 src/libXFX/Vector3.cpp create mode 100644 src/libXFX/Vector4.cpp create mode 100644 src/libXFX/VertexElement.cpp create mode 100644 src/libXFX/VertexPositionNormalTexture.cpp create mode 100644 src/libXFX/VertexPositionTexture.cpp create mode 100644 src/libXFX/VideoPlayer.cpp create mode 100644 src/libXFX/Viewport.cpp create mode 100644 src/libXFX/libXFX.vcproj create mode 100644 src/libXFX/makefile create mode 100644 src/libXFX/usb/hub.cpp create mode 100644 src/libXFX/usb/hub.h create mode 100644 src/libXFX/usb/ohci.cpp create mode 100644 src/libXFX/usb/ohci.h create mode 100644 src/libXFX/usb/pad.cpp create mode 100644 src/libXFX/usb/pad.h create mode 100644 src/libXFX/usb/xinput.cpp create mode 100644 src/libXFX/usb/xinput.h create mode 100644 src/libmscorlib/Array.cpp create mode 100644 src/libmscorlib/BinaryReader.cpp create mode 100644 src/libmscorlib/BitConverter.cpp create mode 100644 src/libmscorlib/Buffer.cpp create mode 100644 src/libmscorlib/Calendar.cpp create mode 100644 src/libmscorlib/Comparer.cpp create mode 100644 src/libmscorlib/DateTime.cpp create mode 100644 src/libmscorlib/Decoder.cpp create mode 100644 src/libmscorlib/Dictionary.cpp create mode 100644 src/libmscorlib/Directory.cpp create mode 100644 src/libmscorlib/Encoder.cpp create mode 100644 src/libmscorlib/Encoding.cpp create mode 100644 src/libmscorlib/Environment.cpp create mode 100644 src/libmscorlib/Exception.cpp create mode 100644 src/libmscorlib/File.cpp create mode 100644 src/libmscorlib/FileStream.cpp create mode 100644 src/libmscorlib/HashHelpers.cpp create mode 100644 src/libmscorlib/HashHelpers.h create mode 100644 src/libmscorlib/IOException.cpp create mode 100644 src/libmscorlib/KeyNotFoundException.cpp create mode 100644 src/libmscorlib/KeyValuePair.cpp create mode 100644 src/libmscorlib/Math.cpp create mode 100644 src/libmscorlib/MemoryStream.cpp create mode 100644 src/libmscorlib/Object.cpp create mode 100644 src/libmscorlib/Path.cpp create mode 100644 src/libmscorlib/Stream.cpp create mode 100644 src/libmscorlib/StreamAsyncResult.cpp create mode 100644 src/libmscorlib/StreamReader.cpp create mode 100644 src/libmscorlib/StreamWriter.cpp create mode 100644 src/libmscorlib/String.cpp create mode 100644 src/libmscorlib/SystemException.cpp create mode 100644 src/libmscorlib/TextureCollection.cpp create mode 100644 src/libmscorlib/Thread.cpp create mode 100644 src/libmscorlib/TimeSpan.cpp create mode 100644 src/libmscorlib/Version.cpp create mode 100644 src/libmscorlib/libmscorlib.vcproj create mode 100644 src/libmscorlib/makefile create mode 100644 src/libmscorlib/misc.cpp diff --git a/XFX.sln b/XFX.sln new file mode 100644 index 0000000..1f98698 --- /dev/null +++ b/XFX.sln @@ -0,0 +1,51 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libXFX", "src\libXFX\libXFX.vcproj", "{379FFCFD-88FA-46D6-A686-CAE8F58652FC}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection + ProjectSection(ProjectDependencies) = postProject + {B7A9CAB6-B307-4A2E-A01F-970F9A8B044E} = {B7A9CAB6-B307-4A2E-A01F-970F9A8B044E} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libXFX.Game", "src\libXFX.Game\libXFX.Game.vcproj", "{467C54AE-676B-4D1A-AB8E-60B930F09FB1}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection + ProjectSection(ProjectDependencies) = postProject + {B7A9CAB6-B307-4A2E-A01F-970F9A8B044E} = {B7A9CAB6-B307-4A2E-A01F-970F9A8B044E} + {379FFCFD-88FA-46D6-A686-CAE8F58652FC} = {379FFCFD-88FA-46D6-A686-CAE8F58652FC} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libmscorlib", "src\libmscorlib\libmscorlib.vcproj", "{B7A9CAB6-B307-4A2E-A01F-970F9A8B044E}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {379FFCFD-88FA-46D6-A686-CAE8F58652FC}.Debug|Win32.ActiveCfg = Debug|Win32 + {379FFCFD-88FA-46D6-A686-CAE8F58652FC}.Debug|Win32.Build.0 = Debug|Win32 + {379FFCFD-88FA-46D6-A686-CAE8F58652FC}.Release|Win32.ActiveCfg = Release|Win32 + {379FFCFD-88FA-46D6-A686-CAE8F58652FC}.Release|Win32.Build.0 = Release|Win32 + {467C54AE-676B-4D1A-AB8E-60B930F09FB1}.Debug|Win32.ActiveCfg = Debug|Win32 + {467C54AE-676B-4D1A-AB8E-60B930F09FB1}.Debug|Win32.Build.0 = Debug|Win32 + {467C54AE-676B-4D1A-AB8E-60B930F09FB1}.Release|Win32.ActiveCfg = Release|Win32 + {467C54AE-676B-4D1A-AB8E-60B930F09FB1}.Release|Win32.Build.0 = Release|Win32 + {B7A9CAB6-B307-4A2E-A01F-970F9A8B044E}.Debug|Win32.ActiveCfg = Debug|Win32 + {B7A9CAB6-B307-4A2E-A01F-970F9A8B044E}.Debug|Win32.Build.0 = Debug|Win32 + {B7A9CAB6-B307-4A2E-A01F-970F9A8B044E}.Release|Win32.ActiveCfg = Release|Win32 + {B7A9CAB6-B307-4A2E-A01F-970F9A8B044E}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/include/Audio.h b/include/Audio.h new file mode 100644 index 0000000..bb1d351 --- /dev/null +++ b/include/Audio.h @@ -0,0 +1,27 @@ +#ifndef XFRAMEWORK_AUDIO_H +#define XFRAMEWORK_AUDIO_H + +#ifdef XBOX +// +//Data Types +// +#include "AudioCategory.h" +#include "AudioEmitter.h" +#include "AudioEngine.h" +#include "AudioListener.h" +#include "Cue.h" +#include "RendererDetail.h" +#include "SoundBank.h" +#include "SoundState.h" +#include "WaveBank.h" +// +//Enums +// +#include "AudioStopOptions.h" +// +//Interfaces +// + +#endif + +#endif //XFRAMEWORK_AUDIO_H diff --git a/include/Audio/AudioCategory.h b/include/Audio/AudioCategory.h new file mode 100644 index 0000000..7be8153 --- /dev/null +++ b/include/Audio/AudioCategory.h @@ -0,0 +1,19 @@ +#ifndef XFRAMEWORK_AUDIOCATEGORY_H +#define XFRAMEWORK_AUDIOCATEGORY_H + +namespace XFramework::Audio +{ + struct AudioCategory + { + char* Name; + + void Pause(); + int operator!=(AudioCategory &other); + int operator==(AudioCategory &other); + void Resume(); + void SetVolume(float volume); + void Stop(); + }; +} + +#endif //XFRAMEWORK_AUDIOCATEGORY_H diff --git a/include/Audio/AudioEmitter.h b/include/Audio/AudioEmitter.h new file mode 100644 index 0000000..19f4aba --- /dev/null +++ b/include/Audio/AudioEmitter.h @@ -0,0 +1,33 @@ +/******************************************************** + * AudioEmitter.h * + * * + * XFX AudioEmitter definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef AUDIOEMITTER_H +#define AUDIOEMITTER_H + +#include "System/System.h" + +namespace XFX +{ + namespace Audio + { + class Vector3; + + class Audioemitter + { + public: + float DopplerScale; + Vector3 Forward; + Vector3 Position; + Vector3 Up; + Vector3 Velocity; + + AudioEmitter(); + + } + } +} + +#endif //AUDIOEMITTER_H diff --git a/include/Audio/AudioEngine.h b/include/Audio/AudioEngine.h new file mode 100644 index 0000000..bc55ec0 --- /dev/null +++ b/include/Audio/AudioEngine.h @@ -0,0 +1,39 @@ +/******************************************************** + * AudioEngine.h * + * * + * XFramework AudioEngine definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef XFRAMEWORK_AUDIOENGINE_H +#define XFRAMEWORK_AUDIOENGINE_H + +#include "System/System.h" + +namespace XFramework +{ + namespace Audio + { + class AudioCategory; + + class AudioEngine + { + protected: + virtual void Dispose(int disposing); + + public: + const int ContentVersion; //XACT version supported + + AudioEngine(); //Initialize the audio engine for direct wav play. + AudioEngine(char* settingsFile); //Initialize the audio engine for XACT + AudioEngine(char* settingsFile, Timespan &lookAheadTime, char* rendererId); + + void Dispose(); + AudioCategory GetCategory(char* name); + float GetGlobalVariable(char* name); + void SetGlobalVariable(char* name, float value); + void Update(); + }; + } +} + +#endif //XFRAMEWORK_AUDIOENGINE_H diff --git a/include/Audio/AudioListener.h b/include/Audio/AudioListener.h new file mode 100644 index 0000000..83f13b2 --- /dev/null +++ b/include/Audio/AudioListener.h @@ -0,0 +1,32 @@ +/******************************************************** + * AudioListener.h * + * * + * XFramework AudioListener definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ + +#ifndef XFRAMEWORK_AUDIOLISTENER_H +#define XFRAMEWORK_AUDIOLISTENER_H + +#include "System/System.h" + +namespace XFramework +{ + class Vector3; + + namespace Audio + { + class AudioListener + { + public: + Vector3 Forward; + Vector3 Position; + Vector3 Up; + Vector3 Velocity; + + AudioListener(); + } + } +} + +#endif //XFRAMEWORK_AUDIOLISTENER_H diff --git a/include/Audio/AudioStopOptions.h b/include/Audio/AudioStopOptions.h new file mode 100644 index 0000000..e722b45 --- /dev/null +++ b/include/Audio/AudioStopOptions.h @@ -0,0 +1,22 @@ +/******************************************************** + * AudioStopOptions.h * + * * + * XFramework AudioStopOptions definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef XFRAMEWORK_AUDIOSTOPOPTIONS_H +#define XFRAMEWORK_AUDIOSTOPOPTIONS_H + +namespace XFramework +{ + namespace Audio + { + enum AudiostopOptions + { + AsAuthored, + Immediate + }; + } +} + +#endif //XFRAMEWORK_AUDIOSTOPOPTIONS_H diff --git a/include/Audio/Cue.h b/include/Audio/Cue.h new file mode 100644 index 0000000..a9d958e --- /dev/null +++ b/include/Audio/Cue.h @@ -0,0 +1,40 @@ +/******************************************************** + * Cue.h * + * * + * XFramework Cue definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef XFRAMEWORK_CUE_H +#define XFRAMEWORK_CUE_H + +namespace XFramework +{ + namespace Audio + { + class AudioEmitter; + class AudioListener; + + class Cue + { + private: + int isPaused; + int isPlaying; + int isStopped; + + public: + int IsPaused(); + int IsPlaying(); + int IsStopped(); + char* Name; + + void Apply3D(AudioListener &listener, AudioEmitter &emitter); + float GetVariable(char* name); + void Pause(); + void Play(); + void SetVariable(char* name, float value); + void Stop(); + }; + } +} + +#endif //XFRAMEWORK_CUE_H diff --git a/include/Audio/SoundState.h b/include/Audio/SoundState.h new file mode 100644 index 0000000..b52d795 --- /dev/null +++ b/include/Audio/SoundState.h @@ -0,0 +1,14 @@ +#ifndef XFRAMEWORK_SOUNDSTATE_H +#define XFRAMEWORK_SOUNDSTATE_H + +namespace XFramework::Audio +{ + enum SoundState + { + Paused, + Playing, + Stopped + }; +} + +#endif //XFRAMEWORK_SOUNDSTATE_H diff --git a/include/Audio/Soundbank.h b/include/Audio/Soundbank.h new file mode 100644 index 0000000..e3792f4 --- /dev/null +++ b/include/Audio/Soundbank.h @@ -0,0 +1,26 @@ +#ifndef XFRAMEWORK_SOUNDBANK_H +#define XFRAMEWORK_SOUNDBANK_H + +#include "AudioEmitter.h" +#include "AudioEngine.h" +#include "AudioListener.h" +#include "Cue.h" + +namespace XFramework::Audio +{ + class SoundBank + { + protected: + void Dispose(int disposing); + public: + int IsInUse; + + void Dispose(); + Cue GetCue(char* name); + void PlayCue(char* name); + void PlayCue(char *name, AudioListener listener, AudioEmitter emitter); + SoundBank(AudioEngine audioEngine, char* filename); + }; +} + +#endif //XFRAMEWORK_SOUNDBANK_H diff --git a/include/Audio/WaveBank.h b/include/Audio/WaveBank.h new file mode 100644 index 0000000..01351c8 --- /dev/null +++ b/include/Audio/WaveBank.h @@ -0,0 +1,30 @@ +#ifndef XFRAMEWORK_WAVEBANK_H +#define XFRAMEWORK_WAVEBANK_H + +#include "AudioEngine.h" +#include "../Net_Framework/System.h" + +namespace XFramework::Audio +{ + class WaveBank + { + private: + int isDisposed; + int isInUse; + int isPrepared; + + protected: + void Dispose(int disposing); + + public: + int IsDisposed(); + int IsInUse(); + int IsPrepared(); + + void Dispose(); + WaveBank(AudioEngine audioEngine, char* nonStreamingWaveBankFilename); + WaveBank(AudioEngine audioEngine, char* streamingWaveBankFilename, int offset, short packetsize); + } +} + +#endif //XFRAMEWORK_WAVEBANK_H diff --git a/include/Audio/XACT.h b/include/Audio/XACT.h new file mode 100644 index 0000000..72a53ee --- /dev/null +++ b/include/Audio/XACT.h @@ -0,0 +1,28 @@ +/******************************************************** + * XACT.h * + * * + * XFramework XACT specification file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef XFRAMEWORK_XACT_H +#define XFRAMEWORK_XACT_H + +//The header in an XACT Settings (XGS) file +struct XGSHeader +{ + char magic[4]; //XGSF +} + +//The header in a Sound Bank (XSB) file +struct XSBHeader +{ + char magic[4]; //SDBK +} + +//The header in a Wave Bank (XWB) file +struct XWBHeader +{ + char magic[4]; +} + +#endif diff --git a/include/Audio/wave.h b/include/Audio/wave.h new file mode 100644 index 0000000..cbd8fe5 --- /dev/null +++ b/include/Audio/wave.h @@ -0,0 +1,31 @@ +#include +#include + +#pragma pack(1) +struct WAV_Head +{ + char ChunkID[4]; //"RIFF" + unsigned int ChunkSize; + char Format[4]; //"WAVE" + char Subchunk1ID[4]; //"fmt " + unsigned int Subchunk1Size; + short int AudioFormat; + short int NumChannels; + unsigned int SampleRate; + unsigned int ByteRate; + short int BlockAlign; + short int BitsPerSample; + char Subchunk2ID[4]; //"data" + unsigned int Subchunk2Size; +}; +#pragma pack() + +void Load_Wave(char* fileName, WAV_Head wavHead) +{ + // Read in our header information + FILE* fp = fopen("test.wav", "rb"); + + fread(&wavHead, 1, sizeof(wavHead), fp); + + fclose(fp); +} diff --git a/include/BoundingBox.h b/include/BoundingBox.h new file mode 100644 index 0000000..4f0bf96 --- /dev/null +++ b/include/BoundingBox.h @@ -0,0 +1,61 @@ +/******************************************************** + * BoundingBox.h * + * * + * XFX BoundingBox definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _BOUNDINGBOX_ +#define _BOUNDINGBOX_ + +#include +#include "Enums.h" +#include "Vector3.h" + +namespace XFX +{ + struct BoundingSphere; + struct Plane; + struct Ray; + + /// + /// Defines an axis-aligned box-shaped 3D volume. + /// + struct BoundingBox + { + public: + Vector3 Max; + Vector3 Min; + static const int CornerCount; + + BoundingBox(Vector3 min, Vector3 max); + BoundingBox(const BoundingBox &obj); + BoundingBox(); + + ContainmentType_t Contains(BoundingBox box); + void Contains(BoundingBox box, out ContainmentType_t result); + ContainmentType_t Contains(BoundingSphere sphere); + void Contains(BoundingSphere sphere, out ContainmentType_t result); + ContainmentType_t Contains(Vector3 vector); + void Contains(Vector3 vector, out ContainmentType_t result); + static BoundingBox CreateFromPoints(Vector3 points[]); + static BoundingBox CreateFromSphere(BoundingSphere sphere); + static void CreateFromSphere(BoundingSphere sphere, out BoundingBox result); + static BoundingBox CreateMerged(BoundingBox box1, BoundingBox box2); + static void CreateMerged(BoundingBox box1, BoundingBox box2, out BoundingBox result); + bool Equals(BoundingBox obj); + int Intersects(BoundingBox box); + void Intersects(BoundingBox box, out int result); + int Intersects(BoundingSphere sphere); + void Intersects(BoundingSphere sphere, out int result); + PlaneIntersectionType_t Intersects(Plane plane); + void Intersects(Plane plane, out PlaneIntersectionType_t result); + float Intersects(Ray ray); + void Intersects(Ray ray, out float distance); + + bool operator!=(const BoundingBox other); + bool operator==(const BoundingBox other); + BoundingBox operator=(const BoundingBox other); + }; +} + +#endif //_BOUNDINGBOX_ diff --git a/include/BoundingFrustrum.h b/include/BoundingFrustrum.h new file mode 100644 index 0000000..2ef739a --- /dev/null +++ b/include/BoundingFrustrum.h @@ -0,0 +1,85 @@ +/******************************************************** + * BoundingFrustrum.h * + * * + * XFX BoundingFrustrum definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_BOUNDINGFRUSTRUM_ +#define _XFX_BOUNDINGFRUSTRUM_ + +#include "Enums.h" +#include "Matrix.h" +#include "Plane.h" +#include + +namespace XFX +{ + struct BoundingBox; + struct BoundingSphere; + struct Ray; + struct Vector3; + + /// + /// Defines a frustum and helps determine whether forms intersect with it. + /// + class BoundingFrustrum + { + private: + static const int BottomPlaneIndex; + Vector3 cornerArray[8]; + static const int FarPlaneIndex; + static const int LeftPlaneIndex; + Matrix matrix; + static const int NearPlaneIndex; + static const int NumPlanes; + Plane planes[6]; + static const int RightPlaneIndex; + static const int TopPlaneIndex; + + static Vector3 ComputeIntersection(Plane plane, Ray ray); + static Ray ComputeIntersectionLine(Plane p1, Plane p2); + void SetMatrix(Matrix value); + void SupportMapping(Vector3 v, out Vector3 result); + + public: + Plane Bottom(); + static const int CornerCount; + Plane Far(); + Plane Left(); + Matrix Matrix_(); + void Matrix_(Matrix value); + Plane Near(); + Plane Right(); + Plane Top(); + + BoundingFrustrum(); + BoundingFrustrum(Matrix value); + BoundingFrustrum(const BoundingFrustrum &obj); // copy constructor + + ContainmentType_t Contains(BoundingBox box); + ContainmentType_t Contains(BoundingFrustrum frustrum); + ContainmentType_t Contains(BoundingSphere sphere); + ContainmentType_t Contains(Vector3 point); + void Contains(BoundingBox box, out ContainmentType_t result); + void Contains(BoundingSphere sphere, out ContainmentType_t result); + void Contains(Vector3 point, out ContainmentType_t result); + bool Equals(BoundingFrustrum other); + Vector3* GetCorners(); + void GetCorners(Vector3 corners[]); + int GetHashCode(); + bool Intersects(BoundingBox box); + bool Intersects(BoundingFrustrum frustrum); + bool Intersects(BoundingSphere sphere); + PlaneIntersectionType_t Intersects(Plane plane); + float Intersects(Ray ray); + void Intersects(BoundingBox box, out bool result); + void Intersects(BoundingSphere sphere, out bool result); + void Intersects(Plane plane, out PlaneIntersectionType_t result); + void Intersects(Ray ray, out float result); + + bool operator==(BoundingFrustrum other); + bool operator!=(BoundingFrustrum other); + }; +} + +#endif //_XFX_BOUNDINGFRUSTRUM_ diff --git a/include/BoundingSphere.h b/include/BoundingSphere.h new file mode 100644 index 0000000..f8d355a --- /dev/null +++ b/include/BoundingSphere.h @@ -0,0 +1,34 @@ +/******************************************************** + * BoundingSphere.h * + * * + * XFX BoundingSphere definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_BOUNDINGSPHERE_ +#define _XFX_BOUNDINGSPHERE_ + +#include +#include "Vector3.h" + +namespace XFX +{ + /// + /// Defines a sphere. + /// + class BoundingSphere + { + public: + Vector3 Center; + float Radius; + + BoundingSphere(Vector3 center, float radius); + BoundingSphere(const BoundingSphere &obj); + BoundingSphere(); + + int operator==(const BoundingSphere other); + int operator!=(const BoundingSphere other); + BoundingSphere operator=(const BoundingSphere other); + }; +} + +#endif //_XFX_BOUNDINGSPHERE_ diff --git a/include/Content/ContentLoadException.h b/include/Content/ContentLoadException.h new file mode 100644 index 0000000..6d4b557 --- /dev/null +++ b/include/Content/ContentLoadException.h @@ -0,0 +1,23 @@ +#ifndef _CONTENT_CONTENTLOADEXCEPTION_ +#define _CONTENT_CONTENTLOADEXCEPTION_ + +#include +#include + +using namespace System; + +namespace XFX +{ + namespace Content + { + class ContentLoadException : public Exception + { + public: + ContentLoadException(); + ContentLoadException(char* message); + ContentLoadException(char* message, Exception innerException); + }; + } +} + +#endif //_CONTENT_CONTENTLOADEXCEPTION_ diff --git a/include/Content/ContentManager.h b/include/Content/ContentManager.h new file mode 100644 index 0000000..9f69cf1 --- /dev/null +++ b/include/Content/ContentManager.h @@ -0,0 +1,58 @@ +/******************************************************** + * ContentManager.h * + * * + * XFX ContentManager definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_CONTENT_CONTENTMANAGER_ +#define _XFX_CONTENT_CONTENTMANAGER_ + +#include +#include +#include +#include +#include +#include + +using namespace System; +using namespace System::Collections::Generic; +using namespace System::IO; + +namespace XFX +{ + namespace Content + { + /// + /// The ContentManager is the run-time component which loads managed + /// objects from the binary files produced by the design time content pipeline. + /// It also manages the lifespan of the loaded objects, disposing the content + /// manager will also dispose any assets which are themselves System.IDisposable. + /// + class ContentManager : public IDisposable + { + private: + List disposableAssets; + bool disposed; + + protected: + virtual void Dispose(bool disposing); + virtual Stream OpenStream(char* assetName); + template + T ReadAsset(char* assetName); //! usage: T ReadAsset(assetName); where T is the preferred type, i.e. Texture2D + + public: + char* RootDirectory; + + ContentManager(); + ContentManager(char* rootDirectory); + virtual ~ContentManager(); + + void Dispose(); + template + T Load(char* assetName); //! usage: T Load(assetName); where T is the preferred type, i.e. Texture2D + virtual void Unload(); + }; + } +} + +#endif //_XFX_CONTENT_CONTENTMANAGER_ diff --git a/include/Content/ContentReader.h b/include/Content/ContentReader.h new file mode 100644 index 0000000..dfd0f41 --- /dev/null +++ b/include/Content/ContentReader.h @@ -0,0 +1,74 @@ +/******************************************************** + * ContentReader.h * + * * + * XFX ContentReader class definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _CONTENT_CONTENTREADER_ +#define _CONTENT_CONTENTREADER_ + +#include +#include +#include + +using namespace System::IO; +using namespace XFX::Graphics; + +namespace XFX +{ + struct Matrix; + struct Quaternion; + struct Vector2; + struct Vector3; + struct Vector4; + + namespace Content + { + class ContentTypeReader; + + /// + /// A worker object that implements most of ContentManager.Load. A new + /// ContentReader is constructed for each asset loaded. + /// + class ContentReader : public BinaryReader + { + private: + ContentManager contentManager; + GraphicsDevice _graphicsDevice; + char* _assetName; + static const short XnbVersion; + + static Stream PrepareStream(Stream stream, char* assetName); + + public: + ContentReader(ContentManager manager, Stream stream, GraphicsDevice graphicsDevice); + ContentReader(ContentManager manager, Stream input, char* assetName); + + template + T ReadExternalReference(); + Matrix ReadMatrix(); + template + T ReadObject(); + template + T ReadObject(T existingInstance); + template + T ReadObject(ContentTypeReader typeReader); + template + T ReadObject(ContentTypeReader typeReader, T existingInstance); + Quaternion ReadQuaternion(); + template + T ReadRawObject(); + template + T ReadRawObject(ContentTypeReader typeReader); + template + T ReadRawObject(T existingInstance); + template + T ReadRawObject(ContentTypeReader typeReader, T existingInstance); + Vector2 ReadVector2(); + Vector3 ReadVector3(); + Vector4 ReadVector4(); + }; + } +} + +#endif //_CONTENTREADER_ diff --git a/include/Enums.h b/include/Enums.h new file mode 100644 index 0000000..412e36a --- /dev/null +++ b/include/Enums.h @@ -0,0 +1,110 @@ +/******************************************************** + * Enums.h * + * * + * XFX enumeration definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_ENUMS_ +#define _XFX_ENUMS_ + +namespace XFX +{ + /// + /// Describes how one bounding volume contains another. + /// + struct ContainmentType + { + enum type + { + Contains, + Disjoint, + Intersects + }; + }; + /// + /// Defines the continuity of CurveKeys on a Curve. + /// + struct CurveContinuity + { + enum type + { + Smooth, + Step + }; + }; + /// + /// Defines how the value of a Curve will be determined for positions before + /// the first point on the Curve or after the last point on the Curve. + /// + struct CurveLoopType + { + enum type + { + Constant, + Cycle, + CycleOffset, + Linear, + Oscillate + }; + }; + /// + /// Specifies different tangent types to be calculated for CurveKey points in a Curve. + /// + struct CurveTangent + { + enum type + { + Flat, + Linear, + Smooth + }; + }; + /// + /// Describes the intersection between a plane and a bounding volume. + /// + struct PlaneIntersectionType + { + enum type + { + Back, + Front, + Intersecting + }; + }; + /// + /// Specifies the index of a player. + /// + struct PlayerIndex + { + enum type + { + One, + Two, + Three, + Four + }; + }; + /// + /// Defines the target platform to be used when compiling content. + /// + struct TargetPlatform + { + enum type + { + Unknown, + Linux, + XBOX + }; + }; + + //Lots of typedefs, but there was no other way to make these enum hacks look good. + typedef ContainmentType::type ContainmentType_t; + typedef CurveContinuity::type CurveContinuity_t; + typedef CurveLoopType::type CurveLoopType_t; + typedef CurveTangent::type CurveTangent_t; + typedef PlaneIntersectionType::type PlaneIntersectionType_t; + typedef PlayerIndex::type PlayerIndex_t; + typedef TargetPlatform::type TargetPlatform_t; +} + +#endif //_ENUMS_ diff --git a/include/Game.h b/include/Game.h new file mode 100644 index 0000000..de1f6aa --- /dev/null +++ b/include/Game.h @@ -0,0 +1,168 @@ +/******************************************************** + * Game.h * + * * + * XFX Game class definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_GAME_ +#define _XFX_GAME_ + +#include +#include + +#include "Content/ContentManager.h" +#include "GameComponentCollection.h" +#include "GameServiceContainer.h" +#include "GameTime.h" +#include "Graphics/GraphicsDevice.h" +#include "Graphics/IGraphicsDeviceService.h" +#include "Interfaces.h" + +using namespace System; +using namespace XFX::Content; +using namespace XFX::Graphics; + +namespace XFX +{ + /// + /// Provides basic graphics device initialization, game logic, and rendering code. + /// + class Game : public IDisposable + { + private: + bool exiting; + bool inRun; + bool isActive; + + GameComponentCollection components; + List visibleDrawable; + List enabledUpdateable; + GameServiceContainer services; + bool disposed; + GameTime gameTime; + TimeSpan inactiveSleepTime; + IGraphicsDeviceManager* graphicsManager; + IGraphicsDeviceService graphicsService; + +#if !ENABLE_XBOX + private bool isMouseVisible; +#endif + static const Int64 DefaultTargetElapsedTicks; + + protected: + virtual bool BeginDraw(); + virtual void BeginRun(); + virtual void Dispose(bool disposing); + virtual void Draw(GameTime gameTime); + virtual void EndDraw(); + virtual void EndRun(); + void Finalize(); + virtual void LoadContent(); + virtual void Initialize(); +#if !ENABLE_XBOX + virtual void OnActivated(void* sender, EventArgs args); + virtual void OnDeactivated(void* sender, EventArgs args); +#endif + virtual void OnExiting(void* sender, EventArgs args); + virtual void UnloadContent(); + virtual void Update(GameTime gameTime); + + public: + GameComponentCollection Components(); + ContentManager Content; + GraphicsDevice GraphicsDevice_(); + GameServiceContainer Services(); + bool IsActive(); + + bool IsFixedTimeStep; + bool IsMouseVisible; + TimeSpan TargetElapsedTime; + +#if !ENABLE_XBOX + EventHandler Activated; + EventHandler Deactivated; +#endif + EventHandler Disposed; + EventHandler Exiting; + + void Dispose(); + void Exit(); + Game(); + void ResetElapsedTime(); + void Run(); + void SuppressDraw(); + void Tick(); + }; + + /// + /// Base class for all XNA Framework game components. + /// + class GameComponent : IGameComponent, IUpdateable, IDisposable + { + private: + Game _game; + bool _disposed; + bool _enabled; + int _updateOrder; + + protected: + virtual void Dispose(bool disposing); + virtual ~GameComponent(); + + virtual void OnEnabledChanged(void* sender, EventArgs args); + virtual void OnUpdateOrderChanged(void* sender, EventArgs args); + + public: + bool Enabled(); + void Enabled(bool value); + int UpdateOrder(); + void UpdateOrder(int value); + Game Game_(); + + EventHandler EnabledChanged; + EventHandler UpdateOrderChanged; + EventHandler Disposed; + + GameComponent(Game game); + GameComponent(); + + virtual void Dispose(); + virtual void Initialize(); + virtual void Update(GameTime gameTime); + }; + + /// + /// A game component that is notified when it needs to draw itself. + /// + class DrawableGameComponent : GameComponent, IDrawable + { + private: + int _drawOrder; + bool _visible; + IGraphicsDeviceService _graphicsService; + + protected: + void Dispose(bool disposing); + virtual void LoadContent(); + virtual void OnDrawOrderChanged(void* sender, EventArgs args); + virtual void OnVisibleChanged(void* sender, EventArgs args); + virtual void UnloadContent(); + + public: + int DrawOrder(); + void DrawOrder(int value); + GraphicsDevice GraphicsDevice_(); + bool Visible(); + void Visible(bool value); + + EventHandler DrawOrderChanged; + EventHandler VisibleChanged; + + DrawableGameComponent(Game game); + virtual void Draw(GameTime gameTime); + void Initialize(); + virtual void Update(GameTime gameTime); + }; +} + +#endif //_XFX_GAME_ diff --git a/include/GameComponentCollection.h b/include/GameComponentCollection.h new file mode 100644 index 0000000..83f0474 --- /dev/null +++ b/include/GameComponentCollection.h @@ -0,0 +1,31 @@ +/******************************************************** + * GameComponentCollection.h * + * * + * XFX GameComponentCollection definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_GAMECOMPONENTCOLLECTION_ +#define _XFX_GAMECOMPONENTCOLLECTION_ + +#include "Interfaces.h" + +namespace XFX +{ + + /// + /// A collection of game components. + /// + class GameComponentCollection + { + protected: + void ClearItems(); + void InsertItem(int index, IGameComponent* item); + void RemoveItem(int index); + void SetItem(int index, IGameComponent* item); + + public: + GameComponentCollection(); + }; +} + +#endif //_XFX_GAMECOMPONENTCOLLECTION_ diff --git a/include/GameComponentCollectionEventArgs.h b/include/GameComponentCollectionEventArgs.h new file mode 100644 index 0000000..1d2ddd0 --- /dev/null +++ b/include/GameComponentCollectionEventArgs.h @@ -0,0 +1,30 @@ +/******************************************************** + * GameComponentCollectionEventArgs.h * + * * + * XFX GameComponentCollectionEventArgs definition * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_GAMECOMPONENTCOLLECTIONEVENTARGS_ +#define _XFX_GAMECOMPONENTCOLLECTIONEVENTARGS_ + +#include "Interfaces.h" +#include + +namespace XFX +{ + /// + /// Arguments used with events from the GameComponentCollection. + /// + class GameComponentCollectionEventArgs : EventArgs + { + private: + IGameComponent _gameComponent; + + public: + IGameComponent GameComponent_(); + + GameComponentCollectionEventArgs(IGameComponent gameComponent); + }; +} + +#endif //_XFX_GAMECOMPONENTCOLLECTIONEVENTARGS_ diff --git a/include/GamePadCapabilities.h b/include/GamePadCapabilities.h new file mode 100644 index 0000000..600675b --- /dev/null +++ b/include/GamePadCapabilities.h @@ -0,0 +1,45 @@ +/******************************************************** + * GamePadCapabilities.h * + * * + * XFX GamePadCapabilities definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef GAMEPADCAPABILITIES_H +#define GAMEPADCAPABILITIES_H + +#include "GamePadType.h" + +namespace XFX +{ + namespace Input + { + struct GamePadCapabilities + { + GamePadType GamePadType; + int HasAButton; + int HasBButton; + int HasBackButton; + int HasDPadDownButton; + int HasDPadLeftButton; + int HasDPadRightButton; + int HasDPadUpButton; + int HasLeftStickButton; + int HasLeftTrigger; + int HasLeftVibrationMotor; + int HasLeftXThumbStick; + int HasLeftYThumbStick; + int HasRightStickButton; + int HasRightTrigger; + int HasRightVibrationMotor; + int HasRightXThumbStick; + int HasRightYThumbStick; + int HasStartButton; + int HasWhiteButton; + int HasXButton; + int HasYButton; + int IsConnected; + }; + } +} + +#endif //GAMEPADCAPABILITIES_H diff --git a/include/GamePadDPad.h b/include/GamePadDPad.h new file mode 100644 index 0000000..1ff7c5f --- /dev/null +++ b/include/GamePadDPad.h @@ -0,0 +1,37 @@ +/******************************************************** + * GamePadDPad.h * + * * + * XFX GamePadDPad definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef GAMEPADDPAD_H +#define GAMEPADDPAD_H + +#include "ButtonState.h" + +namespace XFX +{ + namespace Input + { + struct GamePadDPad + { + ButtonState Down; + ButtonState Left; + ButtonState Right; + ButtonState Up; + + int operator!=(const GamePadDPad &other) + { + return !((Down == other.Down) && (Left == other.Left) && + (Right == other.Right) && (Up == other.Up)); + } + int operator==(const GamePadDPad &other) + { + return ((Down == other.Down) && (Left == other.Left) && + (Right == other.Right) && (Up == other.Up)); + } + }; + } +} + +#endif //GAMEPADDPAD_H diff --git a/include/GamePadThumbSticks.h b/include/GamePadThumbSticks.h new file mode 100644 index 0000000..cbfd36e --- /dev/null +++ b/include/GamePadThumbSticks.h @@ -0,0 +1,34 @@ +/******************************************************** + * GamePadThumbSticks.h * + * * + * XFX GamePadThumbSticks definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef GAMEPADTHUMBSTICKS_H +#define GAMEPADTHUMBSTICKS_H + +#include "Vector2.h" + +namespace XFX +{ + namespace Input + { + struct GamePadThumbSticks + { + Vector2 Left; + Vector2 Right; + + int GamePadThumbSticks::operator!=(const GamePadThumbSticks &other) + { + return !((Left == other.Left) && (Right == other.Right)); + } + + int GamePadThumbSticks::operator==(const GamePadThumbSticks &other) + { + return ((Left == other.Left) && (Right == other.Right)); + } + }; + } +} + +#endif //GAMEPADTHUMBSTICKS_H diff --git a/include/GamePadTriggers.h b/include/GamePadTriggers.h new file mode 100644 index 0000000..2236130 --- /dev/null +++ b/include/GamePadTriggers.h @@ -0,0 +1,31 @@ +/******************************************************** + * GamePadTriggers.h * + * * + * XFX GamePadTriggers definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef GAMEPADTRIGGERS_H +#define GAMEPADTRIGGERS_H + +namespace XFX +{ + namespace Input + { + struct GamePadTriggers + { + float Left; + float Right; + + int operator!=(const GamePadTriggers &other) + { + return !((Left == other.Left) && (Right == other.Right)); + } + int operator==(const GamePadTriggers &other) + { + return ((Left == other.Left) && (Right == other.Right)); + } + }; + } +} + +#endif //GAMEPADTRIGGERS_H diff --git a/include/GameServiceContainer.h b/include/GameServiceContainer.h new file mode 100644 index 0000000..c61e37c --- /dev/null +++ b/include/GameServiceContainer.h @@ -0,0 +1,28 @@ +/******************************************************** + * GameServiceContainer.h * + * * + * XFX GameServiceContainer definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_GAMESERVICECONTAINER_ +#define _XFX_GAMESERVICECONTAINER_ + +namespace XFX +{ + /// + /// A collection of game services. + /// + class GameServiceContainer + { + public: + template + void AddService(T type, void* provider); + GameServiceContainer(); + template + void* GetService(T type); + template + void RemoveService(T type); + }; +} + +#endif //_XFX_GAMESERVICECONTAINER_H diff --git a/include/GameTime.h b/include/GameTime.h new file mode 100644 index 0000000..f853e01 --- /dev/null +++ b/include/GameTime.h @@ -0,0 +1,42 @@ +/******************************************************** + * GameTime.h * + * * + * XFX GameTime definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_GAMETIME_ +#define _XFX_GAMETIME_ + +#include + +using namespace System; + +namespace XFX +{ + /// + /// Snapshot of the game timing state expressed in values that can be used by variable-step (real time) or fixed- + /// step (game time) games. + /// + class GameTime + { + private: + TimeSpan _elapsedGameTime; + TimeSpan _elapsedRealTime; + bool _isRunningSlowly; + TimeSpan _totalGameTime; + TimeSpan _totalRealTime; + + public: + TimeSpan ElapsedGameTime(); + TimeSpan ElapsedRealTime(); + bool IsRunningSlowly(); + TimeSpan TotalGameTime(); + TimeSpan TotalRealTime(); + + GameTime(TimeSpan totalRealTime, TimeSpan elapsedRealTime, TimeSpan totalGameTime, TimeSpan elapsedGameTime); + GameTime(TimeSpan totalRealTime, TimeSpan elapsedRealTime, TimeSpan totalGameTime, TimeSpan elapsedGameTime, bool isRunningSlowly); + GameTime(); + }; +} + +#endif //_XFX_GAMETIME_ diff --git a/include/GamerServices/Enums.h b/include/GamerServices/Enums.h new file mode 100644 index 0000000..71d7258 --- /dev/null +++ b/include/GamerServices/Enums.h @@ -0,0 +1,104 @@ +#ifndef _GAMERSERVICES_ENUMS_H_ +#define _GAMERSERVICES_ENUMS_H_ + +namespace XFX +{ + namespace GamerServices + { + /// + /// Indicates how sensitive this gamer prefers controller input to be. + /// + struct ControllerSensitivity + { + enum type + { + High, + Low, + Medium + }; + }; + + /// + /// Indicates how difficult this gamer likes things to be. + /// + struct GameDifficulty + { + enum type + { + Easy, + Hard, + Normal + }; + }; + + /// + /// This style of social gaming preferred by this Xbox Live member. + /// + struct GamerZone + { + enum type + { + Family, + Pro, + Recreation, + Underground, + Unknown + }; + }; + + /// + /// Defines the different icons for a message box. + /// + struct MessageBoxIcon + { + enum type + { + Alert, + Error, + None, + Warning + }; + }; + + /// + /// Determines where notifications appear on the screen. + /// + struct NotificationPosition + { + enum type + { + BottomCenter, + BottomLeft, + BottomRight, + Center, + CenterLeft, + CenterRight, + TopCenter, + TopLeft, + TopRight + }; + }; + + /// + /// Indicates which camera angle this gamer prefers to use in racing games. + /// + struct RacingCameraAngle + { + enum type + { + Back, + Front, + Inside + }; + }; + + typedef ControllerSensitivity::type ControllerSensitivity_t; + typedef GameDifficulty::type GameDifficulty_t; + typedef GamerZone::type GamerZone_t; + typedef MessageBoxIcon::type MessageBoxIcon_t; + typedef NotificationPosition::type NotificationPosition_t; + typedef RacingCameraAngle::type RacingCameraAngle_t; + } +} + +#endif //_GAMERSERVICES_ENUMS_H_ diff --git a/include/GamerServices/GamerServices.h b/include/GamerServices/GamerServices.h new file mode 100644 index 0000000..e69de29 diff --git a/include/GamerServices/GamerServicesComponent.h b/include/GamerServices/GamerServicesComponent.h new file mode 100644 index 0000000..59a30b2 --- /dev/null +++ b/include/GamerServices/GamerServicesComponent.h @@ -0,0 +1,30 @@ +/******************************************************** + * GamerServicesComponent.h * + * * + * XFX GamerServicesComponent class definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_GAMERSERVICES_GAMERSERVICESCOMPONENT_ +#define _XFX_GAMERSERVICES_GAMERSERVICESCOMPONENT_ + +#include "../Game.h" + +namespace XFX +{ + namespace GamerServices + { + /// + /// Creates a new GamerServicesComponent. + /// + class GamerServicesComponent : GameComponent + { + public: + GamerServicesComponent(Game game); + + void Initialize(); + void Update(GameTime gameTime); + }; + } +} + +#endif //_XFX_GAMERSERVICES_GAMERSERVICESCOMPONENT_ diff --git a/include/GamerServices/Guide.h b/include/GamerServices/Guide.h new file mode 100644 index 0000000..13d0dea --- /dev/null +++ b/include/GamerServices/Guide.h @@ -0,0 +1,44 @@ +#ifndef _GUIDE_H_ +#define _GUIDE_H_ + +#include +/******************************************************** + * Guide.h * + * * + * XFX Guide definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#include + +using namespace System; +using namespace XFX::Storage; + +namespace XFX +{ + namespace GamerServices + { + /// + /// Provides access to the Guide user interface. + /// + class Guide + { + private: + static int _isVisible = false; + + public: + static int IsScreenSaverEnabled(); + static int IsVisible(); + static NotificationPosition notificationPosition; + + static IAsyncResult BeginShowKeyboardInput(PlayerIndex_t player, String &title, String &description, String &defaultText, AsyncCallback &callback, object state); + static IAsyncResult BeginShowStorageDeviceSelector(int sizeInBytes, int directoryCount, AsyncCallback callback, object state); + static IAsyncResult BeginShowStorageDeviceSelector(AsyncCallback &callback, object state); + static IAsyncResult BeginShowStorageDeviceSelector(PlayerIndex_t player, int sizeInBytes, int directoryCount, AsyncCallback callback, object state); + static IAsyncResult BeginShowStorageDeviceSelector(PlayerIndex_t player, AsyncCallback callback, object state); + static String EndShowKeyboardInput(IAsyncResult result); + static StorageDevice EndShowStorageDeviceSelector(IAsyncResult result) + }; + } +} + +#endif //_GUIDE_H_ diff --git a/include/Graphics.h b/include/Graphics.h new file mode 100644 index 0000000..10e3a29 --- /dev/null +++ b/include/Graphics.h @@ -0,0 +1,32 @@ +/******************************************************** + * Graphics.h * + * * + * XFX::Graphics namespace include file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _GRAPHICS_ +#define _GRAPHICS_ + +// +//Data Types +// +#include "Graphics/BasicDirectionalLight.h" +#include "Graphics/BasicEffect.h" +#include "Graphics/ClipPlane.h" +#include "Graphics/Color.h" +#include "Graphics/DisplayMode.h" +#include "Graphics/GraphicsDevice.h" +#include "Graphics/Texture.h" +#include "Graphics/Texture2D.h" +#include "Graphics/VertexElement.h" +#include "Graphics/VertexPositionTexture.h" +// +//Enums +// +#include "Graphics/Enums.h" +// +//Interfaces +// +#include "Graphics/IGraphicsDeviceservice.h" + +#endif //_GRAPHICS_ diff --git a/include/Graphics/BasicDirectionalLight.h b/include/Graphics/BasicDirectionalLight.h new file mode 100644 index 0000000..fbeac79 --- /dev/null +++ b/include/Graphics/BasicDirectionalLight.h @@ -0,0 +1,30 @@ +/******************************************************** + * BasicDirectionalLight.h * + * * + * BasicDirectionalLight definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _BASICDIRECTIONALLIGHT_H_ +#define _BASICDIRECTIONALLICHT_H_ + +#include + +namespace XFX +{ + namespace Graphics + { + /// + /// Provides methods for manipulating the directional lights used by the BasicEffect class. + /// + class BasicDirectionalLight + { + public: + Vector3 DiffuseColor; + Vector3 Direction; + int Enabled; + Vector3 SpecularColor; + }; + } +} + +#endif //_BASICDIRECTIONALLIGHT_H_ diff --git a/include/Graphics/BasicEffect.h b/include/Graphics/BasicEffect.h new file mode 100644 index 0000000..fe2c369 --- /dev/null +++ b/include/Graphics/BasicEffect.h @@ -0,0 +1,60 @@ +/******************************************************** + * BasicEffect.h * + * * + * BasicEffect definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _BASICEFFECT_H_ +#define _BASICEFFECT_H_ + +#include "BasicDirectionalLight.h" +#include "Effect.h" +//#include "GraphicsDevice.h" +#include +#include "Texture2D.h" +#include + +namespace XFX +{ + namespace Graphics + { + /// + /// Represents shader model 1.1 Effect that has optional support for vertex colors, texturing, and lighting. + /// + class BasicEffect : public Effect + { + protected: + BasicEffect(GraphicsDevice &device, BasicEffect &clone); + + public: + float Alpha; + Vector3 AmbientLightColor; + Vector3 DiffuseColor; + BasicDirectionalLight DirectionalLight0(); + BasicDirectionalLight DirectionalLight1(); + BasicDirectionalLight DirectionalLight2(); + Vector3 EmissiveColor; + Vector3 FogColor; + int FogEnabled; + float FogEnd; + float FogStart; + int LightingEnabled; + int PreferPerPixelLighting; + Matrix Projection; + Vector3 SpecularColor; + float SpecularPower; + Texture2D Texture; + int TextureEnabled; + int VertexColorEnabled; + Matrix View; + Matrix World; + + BasicEffect(GraphicsDevice &device, EffectPool &effectPool); + + Effect Clone(GraphicsDevice &device); + void EnableDefaultLighting(); + }; + } +} + +#endif //_BASICEFFECT_H_ diff --git a/include/Graphics/Color.h b/include/Graphics/Color.h new file mode 100644 index 0000000..282d278 --- /dev/null +++ b/include/Graphics/Color.h @@ -0,0 +1,198 @@ +/******************************************************** + * Color.h * + * * + * XFX Color definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_GRAPHICS_COLOR_ +#define _XFX_GRAPHICS_COLOR_ + +#include +#include "PackedVector/IPackedVector.h" + +using namespace System; +using namespace XFX::Graphics::PackedVector; + +namespace XFX +{ + struct Vector3; + struct Vector4; + + namespace Graphics + { + /// + /// Represents a color using Red, Green, Blue, and Alpha values. + /// + struct Color : public IEquatable + { + private: + uint _packedValue; + uint RGBAtoARGB(uint value); + Color(uint packedValue); + static uint InitializeFromVector4(Vector4 vector); + static uint InitializeFromVector3(Vector3 vector); + + public: + byte A(); + static const Color AliceBlue; + static const Color AntiqueWhite; + static const Color Aqua; + static const Color AquaMarine; + static const Color Azure; + byte B(); + static const Color Beige; + static const Color Bisque; + static const Color Black; + static const Color BlanchedAlmond; + static const Color Blue; + static const Color BlueViolet; + static const Color Brown; + static const Color BurlyWood; + static const Color CadetBlue; + static const Color Chartreuse; + static const Color Chocolate; + static const Color Coral; + static const Color CornflowerBlue; + static const Color Cornsilk; + static const Color Crimson; + static const Color Cyan; + static const Color DarkBlue; + static const Color DarkCyan; + static const Color DarkGoldenrod; + static const Color DarkGray; + static const Color DarkGreen; + static const Color DarkKhaki; + static const Color DarkMagenta; + static const Color DarkOliveGreen; + static const Color DarkOrange; + static const Color DarkOrchid; + static const Color DarkRed; + static const Color DarkSalmon; + static const Color DarkSeaGreen; + static const Color DarkSlateBlue; + static const Color DarkSlateGray; + static const Color DarkTurquoise; + static const Color DarkViolet; + static const Color DeepPink; + static const Color DeepSkyBlue; + static const Color DimGray; + static const Color DodgerBlue; + static const Color FireBrick; + static const Color FloralWhite; + static const Color ForestGreen; + static const Color Fuchsia; + byte G(); + static const Color Gainsboro; + static const Color GhostWhite; + static const Color Gold; + static const Color Goldenrod; + static const Color Gray; + static const Color Green; + static const Color GreenYellow; + static const Color Honeydew; + static const Color HotPink; + static const Color IndianRed; + static const Color Indigo; + static const Color Ivory; + static const Color Khaki; + static const Color Lavender; + static const Color LavenderBlush; + static const Color LawnGreen; + static const Color LemonChiffon; + static const Color LightBlue; + static const Color LightCoral; + static const Color LightCyan; + static const Color LightGoldenrodYellow; + static const Color LightGray; + static const Color LightGreen; + static const Color LightPink; + static const Color LightSalmon; + static const Color LightSeaGreen; + static const Color LightSkyBlue; + static const Color LightSlateGray; + static const Color LightSteelBlue; + static const Color LightYellow; + static const Color Lime; + static const Color LimeGreen; + static const Color Linen; + static const Color Magenta; + static const Color Maroon; + static const Color MediumAquamarine; + static const Color MediumBlue; + static const Color MediumOrchid; + static const Color MediumPurple; + static const Color MediumSeaGreen; + static const Color MediumSlateBlue; + static const Color MediumSpringGreen; + static const Color MediumTurquoise; + static const Color MediumVioletRed; + static const Color MidnightBlue; + static const Color MintCream; + static const Color MistyRose; + static const Color Moccasin; + static const Color NavajoWhite; + static const Color Navy; + static const Color OldLace; + static const Color Olive; + static const Color OliveDrab; + static const Color Orange; + static const Color OrangeRed; + static const Color Orchid; + static const Color PaleGoldenrod; + static const Color PaleGreen; + static const Color PaleTurquoise; + static const Color PaleVioletRed; + static const Color PapayaWhip; + static const Color PeachPuff; + static const Color Peru; + static const Color Pink; + static const Color Plum; + static const Color PowderBlue; + static const Color Purple; + byte R(); + static const Color Red; + static const Color RosyBrown; + static const Color RoyalBlue; + static const Color SaddleBrown; + static const Color Salmon; + static const Color SandyBrown; + static const Color SeaGreen; + static const Color SeaShell; + static const Color Sienna; + static const Color Silver; + static const Color SkyBlue; + static const Color SlateBlue; + static const Color SlateGray; + static const Color Snow; + static const Color SpringGreen; + static const Color SteelBlue; + static const Color Tan; + static const Color Teal; + static const Color Thistle; + static const Color Tomato; + static const Color Turquoise; + static const Color Violet; + static const Color Wheat; + static const Color White; + static const Color WhiteSmoke; + static const Color Yellow; + static const Color YellowGreen; + + Color(Vector3 vector); + Color(Vector4 vector); + Color(byte r, byte g, byte b); + Color(byte r, byte g, byte b, byte a); + + bool Equals(Color other); + int GetHashCode(); + uint PackedValue(); + Vector4 ToVector4(); + Vector3 ToVector3(); + + bool operator!=(const Color other); + bool operator==(const Color other); + }; + } +} + +#endif //_COLOR_ diff --git a/include/Graphics/DepthStencilBuffer.h b/include/Graphics/DepthStencilBuffer.h new file mode 100644 index 0000000..11d095a --- /dev/null +++ b/include/Graphics/DepthStencilBuffer.h @@ -0,0 +1,51 @@ +#ifndef _DEPTHSTENCILBUFFER_ +#define _DEPTHSTENCILBUFFER_ + +#include "../System.h" +#include "Enums.h" + +using namespace System; + +namespace XFX +{ + namespace Graphics + { + class GraphicsDevice; + + /// + /// Queries and prepares depth stencil buffers. + /// + class DepthStencilBuffer : IDisposable + { + private: + GraphicsDevice *_graphicsDevice; + int _width; + int _height; + DepthFormat_t _format; + int isDisposed; + int _multiSampleQuality; + MultiSampleType_t _multiSampleType; + + protected: + virtual void Dispose(int __p1); + + public: + DepthFormat_t Format(); + GraphicsDevice GraphicsDevice_(); + int IsDisposed(); + int MultiSampleQuality(); + MultiSampleType_t MultiSampleType_(); + int Height(); + int Width(); + + DepthStencilBuffer(GraphicsDevice &graphicsDevice, int width, int height, DepthFormat_t format); + DepthStencilBuffer(GraphicsDevice &graphicsDevice, int width, int height, DepthFormat_t format, MultiSampleType_t multiSampleType, int multiSampleQuality); + DepthStencilBuffer(); + virtual ~DepthStencilBuffer(); + + void Dispose(); + }; + } +} + +#endif //_DEPTHSTENCILBUFFER_ diff --git a/include/Graphics/DisplayMode.h b/include/Graphics/DisplayMode.h new file mode 100644 index 0000000..c88b357 --- /dev/null +++ b/include/Graphics/DisplayMode.h @@ -0,0 +1,41 @@ +/******************************************************** + * DisplayMode.h * + * * + * XFX DisplayMode structure definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _DISPLAYMODE_ +#define _DISPLAYMODE_ + +#include "Enums.h" + +namespace XFX +{ + struct Rectangle; + + namespace Graphics + { + /// + /// Describes the display mode. + /// + struct DisplayMode + { + public: + float AspectRatio(); + int Height; + SurfaceFormat_t Format; + int RefreshRate; + Rectangle TitleSafeArea(); + int Width; + + DisplayMode(); + bool Equals(const DisplayMode other); + int GetHashCode(); + + bool operator!=(const DisplayMode other); + bool operator==(const DisplayMode other); + }; + } +} + +#endif //_DISPLAYMODE_ diff --git a/include/Graphics/DisplayModeCollection.h b/include/Graphics/DisplayModeCollection.h new file mode 100644 index 0000000..afd169e --- /dev/null +++ b/include/Graphics/DisplayModeCollection.h @@ -0,0 +1,19 @@ +#ifndef _DISPLAYMODECOLLECTION_ +#define _DISPLAYMODECOLLECTION_ + +#include "../System.h" + +using namespace System; + +namespace XFX +{ + namespace Graphics + { + struct DisplayModeCollection + { + + }; + } +} + +#endif //_DISPLAYMODECOLLECTION_ diff --git a/include/Graphics/Effect.h b/include/Graphics/Effect.h new file mode 100644 index 0000000..10a68ae --- /dev/null +++ b/include/Graphics/Effect.h @@ -0,0 +1,67 @@ +#ifndef _EFFECT_H_ +#define _EFFECT_H_ + +#include +#include +#include "Enums.h" +#include "EffectFunctionCollection.h" +#include "EffectPool.h" +#include "EffectParameterCollection.h" +#include "EffectTechnique.h" +#include "EffectTechniqueCollection.h" +#include "GraphicsDevice.h" + +using namespace System; +using namespace System::IO; + +namespace XFX +{ + namespace Graphics + { + /// + /// Used to set and query effects and choose techniques. + /// + class Effect : public IDisposable + { + private: + int _isDisposed; + + protected: + ~Effect(); + Effect(GraphicsDevice &graphicsDevice, Effect &cloneSource); + + void Dispose(int disposing); + + public: + String Creator(); + EffectTechnique CurrentTechnique; + EffectPool EffectPool_(); + EffectFunctionCollection Functions(); + GraphicsDevice GraphicsDevice_(); + int IsDisposed(); + EffectParameterCollection Parameters(); + EffectTechniqueCollection Techniques(); + + Effect(GraphicsDevice &graphicsDevice, byte effectCode[], CompilerOptions_t options, EffectPool &pool); + Effect(GraphicsDevice &graphicsDevice, String &effectCodeFile, CompilerOptions_t options, EffectPool &pool); + Effect(GraphicsDevice &graphicsDevice, Stream &effectCodeFileStream, CompilerOptions_t options, EffectPool &pool); + Effect(GraphicsDevice &graphicsDevice, Stream &effectCodeFileStream, int numberBytes, CompilerOptions_t options, EffectPool &pool); + + void Begin(); + void Begin(SaveStateMode_t saveStateMode); + virtual Effect Clone(GraphicsDevice &device); + void CommitChanges(); + static CompiledEffect CompileEffectFromFile(String &effectFile, CompilerMacro preprocessorDefines[], CompilerIncludeHandler &includeHandler, CompilerOptions_t options, TargetPlatform_t &platform); + static CompiledEffect CompileEffectFromFile(Stream &effectFileStream, int numberBytes, CompilerMacro preprocessorDefines[], CompilerIncludeHandler &includeHandler, CompilerOptions_t options, TargetPlatform_t platform); + static CompiledEffect CompileEffectFromFile(Stream effectFileStream, CompilerMacro preprocessorDefines[], CompilerIncludeHandler &includeHandler, CompilerOptions_t options, TargetPlatform_t platform); + static CompiledEffect CompileEffectFromSource(String effectFileSource, CompilerMacro preprocessorDefines[], CompilerIncludeHandler &includeHandler, CompilerOptions_t options, TargetPlatform_t platform); + static String Disassemble(Effect &effect, int enableColorCode); + String Disassemble(bool enableColorCode); + void Dispose(); + void End(); + String ToString(); + }; + } +} + +#endif //_EFFECT_H_ diff --git a/include/Graphics/Enums.h b/include/Graphics/Enums.h new file mode 100644 index 0000000..2fa8a5d --- /dev/null +++ b/include/Graphics/Enums.h @@ -0,0 +1,773 @@ +/******************************************************** + * Enums.h * + * * + * XFX::Graphics enumeration definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _GRAPHICS_ENUMS_ +#define _GRAPHICS_ENUMS_ + +//We place the enums inside structs so we can access them like this: Name::Value +//making it virtually the same as in C#. +//It also helps preventing pollution of the namespaces with constants and possible naming conflicts. +//I don't get why enums violate the scope principle of C++ + +namespace XFX +{ + namespace Graphics + { + /// + /// Defines color blending factors. + /// + struct Blend + { + enum type + { + Zero = 1, + One = 2, + SourceColor = 3, + InversourceColor = 4, + SourceAlpha = 5, + InverseSourceAlpha = 6, + Destinationalpha = 7, + InverseDestinationAlpha = 8, + DestinationColor = 9, + InverseDestinationColor = 10, + SourceAlphaSaturation = 11, + BothSourceAlpha = 12, + BothInverseSourceAlpha = 13, + BlendFactor = 14, + InverseBlendFactor = 15 + }; + }; + /// + /// Defines how to combine a source color with the destination color already on the render target for color blending. + /// + struct BlendFunction + { + enum type + { + Add = 1, + Subtract = 2, + ReverseSubtract = 3, + Min = 4, + Max = 5 + }; + }; + /// + /// Specifies Special Usage of the buffer contents. + /// + struct BufferUsage + { + enum type + { + None = 0, + Points = 0x40, + WriteOnly = 8 + }; + }; + /// + /// Specifies the buffer to use when calling GraphicsDevice.Clear. + /// + struct ClearOptions + { + enum type + { + Depth = 2, + Stencil = 4, + Target = 1 + }; + }; + /// + /// Defines the color channels that can be chosen for a per-channel write to a render target color buffer. + /// + struct ColorWriteChannels + { + enum type + { + All = 15, + Alpha = 8, + Blue = 4, + Green = 2, + None = 0, + Red = 1 + }; + }; + /// + /// Defines comparison functions that can be chosen for alpha, stencil, or depth-buffer tests. + /// + struct CompareFunction + { + enum type + { + Never = 1, + Less = 2, + Equal = 3, + LessEqual = 4, + Greater = 5, + NotEqual = 6, + GreaterEqual = 7, + Always = 8 + }; + }; + /// + /// Identifies an include file as a local or system resource. + /// + struct CompilerIncludeHandlerType + { + enum type + { + Local, + System + }; + }; + /// + /// Defines optimization options that may be chosen for shader and effect code compilation. + /// + struct CompilerOptions + { + enum type + { + AvoidFlowControl, + Debug, + ForcePixelShaderSoftwareNoOptimizations, + ForceVertexShaderSoftwareNoOptimizations, + None, + NoPreShader, + NotCloneable, + PackMatrixColumnMajor, + PackMatrixRowMajor, + PartialPrecision, + PreferFlowControl, + SkipOptimization, + SkipValidation + }; + }; + /// + /// Defines the faces of a cube map in the TextureCube class type. + /// + struct CubeMapFace + { + enum type + { + NegativeX = 1, + NegativeY = 3, + NegativeZ = 5, + PositiveX = 0, + PositiveY = 2, + PositiveZ = 4 + }; + }; + /// + /// Defines winding orders that may be used to identify back faces for culling. + /// + struct CullMode + { + enum type + { + None = 1, + CullClockwiseFace = 2, + CullCounterClockwiseFace = 3 + }; + }; + /// + /// Defines the format of data in a depth buffer. + /// + struct DepthFormat + { + enum type + { + Depth15Stencil1 = 56, + Depth16 = 54, + Depth24 = 51, + Depth24Stencil8 = 48, + Depth24Stencil8Single = 49, + Depth24Stencil4 = 50, + Depth32 = 52, + Unknown = -1 + }; + }; + /// + /// Specifies the type of device driver. + /// + struct DeviceType + { + enum type + { + Hardware = 1, + NullReference = 4, + Reference = 2 + }; + }; + /// + /// Defines classes that can be used for effect parameters or shader constants. + /// + struct EffectParameterClass + { + enum type + { + MatrixColumns, + MatrixRows, + Object, + Scalar, + Struct, + Vector + }; + }; + /// + /// Describes options for filling the vertices and lines that define a primitive. + /// + struct FillMode + { + enum type + { + Point = 1, + Solid = 3, + WireFrame = 2 + }; + }; + /// + /// Defines modes describing how to filter an image or mipmap when it is minified or magnified to fit a set of vertices. + /// + struct FilterOptions + { + enum type + { + Box = 5, + Dither = 524288, + DitherDiffusion = 1048576, + Linear = 3, + Mirror = 458752, + MirrorU = 65536, + MirrorV = 131072, + MirrorW = 262144, + None = 1, + Point = 2, + Srgb = 6291456, + SrgbIn = 2097152, + SrgbOut = 4194304, + Triangle = 4 + }; + }; + /// + /// Defines constants that describe the fog mode. + /// + struct FogMode + { + enum type + { + Exponent = 1, + ExponentSquared = 2, + Linear = 3, + None = 0 + }; + }; + /// + /// Describes the status of the device. + /// + struct GraphicsDeviceStatus + { + enum type + { + Lost = 1, + Normal = 0, + NotReset = 2 + }; + }; + /// + /// Defines supported image file formats that may be used for textures. + /// + struct ImageFileFormat + { + enum type + { + Bmp = 0, + Dds = 4, + Dib = 6, + Hdr = 7, + Jpg = 1, + Pfm = 8, + Png = 3, + Ppm = 5, + Tga = 2 + }; + }; + /// + /// Defines the size of an element of an index buffer. + /// + struct IndexElementSize + { + enum type + { + SixteenBits, + ThirtyTwoBits + }; + }; + /// + /// Defines the levels of full-scene multisampling that the game machine can apply. + /// + struct MultiSampleType + { + enum type + { + SixteenSamples = 16, + FifteenSamples = 15, + FourteenSamples = 14, + ThirteenSamples = 13, + TwelveSamples = 12, + ElevenSamples = 11, + TenSamples = 10, + NineSamples = 9, + EightSamples = 8, + SevenSamples = 7, + SixSamples = 6, + FiveSamples = 5, + FourSamples = 4, + ThreeSamples = 3, + TwoSamples = 2, + NonMaskable = 1, + None = 0 + }; + }; + /// + /// Defines flags that describe the relationship between the adapter refresh rate and the rate at which GraphicsDevice.Present operations are completed. + /// + struct PresentInterval + { + enum type + { + Default = 0, + Four = 8, + Immediate = -2147483648, + One = 1, + Three = 4, + Two = 2 + }; + }; + /// + /// Defines flags that control the behavior of the back buffer and depth buffer. + /// + struct PresentOptions + { + enum type + { + DeviceClip = 4, + DiscardDepthStencil = 2, + None = 0, + Video = 16 + }; + }; + /// + /// Defines how data in a vertex stream is interpreted during a draw call. + /// + struct PrimitiveType + { + enum type + { + LineList = 2, + LineStrip = 3, + PointList = 1, + TriangleFan = 6, + TriangleList = 4, + TriangleStrip = 5 + }; + }; + /// + /// Defines options for querying device resource formats. + /// + struct QueryUsages + { + enum type + { + Filter = 131072, + None = 0, + PostPixelShaderRendering = 524288, + SrgbRead = 65536, + SrgbWrite = 262144, + VertexTexture = 1048576, + WrapAndMip = 2097152 + }; + }; + /// + /// Determines how render target data is used once a new render target is set. + /// + struct RenderTargetUsage + { + enum type + { + DiscardContents, + PlatformContents, + PreserveContents + }; + }; + /// + /// Defines resource types. + /// + struct ResourceType + { + enum type + { + DepthStencilBuffer = 1, + IndexBuffer = 7, + RenderTarget = 8, + Texture2D = 3, + Texture3D = 4, + Texture3DVolume = 2, + TextureCube = 5, + VertexBuffer = 6 + }; + }; + /// + /// Defines options for saving the graphics device state before and after an effect technique is applied. + /// + struct SaveStateMode + { + enum type + { + None, + SaveState + }; + }; + /// + /// Describes whether existing buffer data will be overwritten or discarded during a SetData operation. + /// + struct SetDataOptions + { + enum type + { + Discard = 8192, + None = 0, + NoOverwrite = 4096 + }; + }; + /// + /// Defines vertex and pixel shader versions. + /// + struct ShaderProfile + { + enum type + { + PS_1_1, + PS_1_2, + PS_1_3, + VS_1_1, + XPS_1_1, //Denotes XBOX specific shader configuration + XVS_1_1 //Denotes XBOX specific shader configuration + }; + }; + /// + /// Defines the data type of a shader register. + /// + struct ShaderRegisterSet + { + enum type + { + Boolean = 0, + Float = 2, + Int4 = 1, + Sampler = 3 + }; + }; + /// + /// The following flags are used to specify sprite blending rendering options to the flags parameter in SpriteBatch.Begin: + /// + struct SpriteBlendMode + { + enum type + { + Additive = 2, + AlphaBlend = 1, + None = 0 + }; + }; + /// + /// Defines sprite rotation options. + /// + struct SpriteEffects + { + enum type + { + FlipHorizontally = 1, + FlipVertically = 256, + None = 0 + }; + }; + /// + /// Defines sprite sort-rendering options. + /// + struct SpriteSortMode + { + enum type + { + BackToFront = 3, + Deferred = 1, + FrontToBack = 4, + Immediate = 0, + Texture = 2 + }; + }; + /// + /// Defines stencil buffer operations. + /// + struct StencilOperation + { + enum type + { + Decrement = 8, + DecrementSaturation = 5, + Increment = 7, + IncrementSaturation = 4, + Invert = 6, + Keep = 1, + Replace = 3, + Zero = 2 + }; + }; + /// + /// Defines various types of surface formats. + /// + struct SurfaceFormat + { + enum type + { + Alpha8 = 15, + Bgr233 = 16, + Bgr24 = 17, + Bgr32 = 2, + Bgr444 = 13, + Bgr555 = 11, + Bgr565 = 9, + Bgra1010102 = 3, + Bgra2338 = 14, + Bgra4444 = 12, + Bgra5551 = 10, + Color = 1, + Depth15Stencil1 = 56, + Depth16 = 54, + Depth24 = 51, + Depth24Stencil4 = 50, + Depth24Stencil8 = 48, + Depth24Stencil8Single = 49, + Depth32 = 52, + Dxt1 = 28, + Dxt2 = 29, + Dxt3 = 30, + Dxt4 = 31, + Dxt5 = 32, + HalfSingle = 25, + HalfVector2 = 26, + HalfVector4 = 27, + Luminance16 = 34, + Luminance8 = 33, + LuminanceAlpha16 = 36, + LuminanceAlpha8 = 35, + Multi2Bgra32 = 47, + NormalizedAlpha1010102 = 41, + NormalizedByte2 = 18, + NormalizedByte2Computed = 42, + NormalizedByte4 = 19, + NormalizedLuminance16 = 39, + NormalizedLuminance32 = 40, + NormalizedShort2 = 20, + Normalizedshort4 = 21, + Palette8 = 37, + PaletteAlpha16 = 38, + Rg32 = 7, + Rgb32 = 5, + Rgba1010102 = 6, + Rgba32 = 4, + Rgba64 = 8, + Single = 22, + Unknown = -1, + Vector2 = 23, + Vector4 = 24, + VideoGrGb = 45, + VideoRgBg = 46, + VideoUyVy = 44, + VideoYuYv = 43 + }; + }; + /// + /// Defines how the device front buffer and back buffer are to be swapped when GraphicsDevice.Present is called. + /// + struct SwapEffect + { + enum type + { + Copy = 3, + Default = 1, + Discard = 1, + Flip = 2 + }; + }; + /// + /// Defines constants that describe supported texture-addressing modes. + /// + struct TextureAddressMode + { + enum type + { + Border = 4, + Clamp = 3, + Mirror = 2, + MirrorOnce = 5, + Wrap = 1 + }; + }; + /// + /// Defines how a texture will be filtered as it is minified for each mipmap level. + /// + struct TextureFilter + { + enum type + { + Anisotropic = 3, + GaussianQuad = 7, + Linear = 2, + None = 0, + Point = 1, + PyramidalQuad = 6 + }; + }; + /// + /// Specifies special usage of the texture data. + /// + struct TextureUsage + { + enum type + { + AutoGenerateMipMap, + Linear, + None, + Tiled + }; + }; + /// + /// Defines supported wrap coordinates. + /// + struct TextureWrapCoordinates + { + enum type + { + None = 0, + One = 2, + Three = 8, + Two = 4, + Zero = 1 + }; + }; + + /// + /// Defines vertex element formats. + /// + struct VertexElementFormat + { + enum type + { + Byte4, + Color, + HalfVector2, + HalfVector4, + Normalized101010, + NormalizedShort2, + NormalizedShort4, + Rg32, + Rgba32, + Rgba64, + Short2, + Short4, + Single, + UInt101010, + Unused, + Vector2, + Vector3, + Vector4 + }; + }; + + /// + /// Defines the tessellator processing method for a vertex element. + /// + struct VertexElementMethod + { + enum type + { + Default, + LookUp, + LookUpPresampled, + UV + }; + }; + + /// + /// Defines usage for vertex elements. + /// + struct VertexElementUsage + { + enum type + { + Binormal, + BlendIndices, + BlendWeight, + Color, + Depth, + Fog, + Normal, + PointSize, + Position, + Sample, + Tangent, + TessellateFactor, + TextureCoordinate + }; + }; + + + //Lots of typedefs, but there was no other way to make these typesafe enum hacks look good. + typedef Blend::type Blend_t; + typedef BlendFunction::type BlendFunction_t; + typedef BufferUsage::type BufferUsage_t; + typedef ClearOptions::type ClearOptions_t; + typedef ColorWriteChannels::type ColorWriteChannels_t; + typedef CompareFunction::type CompareFunction_t; + typedef CompilerIncludeHandlerType::type CompilerIncludeHandlerType_t; + typedef CompilerOptions::type CompilerOptions_t; + typedef CubeMapFace::type CubeMapFace_t; + typedef CullMode::type CullMode_t; + typedef DepthFormat::type DepthFormat_t; + typedef DeviceType::type DeviceType_t; + typedef EffectParameterClass::type EffectParameterClass_t; + typedef FillMode::type FillMode_t; + typedef FilterOptions::type FilterOptions_t; + typedef FogMode::type FogMode_t; + typedef GraphicsDeviceStatus::type GraphicsDeviceStatus_t; + typedef ImageFileFormat::type ImageFileFormat_t; + typedef IndexElementSize::type IndexElementSize_t; + typedef MultiSampleType::type MultiSampleType_t; + typedef PresentInterval::type PresentInterval_t; + typedef PresentOptions::type PresentOptions_t; + typedef PrimitiveType::type PrimitiveType_t; + typedef QueryUsages::type QueryUsages_t; + typedef RenderTargetUsage::type RenderTargetUsage_t; + typedef ResourceType::type ResourceType_t; + typedef SaveStateMode::type SaveStateMode_t; + typedef SetDataOptions::type SetDataOptions_t; + typedef ShaderProfile::type ShaderProfile_t; + typedef ShaderRegisterSet::type ShaderRegisterSet_t; + typedef SpriteBlendMode::type SpriteBlendMode_t; + typedef SpriteEffects::type SpriteEffects_t; + typedef SpriteSortMode::type SpriteSortMode_t; + typedef StencilOperation::type StencilOperation_t; + typedef SurfaceFormat::type SurfaceFormat_t; + typedef SwapEffect::type SwapEffect_t; + typedef TextureAddressMode::type TextureAddressMode_t; + typedef TextureFilter::type TextureFilter_t; + typedef TextureUsage::type TextureUsage_t; + typedef TextureWrapCoordinates::type TextureWrapCoordinates_t; + typedef VertexElementFormat::type VertexElementFormat_t; + typedef VertexElementMethod::type VertexElementMethod_t; + typedef VertexElementUsage::type VertexElementUsage_t; + } +} + +#endif //_GRAPHICS_ENUMS_ diff --git a/include/Graphics/GraphicsAdapter.h b/include/Graphics/GraphicsAdapter.h new file mode 100644 index 0000000..f5afa12 --- /dev/null +++ b/include/Graphics/GraphicsAdapter.h @@ -0,0 +1,64 @@ +/******************************************************** + * GraphicsAdapter.h * + * * + * XFX GraphicsAdapter definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _GRAPHICSADAPTER_ +#define _GRAPHICSADAPTER_ + +#include +#include + +#include "DisplayMode.h" +#include "DisplayModeCollection.h" +#include "Enums.h" + +using namespace System; + +namespace XFX +{ + namespace Graphics + { + /// + /// Provides methods to retrieve and manipulate graphics adapters. + /// + class GraphicsAdapter : public IDisposable + { + protected: + void Dispose(int __p1); + + public: + DisplayMode CurrentDisplayMode(); + + char* Description(); + int DeviceId(); + char* DeviceName(); + char* DriverDLL(); + float DriverVersion(); + bool IsDefaultAdapter(); + int VendorId(); + bool IsWideScreen(); + DisplayModeCollection SupportedDisplayModes(); + + virtual ~GraphicsAdapter(); + + bool CheckDepthStencilMatch(DeviceType_t deviceType, SurfaceFormat_t adapterFormat, SurfaceFormat_t renderTargetFormat, DepthFormat_t depthStencilFormat); + bool CheckDeviceFormat(DeviceType_t deviceType, SurfaceFormat_t adapterFormat, TextureUsage_t usage, QueryUsages_t queryUsages, ResourceType_t resourceType, SurfaceFormat_t checkFormat); + bool CheckDeviceFormat(DeviceType_t deviceType, SurfaceFormat_t adapterFormat, TextureUsage_t usage, QueryUsages_t queryUsages, ResourceType_t resourceType, DepthFormat_t checkFormat); + bool CheckDeviceFormatConversion(DeviceType_t deviceType, SurfaceFormat_t sourceFormat, SurfaceFormat_t targetFormat); + bool CheckDeviceMultiSampleType(DeviceType_t deviceType, SurfaceFormat_t surfaceFormat, int isFullScreen, MultiSampleType_t sampleType); + bool CheckDeviceMultiSampleType(DeviceType_t deviceType, SurfaceFormat_t surfaceFormat, int isFullScreen, MultiSampleType_t sampleType, out int qualityLevels); + bool CheckDeviceType(DeviceType_t deviceType, SurfaceFormat_t displayFormat, SurfaceFormat_t backBufferFormat, int isFullScreen); + void Dispose(); + bool Equals(GraphicsAdapter &other); + int GetHashCode(); + bool IsDeviceTypeAvailable(DeviceType_t deviceType); + + bool operator!=(GraphicsAdapter &other); + bool operator==(GraphicsAdapter &other); + }; + } +} + +#endif //_GRAPHICSADAPTER_ diff --git a/include/Graphics/GraphicsDevice.h b/include/Graphics/GraphicsDevice.h new file mode 100644 index 0000000..1cb882c --- /dev/null +++ b/include/Graphics/GraphicsDevice.h @@ -0,0 +1,95 @@ +/******************************************************** + * GraphicsDevice.h * + * * + * XFX GraphicsDevice definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_GRAPHICS_GRAPHICSDEVICE_ +#define _XFX_GRAPHICS_GRAPHICSDEVICE_ + +#include +#include "Color.h" +#include "DepthStencilBuffer.h" +#include "Enums.h" +#include "GraphicsAdapter.h" +#include "GraphicsDeviceCapabilities.h" +#include "PresentationParameters.h" +#include "TextureCollection.h" +#include "Viewport.h" + +namespace XFX +{ + struct Matrix; + struct Quaternion; + struct Rectangle; + struct Vector2; + struct Vector4; + + namespace Graphics + { + class GammaRamp; + + /// + /// Performs primitive-based rendering, creates resources, handles system-level + /// variables, adjusts gamma ramp levels, and creates shaders. + /// + class GraphicsDevice : public IDisposable + { + private: + GraphicsAdapter _adapter; + DepthStencilBuffer _depthStencilBuffer; + DeviceType_t _deviceType; + GraphicsDeviceCapabilities graphicsDeviceCapabilities; + bool isDisposed; + TextureCollection textures; + Color clearColor; + Viewport viewport; + + protected: + virtual void Dispose(bool disposing); + + public: + DepthStencilBuffer GetDepthStencilBuffer(); + void SetDepthStencilBuffer(DepthStencilBuffer buffer); + TextureCollection Textures(); + Viewport Viewport_(); + void Viewport_(Viewport newValue); + +#if ENABLE_XBOX + GraphicsDevice(GraphicsAdapter adapter, DeviceType_t deviceType, PresentationParameters presentationParameters); +#else + GraphicsDevice(GraphicsAdapter adapter, DeviceType_t deviceType, IntPtr renderWindowHandle, PresentationParameters presentationParameters); +#endif + GraphicsDevice(); + virtual ~GraphicsDevice(); + + void Clear(Color color); + void Clear(ClearOptions_t options, Color color, float depth, int stencil); + void Clear(ClearOptions_t options, Vector4 color, float depth, int stencil); + void Clear(ClearOptions_t options, Color color, float depth, int stencil, Rectangle regions[]); + void Clear(ClearOptions_t options, Vector4 color, float depth, int stencil, Rectangle regions[]); + void Dispose(); + void DrawIndexedPrimitives(PrimitiveType_t primitiveType, int baseVertex, int minVertexIndex, int numVertices, int startIndex, int primitiveCount); + void DrawPrimitives(PrimitiveType primitiveType, int startVertex, int primitiveCount); + template + void DrawUserIndexedPrimitives(PrimitiveType_t primitiveType, T vertexData[], int vertexOffset, int numVertices, int indexData[], int indexOffset, int primitiveCount); + template + void DrawUserIndexedPrimitives(PrimitiveType_t primitiveType, T vertexData[], int vertexOffset, int numVertices, short indexData[], int indexOffset, int primitiveCount); + template + void DrawUserPrimitives(PrimitiveType_t primitiveType, T vertexData[], int vertexOffset, int primitiveCount); + void EvictManagedResources(); + GammaRamp GetGammaRamp(); + int* GetPixelShaderBooleanConstant(int startRegister, int constantCount); + int* GetPixelShaderInt32Constant(int startRegister, int constantCount); + Matrix* GetPixelShaderMatrixArrayConstant(int startRegister, int constantCount); + Matrix GetPixelShaderMatrixConstant(int startRegister); + Quaternion* GetPixelShaderQuaternionArrayConstant(int startRegister, int constantCount); + Quaternion GetPixelShaderQuaternionConstant(int startRegister); + float* GetPixelShaderSingleConstant(int startRegister, int constantCount); + Vector2* GetPixelShaderVector2ArrayConstant(int startRegister, int constantCount); + Vector2 GetPixelShaderVector2Constant(int startRegister); + }; + } +} + +#endif //_XFX_GRAPHICS_GRAPHICSDEVICE_ diff --git a/include/Graphics/GraphicsDeviceCapabilities.h b/include/Graphics/GraphicsDeviceCapabilities.h new file mode 100644 index 0000000..50d764e --- /dev/null +++ b/include/Graphics/GraphicsDeviceCapabilities.h @@ -0,0 +1,182 @@ +/******************************************************** + * GraphicsDeviceCapabilities.h * + * * + * XFX GraphicsDeviceCapabilities definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _GRAPHICSDEVICECAPABILITIES_ +#define _GRAPHICSDEVICECAPABILITIES_ + +#include +#include "Enums.h" + +using namespace System; + +namespace XFX +{ + namespace Graphics + { + /// + /// Represents the capabilities of the hardware. + /// + class GraphicsDeviceCapabilities : IDisposable + { + protected: + void Dispose(bool disposing); + + public: + struct BlendCaps; + struct CompareCaps; + struct CursorCaps; + struct DeclarationTypeCaps; + struct DeviceCaps; + struct DriverCaps; + struct FilterCaps; + + int AdapterOrdinalInGroup(); + CompareCaps AlphaCompareCapabilities(); + FilterCaps CubeTextureFilterCapabilities(); + CursorCaps CursorCapabilities(); + DeclarationTypeCaps DeclarationTypeCapabilities(); + CompareCaps DepthBufferCompareCapabilities(); + BlendCaps DestinationBlendCapabilities(); + DeviceCaps DeviceCapabilities(); + DeviceType_t DeviceType_(); + DriverCaps DriverCapabilities(); + + void Dispose(); + + int operator!=(GraphicsDeviceCapabilities other); + int operator==(GraphicsDeviceCapabilities other); + + public: + /// + /// Represents the texture addressing capabilities for Texture structures. + /// + struct AddressCaps + { + bool SupportsBorder(); + bool SupportsClamp(); + bool SupportsIndependentUV(); + bool SupportsMirror(); + bool SupportsMirrorOnce(); + bool SupportsWrap(); + + bool Equals(AddressCaps obj); + int GetHashCode(); + char* ToString(); + + bool operator!=(AddressCaps other); + bool operator==(AddressCaps other); + }; + /// + /// Represents the supported blend capabilities. + /// + struct BlendCaps + { + int SupportsBlendFactor(); + int SupportsBothInverseSourceAlpha(); + int SupportsBothSourceAlpha(); + int SupportsDestinationAlpha(); + + bool Equals(BlendCaps obj); + int GetHashCode(); + char* ToString(); + + int operator!=(BlendCaps other); + int operator==(BlendCaps other); + }; + /// + /// Represents comparison capabilities. + /// + struct CompareCaps + { + bool SupportsAlways(); + bool SupportsEqual(); + bool SupportsGreater(); + bool SupportsGreaterEqual(); + bool SupportsLess(); + bool SupportsLessEqual(); + bool SupportsNever(); + bool SupportsNotEqual(); + + bool Equals(CompareCaps obj); + int GetHashCode(); + char* ToString(); + + bool operator!=(CompareCaps other); + bool operator==(CompareCaps other); + }; + /// + /// Represents hardware support for cursors. + /// + struct CursorCaps + { + bool SupportsColor(); + bool SupportsLowResolution(); + + bool Equals(CursorCaps obj); + int GetHashCode(); + char* ToString(); + + bool operator!=(CursorCaps other); + bool operator==(CursorCaps other); + }; + /// + /// Represents data types contained in a vertex declaration. + /// + struct DeclarationTypeCaps + { + bool SupportsByte4(); + bool SupportsHalfVector2(); + bool SupportsHalfVector4(); + bool SupportsNormalized101010(); + bool SupportsNormalizedShort2(); + bool SupportsNormalizedShort4(); + bool SupportsRg32(); + bool SupportsRgba32(); + bool SupportsRgba64(); + bool SupportsUInt101010(); + + bool Equals(DeclarationTypeCaps obj); + int GetHashCode(); + char* ToString(); + + bool operator!=(DeclarationTypeCaps other); + bool operator==(DeclarationTypeCaps other); + }; + /// + /// Represents device-specific capabilities. + /// + struct DeviceCaps + { + bool CanDrawSystemToNonLocal(); + bool CanRenderAfterFlip(); + bool IsDirect3D9Driver(); + bool SupportsDrawPrimitives2(); + bool SupportsDrawPrimitives2Ex(); + + bool Equals(DeviceCaps obj); + int GetHashCode(); + char* ToString(); + + bool operator!=(DeviceCaps other); + bool operator==(DeviceCaps other); + }; + /// + /// Represents texture filter capabilities. + /// + struct FilterCaps + { + bool Equals(FilterCaps obj); + int GetHashCode(); + char* ToString(); + + bool operator!=(FilterCaps other); + bool operator==(FilterCaps other); + }; + }; + } +} + +#endif //_GRAPHICSDEVICECAPABILITIES_ diff --git a/include/Graphics/GraphicsResource.h b/include/Graphics/GraphicsResource.h new file mode 100644 index 0000000..d025e6f --- /dev/null +++ b/include/Graphics/GraphicsResource.h @@ -0,0 +1,54 @@ +/******************************************************** + * GraphicsResource.h * + * * + * XFX GraphicsResource definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_GRAPHICS_GRAPHICSRESOURCE_ +#define _XFX_GRAPHICS_GRAPHICSRESOURCE_ + +#include +#include +#include "Enums.h" +#include "GraphicsDevice.h" + +using namespace System; + +namespace XFX +{ + namespace Graphics + { + /// + /// Queries and prepares resources. + /// + class GraphicsResource : public IDisposable + { + private: + bool isDisposed; + char* name; + ResourceType_t resourceType; + + protected: + GraphicsDevice graphicsDevice; + + virtual void Dispose(bool disposing)=0; + + public: + virtual GraphicsDevice GraphicsDevice_(); + bool IsDisposed(); + char* Name(); + void Name(char* value); + int Priority; + virtual ResourceType_t ResourceType_(); + + EventHandler Disposing; + + virtual ~GraphicsResource(); + GraphicsResource(); + + void Dispose(); + }; + } +} + +#endif //_GRAPHICSRESOURCE_ diff --git a/include/Graphics/IGraphicsDeviceService.h b/include/Graphics/IGraphicsDeviceService.h new file mode 100644 index 0000000..b11a048 --- /dev/null +++ b/include/Graphics/IGraphicsDeviceService.h @@ -0,0 +1,33 @@ +/******************************************************** + * IGraphicsDeviceService.h * + * * + * XFX IGraphicsDeviceService definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_GRAPHICS_IGRAPHICSDEVICESERVICE_ +#define _XFX_GRAPHICS_IGRAPHICSDEVICESERVICE_ + +#include +#include "GraphicsDevice.h" + +namespace XFX +{ + namespace Graphics + { + /// + /// Defines a mechanism for retrieving GraphicsDevice objects. + /// + interface IGraphicsDeviceService + { + public: + EventHandler DeviceCreated; + EventHandler DeviceDisposing; + EventHandler DeviceReset; + EventHandler DeviceResetting; + + GraphicsDevice GraphicsDevice_(); + }; + } +} + +#endif //_XFX_GRAPHICS_IGRAPHICSDEVICESERVICE_ diff --git a/include/Graphics/IPackedVector.h b/include/Graphics/IPackedVector.h new file mode 100644 index 0000000..d771d0b --- /dev/null +++ b/include/Graphics/IPackedVector.h @@ -0,0 +1,33 @@ +#ifndef _IPACKEDVECTOR_ +#define _IPACKEDVECTOR_ + +#include +#include "TPacked.h" +#include "Vector4.h" + +using namespace XFX; + +namespace XFX +{ + namespace Graphics + { + namespace PackedVector + { + interface IPackedVector + { + public: + void PackFromVector4(Vector4 &vector); + Vector4 ToVector4(); + }; + + template + interface IPackedVector : IPackedVector + { + public: + TPacked PackedValue; + }; + } + } +} + +#endif //_IPACKEDVECTOR_ diff --git a/include/Graphics/PackedVector/IPackedVector.h b/include/Graphics/PackedVector/IPackedVector.h new file mode 100644 index 0000000..3f7f52a --- /dev/null +++ b/include/Graphics/PackedVector/IPackedVector.h @@ -0,0 +1,44 @@ +/******************************************************** + * IPackedVector.h * + * * + * XFX IPackedVector definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _IPACKEDVECTOR_ +#define _IPACKEDVECTOR_ + +#include "../../System.h" + +namespace XFX +{ + class Vector4; + + namespace Graphics + { + namespace PackedVector + { + /// + /// + /// + interface IPackedVector_ + { + public: + virtual void PackFromVector4(Vector4 &vector) = 0; + virtual Vector4 ToVector4() = 0; + }; + + /// + /// + /// + template + interface IPackedVector : virtual public IPackedVector_ + { + public: + virtual TPacked PackedValue() = 0; + virtual void PackedValue(TPacked value) = 0; + }; + } + } +} + +#endif //_IPACKEDVECTOR_ diff --git a/include/Graphics/PresentationParameters.h b/include/Graphics/PresentationParameters.h new file mode 100644 index 0000000..14acdd4 --- /dev/null +++ b/include/Graphics/PresentationParameters.h @@ -0,0 +1,65 @@ +/******************************************************** + * PresentationParameters.h * + * * + * XFX PresentationParameters definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _PRESENTATIONPARAMETERS_ +#define _PRESENTATIONPARAMETERS_ + +#include "../System.h" +#include "Enums.h" + +using namespace System; + +namespace XFX +{ + namespace Graphics + { + /// + /// Contains presentation parameters. + /// + class PresentationParameters : IDisposable + { + private: + int disposed; + + protected: + virtual void Dispose(int disposing); + + public: + DepthFormat_t AutoDepthStencilFormat; + int BackBufferCount; + SurfaceFormat_t BackBufferFormat; + int BackBufferHeight; + int BackBufferWidth; + static const int DefaultPresentRate; + +#if !ENABLE_XBOX //Only valid on Linux + IntPtr DeviceWindowHandle; +#endif + + int EnableAutoDepthStencil; + int FullScreenRefreshRateInHz; + int IsFullScreen; + int MultiSampleQuality; + MultiSampleType_t MultiSampleType_; + PresentInterval_t PresentationInterval; + PresentOptions_t PresentOptions_; + SwapEffect_t SwapEffect_; + + virtual ~PresentationParameters(); + PresentationParameters(); + + void Clear(); + PresentationParameters Clone(); + void Dispose(); + int Equals(PresentationParameters &other); + + int operator!=(PresentationParameters &other); + int operator==(PresentationParameters &other); + }; + } +} + +#endif //_PRESENTATIONPARAMETERS_ diff --git a/include/Graphics/SpriteBatch.h b/include/Graphics/SpriteBatch.h new file mode 100644 index 0000000..97b1809 --- /dev/null +++ b/include/Graphics/SpriteBatch.h @@ -0,0 +1,65 @@ +/******************************************************** + * SpriteBatch.h * + * * + * XFX SpriteBatch definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SPRITEBATCH_ +#define _SPRITEBATCH_ + +#include "../System.h" +#include "Enums.h" + +using namespace System; + +namespace XFX +{ + class Matrix; + class Rectangle; + class Vector2; + + namespace Graphics + { + class Color; + class Sprite; + class SpriteFont; + class Texture2D; + + class SpriteBatch : IDisposable + { + private: + GraphicsDevice *device; + int disposed; + static SpriteBlendMode_t spriteBlendMode; + + void applyGraphicsDeviceSettings(); + void flush(); + void restoreRenderState(); + + protected: + virtual void Dispose(int disposing); + + public: + ~SpriteBatch(); + SpriteBatch(GraphicsDevice &graphicsDevice); + + void Begin(); + void Begin(SpriteBlendMode_t blendMode, SpriteSortMode_t sortMode, SaveStateMode_t stateMode); + void Begin(SpriteBlendMode_t blendMode, SpriteSortMode_t sortMode, SaveStateMode_t stateMode, Matrix &transformMatrix); + void Dispose(); + void Draw(Texture2D &texture, Rectangle &destinationRectangle, Color &color); + void Draw(Texture2D &texture, Rectangle &destinationRectangle, Rectangle &sourceRectangle, Color &color); + void Draw(Texture2D &texture, Vector2 &position, Color &color); + void Draw(Texture2D &texture, Vector2 &position, Rectangle &sourceRectangle, Color &color); + void Draw(Texture2D &texture, Vector2 &position, Rectangle &sourceRectangle, Color &color, float rotation, Vector2 origin, float scale, SpriteEffects_t effects, float layerDepth); + void Draw(Texture2D &texture, Vector2 &position, Rectangle &sourceRectangle, Color &color, float rotation, Vector2 &origin, Vector2 &scale, SpriteEffects_t effects, float layerDepth); + void Draw(Texture2D &texture, Rectangle &destinationRectangle, Rectangle &sourceRectangle, Color &color, float rotation, Vector2 &origin, SpriteEffects_t &effects, float layerDepth); + void DrawString(SpriteFont &spriteFont, char* text, Vector2 &position, Color &color); + void DrawString(SpriteFont &spriteFont, char* text, Vector2 &position, Color &color, float rotation, Vector2 &origin, float scale, SpriteEffects_t effects, float layerDepth); + + void End(); + }; + } +} + +#endif //_SPRITEBATCH_ diff --git a/include/Graphics/Texture.h b/include/Graphics/Texture.h new file mode 100644 index 0000000..a7513fb --- /dev/null +++ b/include/Graphics/Texture.h @@ -0,0 +1,58 @@ +/******************************************************** + * Texture.h * + * * + * XFX Texture definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_GRAPHICS_TEXTURE_ +#define _XFX_GRAPHICS_TEXTURE_ + +#include +#include +#include "GraphicsResource.h" + +using namespace System::IO; + +namespace XFX +{ + namespace Graphics + { + struct TextureCreationParameters; + struct TextureInformation; + + /// + /// Represents a texture resource. + /// + class Texture : GraphicsResource + { + private: + static ImageFileFormat_t ILimageformat2XNAimageformat(int ILFormat); + + protected: + void Dispose(bool disposing); + + public: + int LevelCount(); + int LevelOfDetail; + + static Texture FromFile(GraphicsDevice graphicsDevice, Stream textureStream); + static Texture FromFile(GraphicsDevice graphicsDevice, char* filename); + static Texture FromFile(GraphicsDevice graphicsDevice, Stream textureStream, int numberBytes); + static Texture FromFile(GraphicsDevice graphicsDevice, Stream textureStream, TextureCreationParameters creationParameters); + static Texture FromFile(GraphicsDevice graphicsDevice, char* filename, TextureCreationParameters creationParameters); + static Texture FromFile(GraphicsDevice graphicsDevice, Stream textureStream, int numberBytes, TextureCreationParameters creationParameters); + static Texture FromFile(GraphicsDevice graphicsDevice, char* filename, int width, int height, int depth); + + void GenerateMipMaps(TextureFilter_t filterType); + static TextureCreationParameters GetCreationParameters(GraphicsDevice graphicsDevice, Stream textureStream); + static TextureCreationParameters GetCreationParameters(GraphicsDevice graphicsDevice, char* filename); + static TextureCreationParameters GetCreationParameters(GraphicsDevice graphicsDevice, Stream textureStream, int numberBytes); + static TextureInformation GetTextureInformation(Stream textureStream); + static TextureInformation GetTextureInformation(char* filename); + static TextureInformation GetTextureInformation(Stream textureStream, int numberBytes); + void Save(char* filename, ImageFileFormat_t format); + }; + } +} + +#endif //_XFX_GRAPHICS_TEXTURE_ diff --git a/include/Graphics/Texture2D.h b/include/Graphics/Texture2D.h new file mode 100644 index 0000000..3d893e7 --- /dev/null +++ b/include/Graphics/Texture2D.h @@ -0,0 +1,74 @@ +/******************************************************** + * Texture2D.h * + * * + * XFX Texture2D definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _TEXTURE2D_ +#define _TEXTURE2D_ + +#include "Texture.h" +#include + +using namespace System; +using namespace System::IO; + +namespace XFX +{ + class Rectangle; + + namespace Graphics + { + class Texture2D : Texture + { + private: + GraphicsDevice device; + int _height; // The height of the texture before resizing it + bool _isDisposed; // True when the texture has been disposed + int _numberOfLevels; // The number of mip levels for the texture + TextureUsage_t _textureUsage; + SurfaceFormat_t _surfaceFormat; // The colour format of the texture + int _width; // the width of the texture before resizing it + int textureId; // The reference ID of the texture in OpenGL memory + int imageId; + + Texture2D(GraphicsDevice graphicsDevice); + void Load(byte buffer[]); + + protected: + void Dispose(bool disposing); + + public: + SurfaceFormat_t Format(); + int Height(); + TextureUsage_t TextureUsage_(); + int Width(); + + Texture2D(GraphicsDevice graphicsDevice, int width, int height); + Texture2D(GraphicsDevice graphicsDevice, int width, int height, int numberLevels, TextureUsage_t usage, SurfaceFormat_t format); + + static Texture2D FromFile(GraphicsDevice graphicsDevice, Stream textureStream); + static Texture2D FromFile(GraphicsDevice graphicsDevice, Stream textureStream, TextureCreationParameters creationParameters); + static Texture2D FromFile(GraphicsDevice graphicsDevice, Stream textureStream, int numberBytes); + static Texture2D FromFile(GraphicsDevice graphicsDevice, Stream textureStream, int numberBytes, TextureCreationParameters creationParameters); + static Texture2D FromFile(GraphicsDevice graphicsDevice, char* filename); + static Texture2D FromFile(GraphicsDevice graphicsDevice, char* filename, TextureCreationParameters creationParameters); + static Texture2D FromFile(GraphicsDevice graphicsDevice, char* filename, int width, int height); + + template + void GetData(T data[]); + template + void GetData(T data[], int startIndex, int elementCount); + template + void GetData(int level, Rectangle rect, T data[], int startIndex, int elementCount); + template + void SetData(T data[]); + template + void SetData(T data[], int startIndex, int elementCount, SetDataOptions_t options); + template + void SetData(int level, Rectangle rect, T data[], int startIndex, int elementCount, SetDataOptions_t options); + }; + } +} + +#endif //_TEXTURE2D_ diff --git a/include/Graphics/TextureCollection.h b/include/Graphics/TextureCollection.h new file mode 100644 index 0000000..1cbf6b1 --- /dev/null +++ b/include/Graphics/TextureCollection.h @@ -0,0 +1,39 @@ +/******************************************************** + * TextureCollection.h * + * * + * XFX TextureCollection definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_GRAPHICS_TEXTURECOLLECTION_ +#define _XFX_GRAPHICS_TEXTURECOLLECTION_ + +#include +#include "Texture.h" + +using namespace System::Collections::Generic; + +namespace XFX +{ + namespace Graphics + { + /// + /// + /// + class TextureCollection + { + private: + bool disposed; + List textures; + void Dispose(); + void Dispose(bool disposing); + + public: + TextureCollection(); + ~TextureCollection(); + + Texture operator[](int index); + }; + } +} + +#endif //_XFX_GRAPHICS_TEXTURECOLLECTION_ diff --git a/include/Graphics/TextureCreationParameters.h b/include/Graphics/TextureCreationParameters.h new file mode 100644 index 0000000..156aeff --- /dev/null +++ b/include/Graphics/TextureCreationParameters.h @@ -0,0 +1,48 @@ +/******************************************************** + * TextureCreationParameters.h * + * * + * XFX TextureCreationParameters definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _TEXTURECREATIONPARAMETERS_ +#define _TEXTURECREATIONPARAMETERS_ + +#include "Color.h" +#include "Enums.h" + +namespace XFX +{ + namespace Graphics + { + /// + /// Describes the parameters to use when initializing a new instance of a texture. + /// + struct TextureCreationParameters + { + int Width; + int Height; + int Depth; + int MipLevels; + SurfaceFormat_t Format; + Color ColorKey; + FilterOptions_t Filter; + FilterOptions_t MipFilter; + static TextureCreationParameters Default; + + TextureCreationParameters(int width, int height, int depth, int mipLevels, SurfaceFormat_t format, + TextureUsage_t textureUsage, Color colorKey, FilterOptions_t filter, FilterOptions_t mipFilter); + TextureCreationParameters(const TextureCreationParameters &obj); + TextureCreationParameters(); + + bool Equals(TextureCreationParameters other); + int GetHashCode(); + char* ToString(); + + bool operator!=(TextureCreationParameters other); + bool operator==(TextureCreationParameters other); + bool operator =(TextureCreationParameters other); + }; + } +} + +#endif //_TEXTURECREATIONPARAMETERS_ diff --git a/include/Graphics/TextureInformation.h b/include/Graphics/TextureInformation.h new file mode 100644 index 0000000..ec438ca --- /dev/null +++ b/include/Graphics/TextureInformation.h @@ -0,0 +1,44 @@ +/******************************************************** + * TextureInformation.h * + * * + * XFX TextureInformation definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _TEXTUREINFORMATION_ +#define _TEXTUREINFORMATION_ + +#include "Enums.h" + +namespace XFX +{ + namespace Graphics + { + /// + /// Encapsulates information describing texture resources. + /// + struct TextureInformation + { + int Depth; + SurfaceFormat_t Format; + int Height; + ImageFileFormat_t ImageFormat; + int MipLevels; + ResourceType_t ResourceType_; + int Width; + + TextureInformation(int width, int height, int depth, int mipLevels, SurfaceFormat_t format); + TextureInformation(const TextureInformation &obj); //Copy Constructor + TextureInformation(); // Default Constructor + + bool Equals(TextureInformation other); + int GetHashCode(); + char* ToString(); + + bool operator!=(TextureInformation other); + bool operator==(TextureInformation other); + TextureInformation operator=(TextureInformation other); + }; + } +} + +#endif //_TEXTUREINFORMATION_ diff --git a/include/Graphics/VertexElement.h b/include/Graphics/VertexElement.h new file mode 100644 index 0000000..5f6014c --- /dev/null +++ b/include/Graphics/VertexElement.h @@ -0,0 +1,41 @@ +/******************************************************** + * VertexElement.h * + * * + * XFX VertexElement definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _VERTEXELEMENT_ +#define _VERTEXELEMENT_ + +#include +#include + +namespace XFX +{ + namespace Graphics + { + /// + /// Defines input vertex data to the pipeline. + /// + class VertexElement + { + public: + short Offset; + short Stream; + BYTE UsageIndex; + VertexElementFormat_t VertexElementFormat_; + VertexElementMethod_t VertexElementMethod_; + VertexElementUsage_t VertexElementUsage_; + + VertexElement(short stream, short offset, VertexElementFormat_t elementFormat, VertexElementMethod_t elementMethod, VertexElementUsage_t elementUsage, BYTE usageIndex); + + int Equals(const VertexElement &other); + int GetHashCode(); + + int operator!=(const VertexElement &other); + int operator==(const VertexElement &other); + }; + } +} + +#endif //_VERTEXELEMENT_ diff --git a/include/Graphics/VertexPositionNormalTexture.h b/include/Graphics/VertexPositionNormalTexture.h new file mode 100644 index 0000000..32f1c63 --- /dev/null +++ b/include/Graphics/VertexPositionNormalTexture.h @@ -0,0 +1,44 @@ +/******************************************************** + * VertexPositionNormalTexture.h * + * * + * XFX VertexPositionNormalTexture definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _VERTEXPOSITIONNORMALTEXTURE_ +#define _VERTEXPOSITIONNORMALTEXTURE_ + +#include "VertexElement.h" + +#include +#include + +namespace XFX +{ + namespace Graphics + { + /// + /// Describes a custom vertex format structure that contains position, normal data, + /// and one set of texture coordinates. + /// + class VertexPositionNormalTexture + { + public: + Vector3 Normal; + Vector3 Position; + Vector2 TextureCoordinate; + static const VertexElement VertexElements[]; + + static int SizeInBytes(); + + VertexPositionNormalTexture(Vector3 &position, Vector3 &normal, Vector2 &textureCoordinate); + + int Equals(const VertexPositionNormalTexture &other); + int GetHashCode(); + + int operator!=(const VertexPositionNormalTexture &other); + int operator==(const VertexPositionNormalTexture &other); + }; + } +} + +#endif //_VERTEXPOSITIONNORMALTEXTURE_ diff --git a/include/Graphics/VertexPositionTexture.h b/include/Graphics/VertexPositionTexture.h new file mode 100644 index 0000000..27c8257 --- /dev/null +++ b/include/Graphics/VertexPositionTexture.h @@ -0,0 +1,43 @@ +/******************************************************** + * VertexPositionTexture.h * + * * + * XFX VertexPositionTexture definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _VERTEXPOSITIONTEXTURE_ +#define _VERTEXPOSITIONTEXTURE_ + +#include "VertexElement.h" + +namespace XFX +{ + class Vector2; + class Vector3; + + namespace Graphics + { + /// + /// Describes a custom vertex format structure that contains position and one + /// set of texture coordinates. + /// + class VertexPositionTexture + { + public: + Vector3 Position; + Vector2 TextureCoordinate; + static const VertexElement VertexElements[]; + + static int SizeInBytes(); + + VertexPositionTexture(Vector3 &position, Vector2 &textureCoordinate); + + int Equals(const VertexPositionTexture &other); + int GetHashCode(); + + int operator!=(const VertexPositionTexture &other); + int operator==(const VertexPositionTexture &other); + }; + } +} + +#endif //_VERTEXPOSITIONTEXTURE_ diff --git a/include/Graphics/Viewport.h b/include/Graphics/Viewport.h new file mode 100644 index 0000000..01039c0 --- /dev/null +++ b/include/Graphics/Viewport.h @@ -0,0 +1,36 @@ +/******************************************************** + * Viewport.h * + * * + * XFX Viewport definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ + +namespace XFX +{ + struct Matrix; + struct Vector3; + + namespace Graphics + { + /// + /// Defines the window dimensions of a render-target surface onto which a 3D volume projects. + /// + struct Viewport + { + private: + static bool WithinEpsilon(float a, float b); + + public: + float AspectRatio(); + int Height; + int MaxDepth; + int MinDepth; + int Width; + int X; + int Y; + + Vector3 Project(Vector3 source, Matrix projection, Matrix view, Matrix world); + Vector3 Unproject(Vector3 source, Matrix projection, Matrix view, Matrix world); + }; + } +} diff --git a/include/GraphicsDeviceInformation.h b/include/GraphicsDeviceInformation.h new file mode 100644 index 0000000..cfb9f9d --- /dev/null +++ b/include/GraphicsDeviceInformation.h @@ -0,0 +1,31 @@ +/******************************************************** + * GraphicsDeviceInformation.h * + * * + * XFX GraphicsDeviceInformation definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _GRAPHICSDEVICEINFORMATION_ +#define _GRAPHICSDEVICEINFORMATION_ + +#include +#include + +using namespace XFX::Graphics; + +namespace XFX +{ + /// + /// Holds the settings for creating a graphics device. + /// + class GraphicsDeviceInformation + { + public: + GraphicsAdapter Adapter; + DeviceType deviceType; + PresentationParameters presentationParameters; + + GraphicsDeviceInformation Clone(); + }; +} + +#endif //_GRAPHICSDEVICEINFORMATION_ diff --git a/include/GraphicsDeviceManager.h b/include/GraphicsDeviceManager.h new file mode 100644 index 0000000..d60d792 --- /dev/null +++ b/include/GraphicsDeviceManager.h @@ -0,0 +1,60 @@ +/******************************************************** + * GraphicsDeviceManager.h * + * * + * XFX GraphicsDeviceManager definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_GRAPHICSDEVICEMANAGER_ +#define _XFX_GRAPHICSDEVICEMANAGER_ + +#include "Game.h" +#include "Graphics/GraphicsDevice.h" +#include "GraphicsDeviceInformation.h" +#include "Interfaces.h" +#include "Graphics/IGraphicsDeviceService.h" +#include "Graphics/Enums.h" +#include "System/Interfaces.h" + +using namespace System; +using namespace XFX::Graphics; + +namespace XFX +{ + class GraphicsDeviceManager : public IGraphicsDeviceService, public IDisposable, public IGraphicsDeviceManager + { + private: + bool isFullScreen; + Game _game; + GraphicsDevice graphicsDevice; + + protected: + virtual void Dispose(int disposing); + virtual int CanResetDevice(GraphicsDeviceInformation newDeviceInfo); + + public: + GraphicsDevice GraphicsDevice_(); + bool IsFullScreen(); + float MinimumPixelShaderProfile; + float MinimumVertexShaderProfile; + int PreferMultiSampling; + SurfaceFormat_t PreferredBackBufferFormat; + int PreferredBackBufferWidth; + int PreferredBackBufferHeight; + DepthFormat_t PreferredDepthStencilFormat; + int SynchronizeWithVerticalRetrace; + + static const int DefaultBackBufferWidth; + static const int DefaultBackBufferHeight; + static SurfaceFormat_t ValidAdapterFormats[]; + static SurfaceFormat_t ValidBackBufferFormats[]; + static const DeviceType_t ValidDeviceTypes[]; + + GraphicsDeviceManager(Game game); + + void ApplyChanges(); + void Dispose(); + void ToggleFullscreen(); + }; +} + +#endif //_XFX_GRAPHICSDEVICEMANAGER_ diff --git a/include/Input.h b/include/Input.h new file mode 100644 index 0000000..9c6cdda --- /dev/null +++ b/include/Input.h @@ -0,0 +1,34 @@ +/******************************************************** + * Input.h * + * * + * XFX::Input namespace include file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _INPUT_ +#define _INPUT_ + +extern "C"{ +#include +} + +// +//Data Types +// +#include "GamePad.h" +#include "GamePadButtons.h" +//#include "GamePadCapabilities.h" +#include "GamePadState.h" +#include "Keyboard.h" +#include "Mouse.h" +// +//Enums +// +//#include "Buttons.h" +#include "ButtonState.h" +#include "GamePadDeadZone.h" +#include "GamePadType.h" +// +//Interfaces +// + +#endif //_INPUT_ diff --git a/include/Input/Enums.h b/include/Input/Enums.h new file mode 100644 index 0000000..43a187b --- /dev/null +++ b/include/Input/Enums.h @@ -0,0 +1,111 @@ +/******************************************************** + * Enums.h * + * * + * XFX::Input enumeration definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_INPUT_ENUMS_ +#define _XFX_INPUT_ENUMS_ + +namespace XFX +{ + namespace Input + { + /// + /// Enumerates input device buttons. + /// + struct Buttons + { + enum type + { + A = 0, + B = 1, + Back = 0x20, + Black = 4, + DPadDown = 0x02, + DPadLeft = 0x04, + DPadRight = 0x08, + DPadUp = 0x01, + LeftStick = 0x40, + LeftThumbStickDown, + LeftThumbStickLeft, + LeftThumbStickRight, + LeftThumbStickUp, + LeftTrigger = 6, + RightStick = 0x80, + RightThumbStickDown, + RightThumbStickLeft, + RightThumbStickRight, + RightThumbStickUp, + RightTrigger = 7, + Start = 0x10, + White = 5, + X = 2, + Y = 3 + }; + }; + + /// + /// Identifies the state of a mouse button or Xbox Controller button. + /// + struct ButtonState + { + enum type + { + Pressed = 1, + Released = 0 + }; + }; + + /// + /// Specifies a type of dead zone processing to apply to Xbox controller analog sticks when calling GamePad::GetState. + /// + struct GamePadDeadZone + { + enum type + { + Circular, + IndependantAxes, + None + }; + }; + + /// + /// Describes the type of a given Xbox controller. + /// + struct GamePadType + { + enum type + { + ArcadeStick, + DancePad, + DrumKit, + FlightStick, + GamePad, + Guitar, + Unknown, + Wheel + }; + }; + + /// + /// Identifies the state of a keyboard key. + /// + struct KeyState + { + enum type + { + Down = 1, + Up = 0 + }; + }; + + typedef Buttons::type Buttons_t; + typedef ButtonState::type ButtonState_t; + typedef GamePadDeadZone::type GamePadDeadZone_t; + typedef GamePadType::type GamePadType_t; + typedef KeyState::type KeyState_t; + } +} + +#endif //_XFX_INPUT_ENUMS_ diff --git a/include/Input/GamePad.h b/include/Input/GamePad.h new file mode 100644 index 0000000..cf09c2e --- /dev/null +++ b/include/Input/GamePad.h @@ -0,0 +1,32 @@ +/******************************************************** + * GamePad.h * + * * + * XFX GamePad definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_INPUT_GAMEPAD_ +#define _XFX_INPUT_GAMEPAD_ + +#include +#include "Enums.h" +#include "GamePadState.h" + +namespace XFX +{ + namespace Input + { + /// + /// Allows retrieval of user interaction with an XBOX Controller + /// and setting of controller vibration motors. + /// + class GamePad + { + public: + static GamePadState GetState(PlayerIndex_t playerIndex); + static GamePadState GetState(PlayerIndex_t playerIndex, GamePadDeadZone_t deadZoneMode); + static int SetVibration(PlayerIndex_t playerIndex, float leftMotor, float rightMotor); + }; + } +} + +#endif //_XFX_INPUT_GAMEPAD_ diff --git a/include/Input/GamePadButtons.h b/include/Input/GamePadButtons.h new file mode 100644 index 0000000..229f38b --- /dev/null +++ b/include/Input/GamePadButtons.h @@ -0,0 +1,68 @@ +/******************************************************** + * GamePadButtons.h * + * * + * XFX GamePadButtons definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _GAMEPADBUTTONS_ +#define _GAMEPADBUTTONS_ + +#include "Enums.h" + +namespace XFX +{ + namespace Input + { + struct GamePadButtons + { + ButtonState_t A; + ButtonState_t B; + ButtonState_t Back; + ButtonState_t Black; + ButtonState_t LeftStick; + ButtonState_t RightStick; + ButtonState_t Start; + ButtonState_t White; + ButtonState_t X; + ButtonState_t Y; + + bool GamePadButtons::operator!=(const GamePadButtons &other) + { + return !((A == other.A) && (B == other.B) && (Back == other.Back) && + (Black == other.Black) && (LeftStick == other.LeftStick) && + (RightStick == other.RightStick) && (Start == other.Start) && + (White == other.White) && (X == other.X) && (Y == other.Y)); + } + + bool GamePadButtons::operator==(const GamePadButtons &other) + { + return ((A == other.A) && (B == other.B) && (Back == other.Back) && + (Black == other.Black) && (LeftStick == other.LeftStick) && + (RightStick == other.RightStick) && (Start == other.Start) && + (White == other.White) && (X == other.X) && (Y == other.Y)); + } + }; + + struct GamePadDPad + { + ButtonState_t Down; + ButtonState_t Left; + ButtonState_t Right; + ButtonState_t Up; + + bool GamePadDPad::operator!=(const GamePadDPad &other) + { + return !((Down == other.Down) && (Left == other.Left) && + (Right == other.Right) && (Up == other.Up)); + } + + bool GamePadDPad::operator==(const GamePadDPad &other) + { + return ((Down == other.Down) && (Left == other.Left) && + (Right == other.Right) && (Up == other.Up)); + } + }; + } +} + +#endif //_GAMEPADBUTTONS_ diff --git a/include/Input/GamePadState.h b/include/Input/GamePadState.h new file mode 100644 index 0000000..9f73fef --- /dev/null +++ b/include/Input/GamePadState.h @@ -0,0 +1,39 @@ +/******************************************************** + * GamePadState.h * + * * + * XFX GamePadState definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _GAMEPADSTATE_ +#define _GAMEPADSTATE_ + +#include "GamePadButtons.h" +#include "GamePadThumbSticks.h" +#include "GamePadTriggers.h" + +namespace XFX +{ + namespace Input + { + /// + /// Represents specific information about the state of an Xbox 360 Controller, including the current state of buttons + /// and sticks. + /// + struct GamePadState + { + GamePadButtons Buttons; + GamePadDPad DPad; + bool IsConnected; + GamePadThumbSticks ThumbSticks; + GamePadTriggers Triggers; + + bool IsButtonDown(Buttons_t button); + bool IsButtonUp(Buttons_t button); + + operator==(GamePadState other); + operator!=(GamePadState other); + }; + } +} + +#endif //_GAMEPADSTATE_ diff --git a/include/Input/Keyboard.h b/include/Input/Keyboard.h new file mode 100644 index 0000000..5d1cb2b --- /dev/null +++ b/include/Input/Keyboard.h @@ -0,0 +1,41 @@ +/******************************************************** + * Keyboard.h * + * * + * XFX Keyboard definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_INPUT_KEYBOARD_ +#define _XFX_INPUT_KEYBOARD_ + +#include "Enums.h" +#include "Keys.h" + +namespace XFX +{ + namespace Input + { + /// + /// Represents a state of keystrokes recorded by a keyboard input device. + /// + struct KeyboardState + { + KeyboardState(); + KeyboardState(unsigned char keys[]); + + unsigned char* GetPressedKeys(); + bool IsKeyDown(unsigned char key); + bool IsKeyUp(unsigned char key); + }; + + /// + /// Allows retrieval of keystrokes from a keyboard input device. + /// + class Keyboard + { + public: + static KeyboardState GetState(); + }; + } +} + +#endif //_XFX_INPUT_KEYBOARD_ diff --git a/include/Input/Mouse.h b/include/Input/Mouse.h new file mode 100644 index 0000000..e181047 --- /dev/null +++ b/include/Input/Mouse.h @@ -0,0 +1,48 @@ +/******************************************************** + * Mouse.h * + * * + * XFX Mouse definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_INPUT_MOUSE_ +#define _XFX_INPUT_MOUSE_ + +#include "Enums.h" +#include + +using namespace System; + +namespace XFX +{ + namespace Input + { + /// + /// + /// + struct MouseState + { + ButtonState_t LeftButton; + ButtonState_t MiddleButton; + ButtonState_t RightButton; + int X; + ButtonState_t XButton1; + ButtonState_t XButton2; + int Y; + + bool operator!=(const MouseState other); + bool operator==(const MouseState other); + }; + + /// + /// Allows retrieval of position and button clicks from a mouse input device. + /// + class Mouse + { + public: + static MouseState GetState(); + static void SetPosition(int x, int y); + }; + } +} + +#endif //_XFX_INPUT_MOUSE_ diff --git a/include/Interfaces.h b/include/Interfaces.h new file mode 100644 index 0000000..c03bacf --- /dev/null +++ b/include/Interfaces.h @@ -0,0 +1,74 @@ +/******************************************************** + * Interfaces.h * + * * + * XFX interfaces definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_INTERFACES_ +#define _XFX_INTERFACES_ + +#include + +namespace XFX +{ + class GameTime; + + /// + /// Defines the interface for a drawable game component. + /// + interface IDrawable + { + public: + virtual int DrawOrder()=0; + virtual bool Visible()=0; + + virtual void Draw(GameTime gameTime)=0; + virtual ~IDrawable(); + + EventHandler DrawOrderChanged; + EventHandler VisibleChanged; + }; + + /// + /// Defines an interface for game components. + /// + interface IGameComponent + { + public: + virtual void Initialize()=0; + virtual ~IGameComponent(); + }; + + /// + /// Defines the interface for an object that manages a Graphics.GraphicsDevice. + /// + interface IGraphicsDeviceManager + { + public: + virtual int BeginDraw()=0; + virtual void CreateDevice()=0; + virtual void EndDraw()=0; + + virtual ~IGraphicsDeviceManager(); + }; + + /// + /// Defines an interface for a game component that should be updated in Game.Update. + /// + interface IUpdateable + { + public: + virtual bool Enabled()=0; + virtual void Enabled(int value)=0; + virtual int UpdateOrder()=0; + virtual void UpdateOrder(int value)=0; + + virtual ~IUpdateable(); + virtual void Update(GameTime gameTime)=0; + + EventHandler EnabledChanged; + EventHandler UpdateOrderChanged; + }; +} + +#endif //_XFX_INTERFACES_ diff --git a/include/Keys.h b/include/Keys.h new file mode 100644 index 0000000..33fd98c --- /dev/null +++ b/include/Keys.h @@ -0,0 +1,250 @@ +/******************************************************** + * Keys.h * + * * + * XFX Keyboard Keys definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef KEYS_H +#define KEYS_H + +// Modifier key flag values +#define XKEYBOARD_LCONTROL_FLAG 0x01 +#define XKEYBOARD_LSHIFT_FLAG 0x02 +#define XKEYBOARD_LALT_FLAG 0x04 +#define XKEYBOARD_LWINDOWS_FLAG 0x08 +#define XKEYBOARD_RCONTROL_FLAG 0x10 +#define XKEYBOARD_RSHIFT_FLAG 0x20 +#define XKEYBOARD_RALT_FLAG 0x40 +#define XKEYBOARD_RWINDOWS_FLAG 0x80 + +// usb keyboard usage values for key modifiers +#define USB_KEYBOARD_USAGE_LCONTROL 0xE0 +#define USB_KEYBOARD_USAGE_LSHIFT 0xE1 +#define USB_KEYBOARD_USAGE_LALT 0xE2 +#define USB_KEYBOARD_USAGE_LWINDOWS 0xE3 +#define USB_KEYBOARD_USAGE_RCONTROL 0xE4 +#define USB_KEYBOARD_USAGE_RSHIFT 0xE5 +#define USB_KEYBOARD_USAGE_RALT 0xE6 +#define USB_KEYBOARD_USAGE_RWINDOWS 0xE7 + +// keyboard state flags - keyup, shift, ctrl, alt etc +#define XKEYBOARD_KEYUP 0x01 +#define XKEYBOARD_SHIFT 0x02 +#define XKEYBOARD_CONTROL 0x04 +#define XKEYBOARD_ALT 0x08 + +// key code constants +#define XKEY_INVALID 0x00 + +#define XKEY_LBUTTON 0x01 +#define XKEY_RBUTTON 0x02 +#define XKEY_CANCEL 0x03 +#define XKEY_MBUTTON 0x04 +#define XKEY_XBUTTON1 0x05 +#define XKEY_XBUTTON2 0x06 + +#define XKEY_BACKSPACE 0x08 +#define XKEY_TAB 0x09 + +#define XKEY_CLEAR 0x0C +#define XKEY_RETURN 0x0D + +#define XKEY_SHIFT 0x10 +#define XKEY_CONTROL 0x11 +#define XKEY_MENU 0x12 +#define XKEY_PAUSE 0x13 +#define XKEY_CAPSLOCK 0x14 +#define XKEY_KANA 0x15 +#define XKEY_JUNJA 0x17 +#define XKEY_FINAL 0x18 +#define XKEY_KANJI 0x19 + +#define XKEY_ESCAPE 0x1B +#define XKEY_CONVERT 0x1C +#define XKEY_NONCONVERT 0x1D +#define XKEY_ACCEPT 0x1E +#define XKEY_MODECHANGE 0x1F +#define XKEY_SPACE 0x20 +#define XKEY_PRIOR 0x21 +#define XKEY_NEXT 0x22 +#define XKEY_END 0x23 +#define XKEY_HOME 0x24 +#define XKEY_LEFT 0x25 +#define XKEY_UP 0x26 +#define XKEY_RIGHT 0x27 +#define XKEY_DOWN 0x28 +#define XKEY_SELECT 0x29 +#define XKEY_PRINT 0x2A +#define XKEY_EXECUTE 0x2B +#define XKEY_PRINTSCREEN 0x2C +#define XKEY_INSERT 0x2D +#define XKEY_DELETE 0x2E +#define XKEY_HELP 0x2F +#define XKEY_0 0x30 +#define XKEY_1 0x31 +#define XKEY_2 0x32 +#define XKEY_3 0x33 +#define XKEY_4 0x34 +#define XKEY_5 0x35 +#define XKEY_6 0x36 +#define XKEY_7 0x37 +#define XKEY_8 0x38 +#define XKEY_9 0x39 + +#define XKEY_A 0x41 +#define XKEY_B 0x42 +#define XKEY_C 0x43 +#define XKEY_D 0x44 +#define XKEY_E 0x45 +#define XKEY_F 0x46 +#define XKEY_G 0x47 +#define XKEY_H 0x48 +#define XKEY_I 0x49 +#define XKEY_J 0x4A +#define XKEY_K 0x4B +#define XKEY_L 0x4C +#define XKEY_M 0x4D +#define XKEY_N 0x4E +#define XKEY_O 0x4F +#define XKEY_P 0x50 +#define XKEY_Q 0x51 +#define XKEY_R 0x52 +#define XKEY_S 0x53 +#define XKEY_T 0x54 +#define XKEY_U 0x55 +#define XKEY_V 0x56 +#define XKEY_W 0x57 +#define XKEY_X 0x58 +#define XKEY_Y 0x59 +#define XKEY_Z 0x5A +#define XKEY_LWIN 0x5B +#define XKEY_RWIN 0x5C +#define XKEY_APPS 0x5D + +#define XKEY_SLEEP 0x5F +#define XKEY_NUMPAD0 0x60 +#define XKEY_NUMPAD1 0x61 +#define XKEY_NUMPAD2 0x62 +#define XKEY_NUMPAD3 0x63 +#define XKEY_NUMPAD4 0x64 +#define XKEY_NUMPAD5 0x65 +#define XKEY_NUMPAD6 0x66 +#define XKEY_NUMPAD7 0x67 +#define XKEY_NUMPAD8 0x68 +#define XKEY_NUMPAD9 0x69 +#define XKEY_MULTIPLY 0x6A +#define XKEY_ADD 0x6B +#define XKEY_NUMPAD_ENTER 0x6C +#define XKEY_SUBTRACT 0x6D +#define XKEY_DECIMAL 0x6E +#define XKEY_DIVIDE 0x6F +#define XKEY_F1 0x70 +#define XKEY_F2 0x71 +#define XKEY_F3 0x72 +#define XKEY_F4 0x73 +#define XKEY_F5 0x74 +#define XKEY_F6 0x75 +#define XKEY_F7 0x76 +#define XKEY_F8 0x77 +#define XKEY_F9 0x78 +#define XKEY_F10 0x79 +#define XKEY_F11 0x7A +#define XKEY_F12 0x7B +#define XKEY_F13 0x7C +#define XKEY_F14 0x7D +#define XKEY_F15 0x7E +#define XKEY_F16 0x7F +#define XKEY_F17 0x80 +#define XKEY_F18 0x81 +#define XKEY_F19 0x82 +#define XKEY_F20 0x83 +#define XKEY_F21 0x84 +#define XKEY_F22 0x85 +#define XKEY_F23 0x86 +#define XKEY_F24 0x87 + +#define XKEY_NUMLOCK 0x90 +#define XKEY_SCROLL_LOCK 0x91 +#define XKEY_NUMPADEQUALS 0x92 + +/* + * Fujitsu/OASYS kbd definitions + */ +#define XKEY_OEM_FJ_JISHO 0x92 // 'Dictionary' key +#define XKEY_OEM_FJ_MASSHOU 0x93 // 'Unregister word' key +#define XKEY_OEM_FJ_TOUROKU 0x94 // 'Register word' key +#define XKEY_OEM_FJ_LOYA 0x95 // 'Left OYAYUBI' key +#define XKEY_OEM_FJ_ROYA 0x96 // 'Right OYAYUBI' key + +#define XKEY_LSHIFT 0xA0 +#define XKEY_RSHIFT 0xA1 +#define XKEY_LCONTROL 0xA2 +#define XKEY_RCONTROL 0xA3 +#define XKEY_LMENU 0xA4 +#define XKEY_RMENU 0xA5 +#define XKEY_BROWSER_BACK 0xA6 +#define XKEY_BROWSER_FORWARD 0xA7 +#define XKEY_BROWSER_REFRESH 0xA8 +#define XKEY_BROWSER_STOP 0xA9 +#define XKEY_BROWSER_SEARCH 0xAA +#define XKEY_BROWSER_FAVORITES 0xAB +#define XKEY_BROWSER_HOME 0xAC +#define XKEY_VOLUME_MUTE 0xAD +#define XKEY_VOLUME_DOWN 0xAE +#define XKEY_VOLUME_UP 0xAF +#define XKEY_MEDIA_NEXT_TRACK 0xB0 +#define XKEY_MEDIA_PREV_TRACK 0xB1 +#define XKEY_MEDIA_STOP 0xB2 +#define XKEY_MEDIA_PLAY_PAUSE 0xB3 +#define XKEY_LAUNCH_MAIL 0xB4 +#define XKEY_LAUNCH_MEDIA_SELECT 0xB5 +#define XKEY_LAUNCH_APP1 0xB6 +#define XKEY_LAUNCH_APP2 0xB7 + +#define XKEY_SEMICOLON 0xBA +#define XKEY_EQUALS 0xBB +#define XKEY_COMMA 0xBC +#define XKEY_MINUS 0xBD +#define XKEY_PERIOD 0xBE +#define XKEY_SLASH 0xBF +#define XKEY_GRAVE 0xC0 + +#define XKEY_LBRACE 0xDB +#define XKEY_BACKSLASH 0xDC +#define XKEY_RBRACE 0xDD +#define XKEY_QUOTE 0xDE +#define XKEY_MISC 0xDF + +#define XKEY_OEM_AX 0xE1 +#define XKEY_OEM_102 0xE2 +#define XKEY_ICO_HELP 0xE3 +#define XKEY_ICO_00 0xE4 +#define XKEY_PROCESSKEY 0xE5 +#define XKEY_ICO_CLEAR 0xE6 +#define XKEY_PACKET 0xE7 + +#define XKEY_OEM_RESET 0xE9 +#define XKEY_OEM_JUMP 0xEA +#define XKEY_OEM_PA1 0xEB +#define XKEY_OEM_PA2 0xEC +#define XKEY_OEM_PA3 0xED +#define XKEY_OEM_WSCTRL 0xEE +#define XKEY_OEM_CUSEL 0xEF +#define XKEY_OEM_ATTN 0xF0 +#define XKEY_OEM_FINISH 0xF1 +#define XKEY_OEM_COPY 0xF2 +#define XKEY_OEM_AUTO 0xF3 +#define XKEY_OEM_ENLW 0xF4 +#define XKEY_OEM_BACKTAB 0xF5 + +#define XKEY_ATTN 0xF6 +#define XKEY_CRSEL 0xF7 +#define XKEY_EXSEL 0xF8 +#define XKEY_EREOF 0xF9 +#define XKEY_PLAY 0xFA +#define XKEY_ZOOM 0xFB +#define XKEY_NONAME 0xFC +#define XKEY_PA1 0xFD +#define XKEY_OEM_CLEAR 0xFE + +#endif //KEYS_H diff --git a/include/MathHelper.h b/include/MathHelper.h new file mode 100644 index 0000000..1791a46 --- /dev/null +++ b/include/MathHelper.h @@ -0,0 +1,43 @@ +/******************************************************** + * MathHelper.h * + * * + * XFX MathHelper definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_MATHHELPER_ +#define _SYSTEM_MATHHELPER_ + +namespace XFX +{ + /// + /// Contains commonly used precalculated values. + /// + class MathHelper + { + private: + MathHelper(); // Private constructor to prevent instantiation. + + public: + static const float E; + static const float Log10E; + static const float Log2E; + static const float Pi; + static const float PiOver2; + static const float PiOver4; + static const float TwoPi; + + static float Baricentric(float value1, float value2, float value3, float amount1, float amount2); + static float CatmullRom(float value1, float value2, float value3, float value4, float amount); + static float Clamp(float value, float min, float max); + static float Distance(float value1, float value2); + static float Hermite(float value1, float tangent1, float value2, float tangent2, float amount); + static float Lerp(float value1, float value2, float amount); + static float Max(float value1, float value2); + static float Min(float value1, float value2); + static float SmoothStep(float value1, float value2, float amount); + static float ToDegrees(float radians); + static float ToRadians(float degrees); + }; +} + +#endif //_SYSTEM_MATHHELPER_ diff --git a/include/Matrix.h b/include/Matrix.h new file mode 100644 index 0000000..f4a36be --- /dev/null +++ b/include/Matrix.h @@ -0,0 +1,144 @@ +/******************************************************** + * Matrix.h * + * * + * XFX Matrix definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_MATRIX_ +#define _XFX_MATRIX_ + +#include + +namespace XFX +{ + struct Plane; + struct Quaternion; + struct Vector3; + + /// + /// Defines a Matrix. + /// + struct Matrix + { + public: + float M11; + float M12; + float M13; + float M14; + float M21; + float M22; + float M23; + float M24; + float M31; + float M32; + float M33; + float M34; + float M41; + float M42; + float M43; + float M44; + Vector3 Backward(); + void Backward(Vector3 vector); + Vector3 Down(); + void Down(Vector3 vector); + Vector3 Forward(); + void Forward(Vector3 vector); + static const Matrix Identity; + Vector3 Left(); + void Left(Vector3 vector); + Vector3 Right(); + void Right(Vector3 vector); + Vector3 Translation(); + void Translation(Vector3 vector); + Vector3 Up(); + void Up(Vector3 vector); + + Matrix(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44); + Matrix(const Matrix& obj); + Matrix(); + + static Matrix Add(Matrix matrix1, Matrix matrix2); + static void Add(Matrix matrix1, Matrix matrix2, out Matrix result); + static Matrix CreateBillboard(Vector3 objectPosition, Vector3 cameraPosition, Vector3 cameraUpVector, Vector3* cameraForwardVector); + static void CreateBillboard(Vector3 objectPosition, Vector3 cameraPosition, Vector3 cameraUpVector, Vector3* cameraForwardVector, out Matrix result); + static Matrix CreateConstrainedBillboard(Vector3 objectPosition, Vector3 cameraPosition, Vector3 rotateAxis, Vector3* cameraForwardVector, Vector3* objectForwardVector); + static void CreateConstrainedBillboard(Vector3 objectPosition, Vector3 cameraPosition, Vector3 rotateAxis, Vector3* cameraForwardVector, Vector3* objectForwardVector, out Matrix result); + static Matrix CreateFromAxisAngle(Vector3 axis, float angle); + static void CreateFromAxisAngle(Vector3 axis, float angle, out Matrix result); + static Matrix CreateFromQuaternion(Quaternion rotation); + static void CreateFromQuaternion(Quaternion rotation, out Matrix result); + static Matrix CreateFromYawPitchRoll(float yaw, float pitch, float roll); + static void CreateFromYawPitchRoll(float yaw, float pitch, float roll, out Matrix result); + static Matrix CreateLookAt(Vector3 cameraPosition, Vector3 cameraTarget, Vector3 cameraUpVector); + static void CreateLookAt(Vector3 cameraPosition, Vector3 cameraTarget, Vector3 cameraUpVector, out Matrix result); + static Matrix CreateOrthographic(float width, float height, float zNearPlane, float zFarPlane); + static void CreateOrthographic(float width, float height, float zNearPlane, float zFarPlane, out Matrix result); + static Matrix CreateOrthographicOffCenter(float left, float right, float bottom, float top, float zNearPlane, float zFarPlane); + static void CreateOrthographicOffCenter(float left, float right, float bottom, float top, float zNearPlane, float zFarPlane, out Matrix result); + static Matrix CreatePerspective(float width, float height, float zNearPlane, float zFarPlane); + static void CreatePerspective(float width, float height, float zNearPlane, float zFarPlane, out Matrix result); + static Matrix CreatePerspectiveFieldOfView(float fieldOfView, float aspectRatio, float nearPlaneDistance, float farPlaneDistance); + static void CreatePerspectiveFieldOfView(float fieldOfView, float aspectRatio, float nearPlaneDistance, float farPlaneDistance, out Matrix result); + static Matrix CreatePerspectiveOffCenter(float left, float right, float bottom, float top, float nearPlaneDistance, float farPlaneDistance); + static void CreatePerspectiveOffCenter(float left, float right, float bottom, float top, float nearPlaneDistance, float farPlaneDistance, out Matrix result); + static Matrix CreateReflection(Plane value); + static void CreateReflection(Plane value, out Matrix result); + static Matrix CreateRotationX(float radians); + static void CreateRotationX(float radians, out Matrix result); + static Matrix CreateRotationY(float radians); + static void CreateRotationY(float radians, out Matrix result); + static Matrix CreateRotationZ(float radians); + static void CreateRotationZ(float radians, out Matrix result); + static Matrix CreateScale(float scale); + static void CreateScale(float scale, out Matrix result); + static Matrix CreateScale(float xScale, float yScale, float zScale); + static void CreateScale(float xScale, float yScale, float zScale, out Matrix result); + static Matrix CreateScale(Vector3 scales); + static void CreateScale(Vector3 scales, out Matrix result); + static Matrix CreateShadow(Vector3 lightDirection, Plane plane); + static void CreateShadow(Vector3 lightDirection, Plane plane, out Matrix result); + static Matrix CreateTranslation(float xPosition, float yPosition, float zPosition); + static void CreateTranslation(float xPosition, float yPosition, float zPosition, out Matrix result); + static Matrix CreateTranslation(Vector3 position); + static void CreateTranslation(Vector3 position, out Matrix result); + static Matrix CreateWorld(Vector3 position, Vector3 forward, Vector3 up); + static void CreateWorld(Vector3 position, Vector3 forward, Vector3 up, out Matrix result); + int Decompose(out Vector3 scale, out Quaternion rotation, out Vector3 translation); + float Determinant(); + static Matrix Divide(Matrix matrix1, Matrix matrix2); + static void Divide(Matrix matrix1, Matrix matrix2, out Matrix result); + static Matrix Divide(Matrix matrix1, float divider); + static void Divide(Matrix matrix1, float divider, out Matrix result); + bool Equals(Matrix other); + int GetHashCode(); + static Matrix Invert(Matrix matrix); + static void Invert(Matrix matrix, out Matrix result); + static Matrix Lerp(Matrix value1, Matrix value2, float amount); + static void Lerp(Matrix value1, Matrix value2, float amount, out Matrix result); + static Matrix Multiply(Matrix matrix1, Matrix matrix2); + static void Multiply(Matrix matrix1, Matrix matrix2, out Matrix result); + static Matrix Multiply(Matrix matrix1, float scaleFactor); + static void Multiply(Matrix matrix1, float scaleFactor, out Matrix result); + static Matrix Negate(Matrix matrix); + static void Negate(Matrix matrix, out Matrix result); + static Matrix Subtract(Matrix matrix1, Matrix matrix2); + static void Subtract(Matrix matrix1, Matrix matrix2, out Matrix result); + static Matrix Transform(Matrix value, Quaternion rotation); + static void Transform(Matrix value, Quaternion rotation, out Matrix result); + static Matrix Transpose(Matrix matrix); + static void Transpose(Matrix matrix, out Matrix result); + + Matrix operator+(const Matrix other); + Matrix operator/(const Matrix other); + Matrix operator/(const float divider); + bool operator==(const Matrix other); + bool operator!=(const Matrix other); + Matrix operator*(const Matrix other); + Matrix operator*(const float scaleFactor); + Matrix operator-(const Matrix other); + Matrix operator-(); + Matrix operator=(const Matrix other); + } ALIGNED; +} + +#endif //_XFX_MATRIX_ diff --git a/include/Media/Enums.h b/include/Media/Enums.h new file mode 100644 index 0000000..d689cb6 --- /dev/null +++ b/include/Media/Enums.h @@ -0,0 +1,58 @@ +/******************************************************** + * Enums.h * + * * + * XFX::Media enumeration definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _MEDIA_ENUMS_H_ +#define _MEDIA_ENUMS_H_ + +namespace XFX +{ + namespace Media + { + /// + /// Type of the media source. + /// + struct MediaSourceType + { + enum type + { + LocalDevice, + WindowsMediaConnect + }; + }; + + /// + /// Media playback state (playing, paused, or stopped). + /// + struct MediaState + { + enum type + { + Paused, + Playing, + Stopped + }; + }; + + /// + /// Type of sounds in a video + /// + struct VideoSoundtrackType + { + enum type + { + Dialog, + Music, + MusicAndDialog + }; + }; + + typedef MediaSourceType::type MediaSourceType_t; + typedef MediaState::type MediaState_t; + typedef VideoSoundtrackType::type VideoSoundtrackType_t; + } +} + +#endif //_MEDIA_ENUMS_H_ diff --git a/include/Media/Video.h b/include/Media/Video.h new file mode 100644 index 0000000..86d33eb --- /dev/null +++ b/include/Media/Video.h @@ -0,0 +1,32 @@ +/******************************************************** + * Video.h * + * * + * XFX Video definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _VIDEO_H_ +#define _VIDEO_H_ + +#include +#include "Enums.h" + +namespace XFX +{ + namespace Media + { + /// + /// Represents a video. + /// + class Video + { + public: + TimeSpan Duration(); + float FramesPerSecond(); + int Height(); + VideoSoundtrackType_t videoSoundtrackType(); + int Width(); + }; + } +} + +#endif //_VIDEO_H_ diff --git a/include/Media/VideoPlayer.h b/include/Media/VideoPlayer.h new file mode 100644 index 0000000..ccac74b --- /dev/null +++ b/include/Media/VideoPlayer.h @@ -0,0 +1,53 @@ +/******************************************************** + * VideoPlayer.h * + * * + * XFX VideoPlayer file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _VIDEOPLAYER_H_ +#define _VIDEOPLAYER_H_ + +#include "../Graphics/Texture2D.h" + +namespace XFX +{ + class TimeSpan; + + namespace Media + { + class Video; + + /// + /// Provides methods and properties to playback, pause, resume, and stop video. VideoPlayer also exposes repeat, volume, and play position information. + /// + class VideoPlayer + { + private: + int isDisposed; + void Dispose(bool disposing); + + protected: + ~VideoPlayer(); + + public: + int IsDisposed(); + int IsLooped; + int IsMuted; + TimeSpan PlayPosition(); + MediaState_t State(); + Video Video_(); + float Volume; + + VideoPlayer(); + + void Dispose(); + Texture2D GetTexture(); + void Pause(); + void Play(Video &video); + void Resume(); + void Stop(); + }; + } +} + +#endif //_VIDEOPLAYER_H_ diff --git a/include/Net/Enums.h b/include/Net/Enums.h new file mode 100644 index 0000000..10f4135 --- /dev/null +++ b/include/Net/Enums.h @@ -0,0 +1,87 @@ +/******************************************************** + * Enums.h * + * * + * XFX::Net enumerations definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_NET_ENUMS_ +#define _XFX_NET_ENUMS_ + +namespace XFX +{ + namespace Net + { + /// + /// Defines the reason a session ended. + /// + struct NetworkSessionEndReason + { + enum type + { + ClientSignedOut, + HostEndedSession, + RemovedByHost, + Disconnected + }; + }; + /// + /// Contains additional data about a NetworkSessionJoinException. + /// + struct NetworkSessionJoinError + { + enum type + { + SessionNotFound, + SessionNotJoinable, + SessionFull + }; + }; + /// + /// Defines the different states of a multiplayer session. + /// + struct NetworkSessionState + { + enum type + { + Lobby, + Playing, + Ended + }; + }; + /// + /// Defines the different types of a multiplayer session. + /// + struct NetworkSessionType + { + enum type + { + Local, + SystemLink, + PlayerMatch, + Ranked + }; + }; + + /// + /// Defines options for network packet transmission. + /// + struct SendDataOptions + { + enum type + { + InOrder = 2, + None = 0, + Reliable = 1, + ReliableInOrder = 3 + }; + }; + + typedef NetworkSessionEndReason::type NetworkSessionEndReason_t; + typedef NetworkSessionJoinError::type NetworkSessionJoinError_t; + typedef NetworkSessionState::type NetworkSessionState_t; + typedef NetworkSessionType::type NetworkSessionType_t; + typedef SendDataOptions::type SendDataOptions_t; + } +} + +#endif //_XFX_NET_ENUMS_ diff --git a/include/Net/NetworkException.h b/include/Net/NetworkException.h new file mode 100644 index 0000000..7a631b9 --- /dev/null +++ b/include/Net/NetworkException.h @@ -0,0 +1,39 @@ +#ifndef _XFX_NET_NETWORKEXCEPTION_ +#define _XFX_NET_NETWORKEXCEPTION_ + +#include +#include "Enums.h" + +namespace XFX +{ + namespace Net + { + /// + /// Thrown if there is a network communication failure. + /// + class NetworkException : Exception + { + public: + public NetworkException(); + public NetworkException(char* message); + public NetworkException(char* message, Exception innerException); + }; + + /// + /// Thrown if an error was encountered while joining a session. + /// + class NetworkSessionJoinException : NetworkException + { + public: + public NetworkSessionJoinException(); + public NetworkSessionJoinException(char* message); + public NetworkSessionJoinException(char* message, NetworkSessionJoinError joinError); + public NetworkSessionJoinException(char* message, Exception innerException); + + public NetworkSessionJoinError JoinError(); //! get + public void JoinError(NetworkSessionJoinError joinError); //! set + }; + } +} + +#endif //_XFX_NET_NETWORKEXCEPTION_ diff --git a/include/Plane.h b/include/Plane.h new file mode 100644 index 0000000..06db6d8 --- /dev/null +++ b/include/Plane.h @@ -0,0 +1,65 @@ +/******************************************************** + * Plane.h * + * * + * XFX Plane definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_PLANE_ +#define _XFX_PLANE_ + +#include +#include "Enums.h" +#include "Vector3.h" + +namespace XFX +{ + struct BoundingBox; + struct BoundingSphere; + struct Matrix; + struct Quaternion; + struct Vector4; + + /// + /// Defines a plane. + /// + struct Plane + { + public: + float D; + Vector3 Normal; + + Plane(float a, float b, float c, float d); + Plane(Vector3 normal, float d); + Plane(Vector3 point1, Vector3 point2, Vector3 point3); + Plane(Vector4 value); + Plane(const Plane &obj); + Plane(); + + float Dot(Vector4 value); + void Dot(Vector4 value, out float result); + float DotCoordinate(Vector3 value); + void DotCoordinate(Vector3 value, out float result); + float DotNormal(Vector3 value); + void DotNormal(Vector3 value, out float result); + bool Equals(const Plane obj); + int GetHashCode(); + PlaneIntersectionType_t Intersects(BoundingBox boundingbox); + void Intersects(BoundingBox boundingbox, out PlaneIntersectionType_t result); + PlaneIntersectionType_t Intersects(BoundingSphere sphere); + void Intersects(BoundingSphere sphere, out PlaneIntersectionType_t result); + void Normalize(); + Plane Normalize(Plane plane); + void Normalize(Plane plane, out Plane result); + static Plane Transform(Plane plane, Matrix matrix); + static void Transform(Plane plane, Matrix matrix, out Plane result); + static Plane Transform(Plane plane, Quaternion quaternion); + static void Transform(Plane plane, Quaternion quaternion, out Plane result); + + + bool operator==(const Plane other); + bool operator!=(const Plane other); + Plane operator=(const Plane other); + }; +} + +#endif //_XFX_PLANE_ diff --git a/include/Point.h b/include/Point.h new file mode 100644 index 0000000..5ace3ff --- /dev/null +++ b/include/Point.h @@ -0,0 +1,32 @@ +/******************************************************** + * Point.h * + * * + * XFX Point definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _POINT_ +#define _POINT_ + +#include + +namespace XFX +{ + class Point + { + public: + int X; + int Y; + static const Point Zero; + + Point(int x, int y); + Point(const Point &obj); + Point(); + + int Equals(const Point &obj); + int operator==(const Point &other); + int operator!=(const Point &other); + Point &operator=(const Point &other); + }; +} + +#endif //_POINT_ diff --git a/include/Quaternion.h b/include/Quaternion.h new file mode 100644 index 0000000..95b8c1f --- /dev/null +++ b/include/Quaternion.h @@ -0,0 +1,76 @@ +/******************************************************** + * Quaternion.h * + * * + * XFX Quaternion definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_QUATERNION_ +#define _XFX_QUATERNION_ + +#include + +namespace XFX +{ + struct Matrix; + struct Vector3; + + struct Quaternion + { + public: + float W, X, Y, Z; + static const Quaternion Identity; + + Quaternion(float x, float y, float z, float w); + Quaternion(Vector3 vectorPart, float scalarPart); + Quaternion(const Quaternion &obj); + Quaternion(); + + static Quaternion Add(Quaternion quaternion1, Quaternion quaternion2); + static void Add(Quaternion quaternion1, Quaternion quaternion2, out Quaternion result); + static Quaternion Concatenate(Quaternion quaternion1, Quaternion quaternion2); + static void Concatenate(Quaternion quaternion1, Quaternion quaternion2, out Quaternion result); + void Conjugate(); + static Quaternion Conjugate(Quaternion value); + static void Conjugate(Quaternion value, out Quaternion result); + static Quaternion CreateFromAxisAngle(Vector3 axis, float angle); + static void CreateFromAxisAngle(Vector3 axis, float angle, out Quaternion result); + static Quaternion CreateFromRotationMatrix(Matrix matrix); + static void CreateFromRotationMatrix(Matrix matrix, out Quaternion result); + static Quaternion CreateFromYawPitchRoll(float yaw, float pitch, float roll); + static void CreateFromYawPitchRoll(float yaw, float pitch, float roll, out Quaternion result); + static Quaternion Divide(Quaternion quaternion1, Quaternion quaternion2); + static void Divide(Quaternion quaternion1, Quaternion quaternion2, out Quaternion result); + static float Dot(Quaternion quaternion1, Quaternion quaternion2); + static void Dot(Quaternion quaternion1, Quaternion quaternion2, out float result); + bool Equals(Quaternion obj); + static Quaternion Inverse(Quaternion quaternion); + static void Inverse(Quaternion quaternion, out Quaternion result); + float Length(); + float LengthSquared(); + static Quaternion Lerp(Quaternion quaternion1, Quaternion quaternion2, float amount); + static void Lerp(Quaternion quaternion1, Quaternion quaternion2, float amount, out Quaternion result); + static Quaternion Multiply(Quaternion quaternion1, Quaternion quaternion2); + static void Multiply(Quaternion quaternion1, Quaternion quaternion2, out Quaternion result); + static Quaternion Multiply(Quaternion quaternion, float scaleFactor); + static void Multiply(Quaternion quaternion, float scaleFactor, out Quaternion result); + static Quaternion Negate(Quaternion quaternion); + static void Negate(Quaternion quaternion, out Quaternion result); + void Normalize(); + static Quaternion Slerp(Quaternion quaternion1, Quaternion quaternion2, float amount); + static void Slerp(Quaternion quaternion1, Quaternion quaternion2, float amount, out Quaternion result); + static Quaternion Subtract(Quaternion quaternion1, Quaternion quaternion2); + static void Subtract(Quaternion quaternion1, Quaternion quaternion2, out Quaternion result); + + const Quaternion operator+(const Quaternion other); + const Quaternion operator/(const Quaternion other); + bool operator==(const Quaternion other); + bool operator!=(const Quaternion other); + const Quaternion operator*(const Quaternion other); + const Quaternion operator*(const float scaleFactor); + const Quaternion operator-(const Quaternion other); + const Quaternion operator-(); + Quaternion operator=(const Quaternion other); + } ALIGNED; +} + +#endif //_XFX_QUATERNION_ diff --git a/include/Ray.h b/include/Ray.h new file mode 100644 index 0000000..b99c257 --- /dev/null +++ b/include/Ray.h @@ -0,0 +1,47 @@ +/******************************************************** + * Ray.h * + * * + * XFX Ray definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_RAY_ +#define _XFX_RAY_ + +#include + +namespace XFX +{ + struct BoundingBox; + struct BoundingSphere; + struct Plane; + struct Vector3; + + /// + /// Defines a ray. + /// + class Ray + { + public: + Vector3 Direction; + Vector3 Position; + + Ray(Vector3 direction, Vector3 position); + Ray(const Ray &obj); + Ray(); + + bool Equals(Ray obj); + int GetHashCode(); + float Intersects(BoundingBox boundingbox); + void Intersects(BoundingBox boundingbox, out float result); + float Intersects(BoundingSphere sphere); + void Intersects(BoundingSphere sphere, out float result); + float Intersects(Plane plane); + void Intersects(Plane plane, out float result); + + bool operator==(const Ray other); + bool operator!=(const Ray other); + Ray operator=(const Ray other); + }; +} + +#endif //_RAY_ diff --git a/include/Rectangle.h b/include/Rectangle.h new file mode 100644 index 0000000..52c62c5 --- /dev/null +++ b/include/Rectangle.h @@ -0,0 +1,50 @@ +/******************************************************** + * Rectangle.h * + * * + * XFX Rectangle definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_RECTANGLE_ +#define _XFX_RECTANGLE_ + +#include + +namespace XFX +{ + struct Point; + + struct Rectangle + { + public: + int Bottom(); + int Left(); + int Right(); + int Top(); + int X, Y; + static const Rectangle Empty; + int Width, Height; + + Rectangle(int x,int y,int width,int height); + Rectangle(const Rectangle &obj); + Rectangle(); + + int Contains(int x, int y); + int Contains(Point pt); + void Contains(Point pt, out int result); + int Contains(Rectangle other); + void Contains(Rectangle other, out int result); + int Equals(const Rectangle obj); + int GetHashCode(); + void Inflate(int horizontalAmount, int verticalAmount); + int Intersects(Rectangle other); + void Intersects(Rectangle other, out int result); + void Offset(int x, int y); + void Offset(Point pt); + + int operator==(const Rectangle other); + int operator!=(const Rectangle other); + Rectangle &operator=(const Rectangle other); + }; +} + +#endif //_RECTANGLE_ diff --git a/include/Storage.h b/include/Storage.h new file mode 100644 index 0000000..94d6963 --- /dev/null +++ b/include/Storage.h @@ -0,0 +1,13 @@ +/******************************************************** + * Storage.h * + * * + * XFX::Storage namespace include file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef STORAGE_H +#define STORAGE_H + +#include "StorageContainer.h" +#include "StorageDevice.h" + +#endif //STORAGE_H diff --git a/include/Storage/StorageContainer.h b/include/Storage/StorageContainer.h new file mode 100644 index 0000000..509abe9 --- /dev/null +++ b/include/Storage/StorageContainer.h @@ -0,0 +1,47 @@ +/******************************************************** + * StorageContainer.h * + * * + * XFX StorageContainer definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_STORAGE_STORAGECONTAINER_ +#define _XFX_STORAGE_STORAGECONTAINER_ + +#include +#include +#include <../Enums.h> + +namespace XFX +{ + namespace Storage + { + class StorageDevice; + + /// + /// Represents a logical collection of storage files. + /// + class StorageContainer : public IDisposable + { + private: + bool isDisposed; + DirectoryInfo containerFolder; + StorageDevice device; + EventHandler Disposing; + PlayerIndex_t playerIndex; + char* titleName; + ~StorageContainer(); + + public: + bool IsDisposed(); + char* Path(); + StorageDevice StorageDevice_(); + static char* TitleLocation(); + char* TitleName(); + + void Delete(); + void Dispose(); + }; + } +} + +#endif //_XFX_STORAGE_STORAGECONTAINER_ diff --git a/include/Storage/StorageDevice.h b/include/Storage/StorageDevice.h new file mode 100644 index 0000000..49a7cb6 --- /dev/null +++ b/include/Storage/StorageDevice.h @@ -0,0 +1,40 @@ +/******************************************************** + * StorageDevice.h * + * * + * XFX StorageDevice definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_STORAGE_STORAGEDEVICE_ +#define _XFX_STORAGE_STORAGEDEVICE_ + +#include +#include "../Enums.h" + +namespace XFX +{ + namespace Storage + { + class StorageContainer; + + /// + /// Represents a storage device for user data, such as a memory unit or hard drive. + /// + class StorageDevice + { + private: + PlayerIndex_t _playerIndex; + bool _playerSpecified; + + StorageDevice(PlayerIndex_t playerIndex, bool playerSpecified); + + public: + long long FreeSpace(); + bool IsConnected(); + long long TotalSpace(); + + StorageContainer OpenContainer(char* titleName); + } + } +} + +#endif //_XFX_STORAGE_STORAGEDEVICE_ diff --git a/include/Storage/StorageDeviceNotConnectedException.h b/include/Storage/StorageDeviceNotConnectedException.h new file mode 100644 index 0000000..e00eb70 --- /dev/null +++ b/include/Storage/StorageDeviceNotConnectedException.h @@ -0,0 +1,29 @@ +/******************************************************** + * StorageDeviceNotConnectedException.h * + * * + * XFX StorageDeviceNotConnectedException definition * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_STORAGE_STORAGEDEVICENOTCONNECTEDEXCEPTION_ +#define _XFX_STORAGE_STORAGEDEVICENOTCONNECTEDEXCEPTION_ + +#include + +namespace XFX +{ + namespace Storage + { + /// + /// The exception that is thrown when the requested StorageDevice is not connected + /// + class StorageDeviceNotConnectedException : ExternalException + { + public: + StorageDeviceNotConnectedException(); + StorageDeviceNotConnectedException(char* message); + StorageDeviceNotConnectedException(char* message, Exception innerException); + }; + } +} + +#endif //_XFX_STORAGE_STORAGEDEVICENOTCONNECTEDEXCEPTION_ diff --git a/include/System.h b/include/System.h new file mode 100644 index 0000000..2693937 --- /dev/null +++ b/include/System.h @@ -0,0 +1,30 @@ +/******************************************************** + * System.h * + * * + * XFX System namespace include file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_ +#define _SYSTEM_ + +// Type definitions +#include "System/Types.h" + +// +//Interfaces +// +#include "System/Interfaces.h" +// +//Classes +// +#include "System/Array.h" +#include "System/BitConverter.h" +#include "System/Buffer.h" +#include "System/DateTime.h" +#include "System/Exception.h" //Class-based Exception handling +#include "System/Math.h" +#include "System/Threading/Thread.h" //Experimental! Use at own risk! +#include "System/TimeSpan.h" +#include "System/TimeZone.h" + +#endif //_SYSTEM_ diff --git a/include/System/Array.h b/include/System/Array.h new file mode 100644 index 0000000..06cacb5 --- /dev/null +++ b/include/System/Array.h @@ -0,0 +1,27 @@ +/******************************************************** + * Array.h * + * * + * XFX Array class definition file * + * Contains array helper methods * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_ARRAY_ +#define _SYSTEM_ARRAY_ + +namespace System +{ + class Array + { + public: + template + static void Clear(T array[], int index, int length); + template + static void Copy(T sourceArray[], int sourceIndex, T destinationArray[], int destinationIndex, int length); + template + static int IndexOf(T array[], T value, int startIndex, int count); + template + static int Length(T array[]); + }; +} + +#endif //_SYSTEM_ARRAY_ diff --git a/include/System/BitConverter.h b/include/System/BitConverter.h new file mode 100644 index 0000000..e0d9329 --- /dev/null +++ b/include/System/BitConverter.h @@ -0,0 +1,47 @@ +/******************************************************** + * BitConverter.h * + * * + * XFX BitConverter definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_BITCONVERTER_ +#define _SYSTEM_BITCONVERTER_ + +#include "Types.h" + +namespace System +{ + /// + /// Converts base data types to an array of bytes, and an array of bytes to base data types. + /// + class BitConverter + { + private: + static byte *GetBytes(byte *ptr, int count); + static bool AmIBigOrLittleEndian(); + static bool SwappedWordsInDouble(); + + BitConverter(); //! private constructor to prevent instantiation + + public: + static const bool IsLittleEndian; + + static byte *GetBytes(bool value); + static byte *GetBytes(char value); + static byte *GetBytes(double value); + static byte *GetBytes(short value); + static byte *GetBytes(int value); + static byte *GetBytes(Int64 value); + static byte *GetBytes(float value); + static byte *GetBytes(UInt16 value); + static byte *GetBytes(UInt32 value); + static byte *GetBytes(UInt64 value); + static bool ToBoolean(byte value[], int startIndex); + static char ToChar(byte value[], int startIndex); + static double ToDouble(byte value[], int startIndex); + static Int16 ToInt16(byte value[], int startIndex); + static Int32 ToInt32(byte value[], int startIndex); + }; +} + +#endif //_SYSTEM_BITCONVERTER_ diff --git a/include/System/Buffer.h b/include/System/Buffer.h new file mode 100644 index 0000000..b4107bf --- /dev/null +++ b/include/System/Buffer.h @@ -0,0 +1,31 @@ +/******************************************************** + * Buffer.h * + * * + * XFX Buffer class definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_BUFFER_ +#define _SYSTEM_BUFFER_ + +#include "Types.h" + +namespace System +{ + /// + /// Manipulates arrays of primitive types. + /// + class Buffer + { + public: + template + static void BlockCopy(T src[], int srcOffset, T dst[], int dstOffset, int count); + template + static int ByteLength(T array[]); + template + static byte GetByte(T array[], int index); + template + static void SetByte(T array[], int index, byte value); + }; +} + +#endif //_SYSTEM_BUFFER_ diff --git a/include/System/Collections/Generic/Comparer.h b/include/System/Collections/Generic/Comparer.h new file mode 100644 index 0000000..68b6450 --- /dev/null +++ b/include/System/Collections/Generic/Comparer.h @@ -0,0 +1,34 @@ +#ifndef _SYSTEM_COLLECTIONS_GENERIC_COMPARER_ +#define _SYSTEM_COLLECTIONS_GENERIC_COMPARER_ + +#include +#include "Interfaces.h" + +namespace System +{ + namespace Collections + { + namespace Generic + { + /// + /// Provides a base class for implementations of the System.Collections.Generic.IComparer generic interface. + /// + class Comparer : public IComparer + { + private: + static Comparer defaultComparer; + static Comparer CreateComparer(); + + protected: + Comparer(); + + public: + static Comparer Default(); + + virtual int Compare(T x, T y)=0; + }; + } + } +} + +#endif //_SYSTEM_COLLECTIONS_GENERIC_COMPARER_ diff --git a/include/System/Collections/Generic/Dictionary.h b/include/System/Collections/Generic/Dictionary.h new file mode 100644 index 0000000..c997ca8 --- /dev/null +++ b/include/System/Collections/Generic/Dictionary.h @@ -0,0 +1,123 @@ +/******************************************************** + * Dictionary.h * + * * + * XFX Generic Dictionary class definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_COLLECTIONS_GENERIC_DICTIONARY_ +#define _SYSTEM_COLLECTIONS_GENERIC_DICTIONARY_ + +#include "Interfaces.h" +#include "KeyValuePair.h" + +namespace System +{ + namespace Collections + { + namespace Generic + { + /// + /// Represents a collection of keys and values. + /// + template + class Dictionary : public IDictionary, public ICollection > + { + private: + template + struct Entry + { + int hashCode; + int next; + UKey key; + UValue value; + }; + + private: + int buckets[]; + static const char* ComparerName; + IEqualityComparer comparer; + int count; + Entry entries[]; + int freeCount; + int freeList; + static const char* HashSizeName; + static const char* KeyValuePairsName; + int version; + static const char* VersionName; + + void Add(KeyValuePair keyValuePair); + bool Contains(KeyValuePair keyValuePair); + void CopyTo(KeyValuePair array[], int index); + int FindEntry(TKey key); + bool Remove(KeyValuePair keyValuePair); + void Initialize(int capacity); + void Insert(TKey key, TValue value, bool add); + void Resize(); + + public: + /// + /// Represents the collection of keys in a Dictionary<,>. + /// + template + class KeyCollection : public ICollection, public IEnumerable + { + private: + Dictionary *_dictionary; + + public: + int Count(); + + KeyCollection(Dictionary dictionary); + + void Add(UKey item); + void Clear(); + bool Contains(UKey item); + void CopyTo(UKey array[], int index); + bool Remove(UKey item); + }; + + /// + /// Represents the collection of values in a Dictionary<,>. + /// + template + class ValueCollection : public ICollection, public IEnumerable + { + private: + Dictionary *_dictionary; + + public: + int Count(); + + ValueCollection(Dictionary dictionary); + + void Add(UValue item); + void Clear(); + bool Contains(UValue item); + void CopyTo(UValue array[], int index); + bool Remove(UValue item); + }; + + public: + IEqualityComparer Comparer(); + int Count(); + KeyCollection Keys(); + ValueCollection Values(); + TValue operator[](TKey key); + + Dictionary(); + Dictionary(IDictionary dictionary); + Dictionary(int capacity); + ~Dictionary(); + + void Add(TKey key, TValue value); + void Clear(); + bool ContainsKey(TKey key); + bool ContainsValue(TValue value); + bool Remove(TKey key); + bool TryGetValue(TKey key, out TValue value); + }; + } + } +} + +#endif //_SYSTEM_COLLECTIONS_GENERIC_DICTIONARY_ diff --git a/include/System/Collections/Generic/EqualityComparer.h b/include/System/Collections/Generic/EqualityComparer.h new file mode 100644 index 0000000..a317209 --- /dev/null +++ b/include/System/Collections/Generic/EqualityComparer.h @@ -0,0 +1,28 @@ +#ifndef _SYSTEM_COLLECTIONS_GENERIC_EQUALITYCOMPARER_ +#define _SYSTEM_COLLECTIONS_GENERIC_EQUALITYCOMPARER_ + +namespace System +{ + namespace Collections + { + namespace Generic + { + template + class EqualityComparer : IEqualityComparer + { + private: + static EqualityComparer defaultComparer; + + public: + static EqualityComparer Default(); + + + + bool Equals(T x, T y); + int GetHashCode(T obj); + }; + } + } +} + +#endif //_SYSTEM_COLLECTIONS_GENERIC_EQUALITYCOMPARER_ diff --git a/include/System/Collections/Generic/Interfaces.h b/include/System/Collections/Generic/Interfaces.h new file mode 100644 index 0000000..8ee5a9b --- /dev/null +++ b/include/System/Collections/Generic/Interfaces.h @@ -0,0 +1,111 @@ +/******************************************************** + * Interfaces.h * + * * + * XFX Generic Interfaces definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_COLLECTIONS_GENERIC_INTERFACES_ +#define _SYSTEM_COLLECTIONS_GENERIC_INTERFACES_ + +#include + +namespace System +{ + namespace Collections + { + namespace Generic + { + /// + /// Defines methods to manipulate generic collections. + /// + template + interface ICollection + { + public: + virtual void Add(T item)=0; + virtual void Clear()=0; + virtual bool Contains(T item)=0; + virtual void CopyTo(T array[], int arrayIndex)=0; + virtual bool Remove(T item)=0; + + virtual int Count()=0; + virtual bool IsReadOnly(); + }; + + /// + /// Defines a method that a type implements to compare two objects. + /// + template + interface IComparer + { + public: + virtual int Compare(T x, T y)=0; + }; + + /// + /// Represents a generic collection of key/value pairs. + /// + template + interface IDictionary + { + public: + virtual void Add(TKey key, TValue value)=0; + virtual bool ContainsKey(TKey key)=0; + virtual bool Remove(TKey key)=0; + virtual bool TryGetValue(TKey key, out TValue value)=0; + + virtual ICollection Keys()=0; + virtual ICollection Values()=0; + }; + + /// + /// Supports a simple iteration over a generic collection. + /// + template + interface IEnumerator + { + public: + virtual T Current()=0; + }; + + /// + /// Exposes the enumerator, which supports a simple iteration over a collection of a specified type. + /// + template + interface IEnumerable + { + public: + virtual IEnumerator GetEnumerator()=0; + }; + + /// + /// Defines methods to support the comparison of objects for equality. + /// + template + interface IEqualityComparer + { + public: + virtual bool Equals(T x, T y); + virtual int GetHashCode(T obj); + }; + + /// + /// Represents a collection of objects that can be individually accessed by index. + /// + template + interface IList : public ICollection + { + public: + virtual int IndexOf(T item)=0; + virtual void Insert(int index, T item)=0; + virtual void RemoveAt(int index)=0; + + virtual T operator[](int index)=0; + + virtual ~IList(); + }; + } + } +} + +#endif //_SYSTEM_COLLECTIONS_GENERIC_INTERFACES_ diff --git a/include/System/Collections/Generic/KeyNotFoundException.h b/include/System/Collections/Generic/KeyNotFoundException.h new file mode 100644 index 0000000..77737b7 --- /dev/null +++ b/include/System/Collections/Generic/KeyNotFoundException.h @@ -0,0 +1,33 @@ +/******************************************************** + * KeyNotFoundException.h * + * * + * XFX KeyNotFoundException class definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_COLLECTIONS_GENERIC_KEYNOTFOUNDEXCEPTION_ +#define _SYSTEM_COLLECTIONS_GENERIC_KEYNOTFOUNDEXCEPTION_ + +#include + +namespace System +{ + namespace Collections + { + namespace Generic + { + /// + /// The exception that is thrown when the key specified for accessing an element in a collection does not match any + /// key in the collection. + /// + class KeyNotFoundException : public SystemException + { + public: + KeyNotFoundException(); + KeyNotFoundException(char* message); + KeyNotFoundException(char* message, Exception innerException); + }; + } + } +} + +#endif //_SYSTEM_COLLECTIONS_GENERIC_KEYNOTFOUNDEXCEPTION_ diff --git a/include/System/Collections/Generic/KeyValuePair.h b/include/System/Collections/Generic/KeyValuePair.h new file mode 100644 index 0000000..ded6133 --- /dev/null +++ b/include/System/Collections/Generic/KeyValuePair.h @@ -0,0 +1,37 @@ +/******************************************************** + * KeyValuePair.h * + * * + * XFX KeyValuePair definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_COLLECTIONS_GENERIC_KEYVALUEPAIR_ +#define _SYSTEM_COLLECTIONS_GENERIC_KEYVALUEPAIR_ + +namespace System +{ + namespace Collections + { + namespace Generic + { + /// + /// Defines a key/value pair that can be set or retrieved. + /// + template + struct KeyValuePair + { + private: + TKey _key; + TValue _value; + + public: + TKey Key(); + TValue Value(); + + KeyValuePair(TKey key, TValue value); + KeyValuePair(const KeyValuePair &obj); //! Copy constructor + }; + } + } +} + +#endif //_SYSTEM_COLLECTIONS_GENERIC_KEYVALUEPAIR_ diff --git a/include/System/Collections/Generic/List.h b/include/System/Collections/Generic/List.h new file mode 100644 index 0000000..9a8edeb --- /dev/null +++ b/include/System/Collections/Generic/List.h @@ -0,0 +1,72 @@ +/******************************************************** + * List.h * + * * + * XFX Generic List definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_COLLECTIONS_GENERIC_LIST_ +#define _SYSTEM_COLLECTIONS_GENERIC_LIST_ + +#include +#include "Interfaces.h" + +namespace System +{ + namespace Collections + { + namespace Generic + { + /// + /// Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists. + /// + template + class List : public IList + { + private: + static const int _defaultCapacity = 4; + static T _emptyArray[]; + T _items[]; + int _size; + int _version; + + void EnsureCapacity(int min); + + public: + int Count(); + int Capacity(); // get + void Capacity(int newCap); // set + + List(); + List(int capacity); + ~List(); + + void Add(T item); //Adds an element to the end of the list + int BinarySearch(T item); + int BinarySearch(T item, IComparer comparer); + int BinarySearch(int index, int count, T item, IComparer comparer); + void Clear(); //Removes all elements from the list + bool Contains(T item); + void CopyTo(T array[], int arrayIndex); + int First(); //Goes to the first element in the list + int First(out T item); //Goes to the first element returns the value + void ForEach(char* action); //Executes the specified action on each element in the list + int IndexOf(T item); + void Insert(int index, T item); + int Next(); //Goes to next element in the list + int Next(out T item); //Goes to next element and writes the element in parameter + int Change(const T newElem); //changes the current element + bool Remove(T item); //Removes current element + void RemoveAt(int index); + void RemoveRange(int index, int count); + void Reverse(); + void Reverse(int index, int count); + T *ToArray(); + void TrimExcess(); + + T operator[](int index); + }; + } + } +} + +#endif //_SYSTEM_COLLECTIONS_GENERIC_LIST_ diff --git a/include/System/Collections/IList.h b/include/System/Collections/IList.h new file mode 100644 index 0000000..23ec368 --- /dev/null +++ b/include/System/Collections/IList.h @@ -0,0 +1,24 @@ +#ifndef _ILIST_ +#define _ILIST_ + +#include "../System.h" + +using namespace System; + +namespace System +{ + namespace Collections + { + interface IList : virtual ICollection, virtual IEnumerable + { + public: + virtual int IsFixedSize(); + virtual int IsReadOnly(); + + virtual void Clear(); + virtual void RemoveAt(); + }; + } +} + +#endif //_ILIST_ diff --git a/include/System/Collections/Interfaces.h b/include/System/Collections/Interfaces.h new file mode 100644 index 0000000..0490fe3 --- /dev/null +++ b/include/System/Collections/Interfaces.h @@ -0,0 +1,12 @@ +#ifndef _SYSTEM_COLLECTIONS_INTERFACES_ +#define _SYSTEM_COLLECTIONS_INTERFACES_ + +namespace System +{ + namespace Collections + { + + } +} + +#endif //_SYSTEM_COLLECTIONS_INTERFACES_ diff --git a/include/System/DateTime.h b/include/System/DateTime.h new file mode 100644 index 0000000..37b8d29 --- /dev/null +++ b/include/System/DateTime.h @@ -0,0 +1,130 @@ +/******************************************************** + * DateTime.h * + * * + * XFX DateTime definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _DATETIME_ +#define _DATETIME_ + +#include "Globalization/Calendar.h" +#include "Globalization/Enums.h" +#include "Enums.h" +#include "Interfaces.h" +#include "Types.h" + +namespace System +{ + class String; + class TimeSpan; + + /// + /// Represents an instant in time, typically expressed as a date and time of day. + /// + class DateTime + { + private: + static const Int64 TicksMask; + static const Int64 KindMask; + static const int KindShift; + static const Int64 w32file_epoch; + static const Int64 MAX_VALUE_TICKS; + static const Int64 UnixEpoch; + Int64 encoded; + int AbsoluteDays(int year, int month, int day); + void InvalidTickValue(Int64 ticks); + DateTime Add(double value, int scale); + + public: + DateTime Date(); + int Day(); + DayOfWeek_t DayOfWeek(); + int DayOfYear(); + int Hour(); + DateTimeKind_t Kind(); + int Millisecond(); + int Minute(); + int Month(); + static DateTime Now(); + int Second(); + Int64 Ticks(); + TimeSpan TimeOfDay(); + static DateTime Today(); + static DateTime UtcNow(); + int Year(); + static const DateTime MaxValue; + static const DateTime MinValue; + + DateTime(int year, int month, int day); + DateTime(int year, int month, int day, System::Globalization::Calendar calendar); + DateTime(int year, int month, int day, int hour, int minute, int second); + DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind_t kind); + DateTime(int year, int month, int day, int hour, int minute, int second, System::Globalization::Calendar calendar); + DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond); + DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind_t kind); + DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, System::Globalization::Calendar calendar); + DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, System::Globalization::Calendar calendar, DateTimeKind_t kind); + DateTime(Int64 ticks); + DateTime(Int64 ticks, DateTimeKind_t kind); + DateTime(const DateTime &obj); //Copy constructor + + DateTime Add(TimeSpan value); + DateTime AddDays(double value); + DateTime AddHours(double value); + DateTime AddMilliseconds(double value); + DateTime AddMinutes(double value); + DateTime AddMonths(int months); + DateTime AddSeconds(double value); + DateTime AddTicks(Int64 value); + DateTime AddYears(int value); + static int Compare(DateTime t1, DateTime t2); + int CompareTo(DateTime value); + static int DaysInMonth(int year, int month); + bool Equals(DateTime obj); + bool static Equals(DateTime t1, DateTime t2); + static DateTime FromFileTime(Int64 fileTime); + static DateTime FromFileTimeUtc(Int64 fileTime); + static DateTime FromOADate(double d); + String *GetDateTimeFormats(); + String *GetDateTimeFormats(char format); + String *GetDateTimeFormats(char format, IFormatProvider &formatProvider); + String *GetDateTimeFormats(IFormatProvider &formatProvider); + int GetHashCode(); + bool IsDaylighSavingTime(); + static bool IsLeapYear(int year); + static DateTime Parse(String s); + static DateTime Parse(String s, IFormatProvider &formatProvider); + static DateTime Parse(String s, IFormatProvider &formatProvider, System::Globalization::DateTimeStyles_t styles); + static DateTime ParseExact(String s, String format, IFormatProvider &formatProvider); + static DateTime ParseExact(String s, String format, IFormatProvider &formatProvider, System::Globalization::DateTimeStyles_t style); + static DateTime ParseExact(String s, String formats[], IFormatProvider &formatProvider, System::Globalization::DateTimeStyles_t style); + static DateTime ParseExact(DateTime value, DateTimeKind kind); + TimeSpan Subtract(DateTime value); + DateTime Subtract(TimeSpan value); + Int64 ToFileTime(); + Int64 ToFileTimeUtc(); + DateTime ToLocalTime(); + String ToLongDateString(); + String ToLongTimeString(); + double ToOADate(); + String ToShortDateString(); + String ToShortTimeString(); + String ToString(); + String ToString(IFormatProvider &provider); + String ToString(String format); + String ToString(String format, IFormatProvider &provider); + DateTime ToUniversalTime(); + + DateTime operator +(const TimeSpan other); + bool operator==(const DateTime other); + bool operator >(const DateTime other); + bool operator>=(const DateTime other); + bool operator!=(const DateTime other); + bool operator <(const DateTime other); + bool operator<=(const DateTime other); + TimeSpan operator-(const DateTime other); + DateTime operator-(const TimeSpan t); + }; +} + +#endif //_DATETIME_ diff --git a/include/System/Delegates.h b/include/System/Delegates.h new file mode 100644 index 0000000..b1b11e6 --- /dev/null +++ b/include/System/Delegates.h @@ -0,0 +1,26 @@ +/******************************************************** + * Delegates.h * + * * + * Defines delegates within the System namespace * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_DELEGATES_ +#define _SYSTEM_DELEGATES_ + +#include "EventArgs.h" +#include "Interfaces.h" + +namespace System +{ + /// + /// References a method to be called when a corresponding asynchronous operation completes. + /// + typedef void *(ASyncCallback)(IAsyncResult ar); + + /// + /// Represents the method that will handle an event that has no event data. + /// + typedef void *(EventHandler)(void* sender, EventArgs e); +} + +#endif diff --git a/include/System/Enums.h b/include/System/Enums.h new file mode 100644 index 0000000..b74ad24 --- /dev/null +++ b/include/System/Enums.h @@ -0,0 +1,95 @@ +/**************************************************************** + * Enums.h * + * Defines enumerations used in the System namespace * + * * + * Enumerations are defined inside structs to prevent * + * namespace pollution, and easier distinction. * + ****************************************************************/ +#ifndef _SYSTEM_ENUMS_ +#define _SYSTEM_ENUMS_ + +namespace System +{ + /// + /// Specifies whether a System::DateTime object represents a local time, a Coordinated Universal Time (UTC), or is + /// not specified as either local time or UTC. + /// + struct DateTimeKind + { + enum type + { + Local = 2, + Unspecified = 0, + Utc = 1 + }; + }; + + /// + /// Specifies the day of the week. + /// + struct DayOfWeek + { + enum type + { + Friday = 5, + Monday = 1, + Saturday = 6, + Sunday = 0, + Thursday = 4, + Tuesday = 2, + Wednesday = 3 + }; + }; + /// + /// Identifies the operating system, or platform, supported by an assembly. + /// + struct PlatformID + { + enum type + { + MacOSX = 6, + Unix = 4, + Win32S = 0, + Win32Windows = 1, + WinCE = 3, + Xbox = 5 + }; + }; + + /// + /// Specifies the culture, case, and sort rules to be used by certain overloads + /// of the String::Compare(String,String) and String::Equals(System.Object) methods. + /// + struct StringComparison + { + enum type + { + CurrentCulture, + CurrentCultureIgnoreCase, + InvariantCulture, + InvariantCultureIgnoreCase, + Ordinal, + OrdinalIgnoreCase + }; + }; + + /// + /// Specifies whether applicable Overload:String::Split method overloads include or omit empty substrings from the return value. + /// + struct StringSplitOptions + { + enum type + { + None, + RemoveEmptyEntries + }; + }; + + typedef DateTimeKind::type DateTimeKind_t; + typedef DayOfWeek::type DayOfWeek_t; + typedef PlatformID::type PlatformID_t; + typedef StringComparison::type StringComparison_t; + typedef StringSplitOptions::type StringSplitOptions_t; +} + +#endif //_SYSTEM_ENUMS_ diff --git a/include/System/Environment.h b/include/System/Environment.h new file mode 100644 index 0000000..c1c72b3 --- /dev/null +++ b/include/System/Environment.h @@ -0,0 +1,41 @@ + +#ifndef _ENVIRONMENT_ +#define _ENVIRONMENT_ + +namespace System +{ + class OperatingSystem; + class String; + class Version; + + class Environment + { + /// + /// Specifies enumerated constants used to retrieve directory paths to system special folders. + /// + struct SpecialFolder + { + enum type + { + ApplicationData = 26, + Favorites = 22, + Personal = 5, + Programs = 2, + StartMenu = 11, + Startup = 7 + }; + }; + + typedef SpecialFolder::type SpecialFolder_t; + + public: + static char* GetFolderPath(SpecialFolder_t folder); + static char* NewLine(); + static OperatingSystem OSVersion(); + static int ProcessorCount(); + static int TickCount(); + static Version Version_(); + }; +} + +#endif //_ENVIRONMENT_ diff --git a/include/System/EventArgs.h b/include/System/EventArgs.h new file mode 100644 index 0000000..653e353 --- /dev/null +++ b/include/System/EventArgs.h @@ -0,0 +1,26 @@ +/******************************************************** + * EventArgs.h * + * * + * XFX EventArgs class definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_EVENTARGS_ +#define _SYSTEM_EVENTARGS_ + +#include "Object.h" + +namespace System +{ + /// + /// EventArgs is the base class for classes containing event data. + /// + class EventArgs : public Object + { + public: + static const EventArgs Empty; + + EventArgs(); + }; +} + +#endif //_SYSTEM_EVENTARGS_ diff --git a/include/System/Exception.h b/include/System/Exception.h new file mode 100644 index 0000000..3170a75 --- /dev/null +++ b/include/System/Exception.h @@ -0,0 +1,239 @@ +/******************************************************** + * Exception.h * + * * + * XFX Exception definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_EXCEPTION_ +#define _SYSTEM_EXCEPTION_ + +namespace System +{ + /// + /// Represents errors that occur during application execution. + /// + class Exception + { + private: + Exception *_innerException; + + protected: + char* _message; + + public: + Exception InnerException(); + virtual char* Message(); + + Exception(); + Exception(char* message); + virtual ~Exception(); + + virtual Exception GetBaseException(); + }; + + /// + /// The exception that is thrown when a non-fatal application error occurs. + /// + class ApplicationException : public Exception + { + public: + ApplicationException(); + ApplicationException(char* message); + ~ApplicationException(); + }; + + /// + /// The exception that is thrown for errors in an arithmetic, casting, or conversion operation. + /// + class ArithmeticException : public Exception + { + public: + ArithmeticException(); + ArithmeticException(char* message); + ~ArithmeticException(); + }; + + /// + /// The exception that is thrown when there is an attempt to divide an integral or decimal value by zero. + /// + class DivideByZeroException : public ArithmeticException + { + public: + DivideByZeroException(); + DivideByZeroException(char* message); + ~DivideByZeroException(); + }; + + /// + /// Defines the base class for predefined exceptions in the System namespace. + /// + class SystemException : public Exception + { + public: + SystemException(); + SystemException(char* message); + SystemException(char* message, Exception innerException); + }; + + /// + /// The exception that is thrown when there is an attempt to read or write protected memory. + /// + class AccessViolationException : public SystemException + { + public: + AccessViolationException(); + AccessViolationException(char* message); + AccessViolationException(char* message, Exception innerException); + }; + + /// + /// The exception that is thrown when an attempt is made to access an unloaded application domain. + /// + class AppDomainUnloadedException : public SystemException + { + public: + AppDomainUnloadedException(); + AppDomainUnloadedException(char* message); + }; + + /// + /// The exception that is thrown when one of the arguments provided to a method is not valid. + /// + class ArgumentException : public SystemException + { + protected: + char* _paramName; + + public: + char* Message(); + virtual char* ParamName(); + + ArgumentException(); + ArgumentException(char* message); + ArgumentException(char* message, char* paramName); + }; + + /// + /// The exception that is thrown when a null reference is passed to a method that does not accept it as a + /// valid argument. + /// + class ArgumentNullException : public ArgumentException + { + public: + ArgumentNullException(); + ArgumentNullException(char* paramName); + ArgumentNullException(char* paramName, char* message); + }; + + /// + /// The exception that is thrown when the value of an argument is outside the allowable range of values as + /// defined by the invoked method. + /// + class ArgumentOutOfRangeException : public ArgumentException + { + public: + ArgumentOutOfRangeException(); + ArgumentOutOfRangeException(char* paramName); + ArgumentOutOfRangeException(char* paramName, void* object, char* message); + ArgumentOutOfRangeException(char* paramName, char* message); + + virtual void *ActualValue(); + char* Message(); + }; + + /// + /// The base exception type for all COM interop exceptions and structured exception handling (SEH) exceptions. + /// + class ExternalException : public SystemException + { + public: + ExternalException(); + ExternalException(char* message); + ExternalException(char* message, Exception inner); + }; + + /// + /// The exception that is thrown when an attempt is made to access an element of an array with an index that is + /// outside the bounds of the array. This class cannot be inherited. + /// + class IndexOutOfRangeException : public SystemException + { + public: + IndexOutOfRangeException(); + IndexOutOfRangeException(char* message); + }; + + /// + /// The exception that is thrown when a method call is invalid for the object's current state. + /// + class InvalidOperationException : public SystemException + { + public: + InvalidOperationException(); + InvalidOperationException(char* message); + InvalidOperationException(char* message, Exception inner); + }; + + /// + /// The exception that is thrown when a requested method or operation is not implemented. + /// + class NotImplementedException : public SystemException + { + public: + NotImplementedException(); + NotImplementedException(char* message); + NotImplementedException(char* message, Exception innerException); + }; + + /// + /// The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, + /// seek, or write to a stream that does not support the invoked functionality. + /// + class NotSupportedException : public SystemException + { + public: + NotSupportedException(); + NotSupportedException(char* message); + NotSupportedException(char* message, Exception innerException); + }; + + /// + /// The exception that is thrown when the operating system denies access because of an I/O error or a specific + /// type of security error. + /// + class UnauthorizedAccessException : public SystemException + { + public: + UnauthorizedAccessException(); + UnauthorizedAccessException(char* message); + UnauthorizedAccessException(char* message, Exception inner); + }; + + /// + /// The exception that is thrown when an operation is performed on a disposed object. + /// + class ObjectDisposedException : public InvalidOperationException + { + private: + char* _objectName; + + public: + char* ObjectName(); + + ObjectDisposedException(char* objectName); + ObjectDisposedException(char* objectName, char* message); + }; + + /// + /// The exception that is thrown when an arithmetic, casting, or conversion operation in a checked context results in an overflow. + /// + class OverflowException : public ArithmeticException + { + public: + OverflowException(); + OverflowException(char* message); + OverflowException(char* message, Exception innerException); + }; +} + +#endif //_SYSTEM_EXCEPTION_ diff --git a/include/System/Globalization/Calendar.h b/include/System/Globalization/Calendar.h new file mode 100644 index 0000000..497082e --- /dev/null +++ b/include/System/Globalization/Calendar.h @@ -0,0 +1,27 @@ +#ifndef _SYSTEM_GLOBALIZATION_CALENDAR_ +#define _SYSTEM_GLOBALIZATION_CALENDAR_ + + + +namespace System +{ + class DateTime; + + namespace Globalization + { + /// + /// Represents time in divisions, such as weeks, months, and years. + /// + class Calendar + { + public: + DateTime AddDays(DateTime time, int days); + DateTime AddHours(DateTime time, int hours); + DateTime AddMilliseconds(DateTime time, double milliseconds); + DateTime AddMinutes(DateTime time, int minutes); + DateTime AddMonths(DateTime time, int months); + }; + } +} + +#endif //_SYSTEM_GLOBALIZATION_CALENDAR_ diff --git a/include/System/Globalization/CultureInfo.h b/include/System/Globalization/CultureInfo.h new file mode 100644 index 0000000..757abf8 --- /dev/null +++ b/include/System/Globalization/CultureInfo.h @@ -0,0 +1,17 @@ +#ifndef CULTUREINFO_H_ +#define CULTUREINFO_H_ + +namespace System +{ + namespace Globalization + { + class CultureInfo + { + public: + void ClearCacheData(); + + }; + } +} + +#endif //CULTUREINFO_H_ diff --git a/include/System/Globalization/DaylightTime.h b/include/System/Globalization/DaylightTime.h new file mode 100644 index 0000000..71d7b84 --- /dev/null +++ b/include/System/Globalization/DaylightTime.h @@ -0,0 +1,31 @@ +#ifndef _DAYLIGHTTIME_ +#define _DAYLIGHTTIME_ + +#include +#include + +namespace System +{ + namespace Globalization + { + /// + /// Defines the period of daylight saving time. + /// + class DaylightTime + { + private: + DateTime _start; + DateTime _end; + TimeSpan _delta; + + public: + TimeSpan Delta(); + DateTime End(); + DateTime Start(); + + DaylightTime(DateTime start, DateTime end, DateTime delta); + }; + } +} + +#endif //_DAYLIGHTTIME_ diff --git a/include/System/Globalization/Enums.h b/include/System/Globalization/Enums.h new file mode 100644 index 0000000..b586755 --- /dev/null +++ b/include/System/Globalization/Enums.h @@ -0,0 +1,124 @@ +#ifndef _SYSTEM_GLOBALIZATION_ENUMS_ +#define _SYSTEM_GLOBALIZATION_ENUMS_ + +namespace System +{ + namespace Globalization + { + /// + /// Defines different rules for determining the first week of the year. + /// + struct CalendarWeekRule + { + enum type + { + FirstDay = 0, + FirstFourDayWeek = 2, + FirstFullWeek = 1 + }; + }; + /// + /// Defines the string comparison options to use with System.Globalization.CompareInfo. + /// + struct CompareOptions + { + enum type + { + IgnoreCase = 1, + IgnoreKanaType = 8, + IgnoreNonSpace = 2, + IgnoreSymbols = 4, + IgnoreWidth = 16, + None = 0, + Ordinal = 1073741824, + OrdinalIgnoreCase = 268435456, + StringSort = 536870912 + }; + }; + /// + /// Defines the types of culture lists that can be retrieved using System::Globalization::CultureInfo::GetCultures + /// (System.Globalization.CultureTypes). + /// + struct CultureTypes + { + enum type + { + AllCultures = 7, + InstalledWin32Cultures = 4, + NeutralCultures = 1, + SpecificCulture = 2 + }; + }; + /// + /// Defines the formatting options that customize string parsing for the System::DateTime::Parse and + /// System::DateTime::ParseExact methods. + /// + struct DateTimeStyles + { + enum type + { + AdjustToUniversal = 16, + AllowInnerWhite = 4, + AllowLeadingWhite = 1, + AllowTrailingWhite = 2, + AllowWhiteSpaces = 7, + AssumeLocal = 32, + AssumeUniversal = 64, + NoCurrentDateDefault = 8, + None = 0, + RoundtripKind = 128 + }; + }; + /// + /// Defines the different language versions of the Gregorian calendar. + /// + struct GregorianCalenderTypes + { + enum type + { + Arabic = 10, + Localized = 1, + MiddleEastFrench = 9, + TransliteratedEnglish = 11, + TransliteratedFrench = 12, + USEnglish = 2 + }; + }; + /// + /// Determines the styles permitted in numeric string arguments that are passed to the Parse methods of the + /// numeric base type classes. + /// + struct NumberStyles + { + enum type + { + AllowCurrencySymbol = 256, + AllowDecimalPoint = 32, + AllowExponent = 128, + AllowHexSpecifier = 512, + AllowLeadingSign = 4, + AllowLeadingWhite = 1, + AllowParentheses = 16, + AllowThousands = 64, + AllowTrailingSign = 8, + AllowTrailingWhite = 2, + Any = 511, + Currency = 383, + Float = 167, + HexNumber = 515, + Integer = 7, + None = 0, + Number = 111 + }; + }; + + typedef CalendarWeekRule::type CalendarWeekRule_t; + typedef CompareOptions::type CompareOptions_t; + typedef CultureTypes::type CultureTypes_t; + typedef DateTimeStyles::type DateTimeStyles_t; + typedef GregorianCalenderTypes::type GregorianCalenderTypes_t; + typedef NumberStyles::type NumberStyles_t; + } +} + +#endif //_SYSTEM_GLOBALIZATION_ENUMS_ diff --git a/include/System/IO/BinaryReader.h b/include/System/IO/BinaryReader.h new file mode 100644 index 0000000..f230918 --- /dev/null +++ b/include/System/IO/BinaryReader.h @@ -0,0 +1,61 @@ +#ifndef _IO_BINARYREADER_ +#define _IO_BINARYREADER_ + +#include "../Types.h" +#include "../Interfaces.h" +#include "../Text/Encoding.h" +#include "Stream.h" + +using namespace System::Text; + +namespace System +{ + namespace IO + { + /// + /// Reads primitive data types as binary values in a specific encoding. + /// + class BinaryReader : public IDisposable, public Object + { + private: + bool m_2BytesPerChar; + byte* m_buffer; + char* m_charBuffer; + byte* m_charBytes; + char* m_singleChar; + Stream m_stream; + Encoding m_encoding; + bool m_isMemoryStream; + Decoder m_decoder; + + //! 128 chars should cover most strings in one grab. + static const int MaxBufferSize = 128; + + bool m_disposed; + + int InternalReadChars(char buffer[], int index, int count); + int InternalReadOneChar(); + + protected: + virtual void Dispose(bool disposing); + virtual void FillBuffer(int numBytes); + + public: + virtual Stream BaseStream(); + + BinaryReader(Stream input); + BinaryReader(Stream input, Encoding encoding); + virtual ~BinaryReader(); + + virtual void Close(); + virtual void Dispose(); + virtual int PeekChar(); + virtual int Read(); + virtual int Read(byte buffer[], int index, int count); + virtual int Read(char buffer[], int index, int count); + virtual float ReadSingle(); + }; + } +} + +#endif //_IO_BINARYREADER_ diff --git a/include/System/IO/Directory.h b/include/System/IO/Directory.h new file mode 100644 index 0000000..e8c82b3 --- /dev/null +++ b/include/System/IO/Directory.h @@ -0,0 +1,51 @@ +/******************************************************** + * Directory.h * + * * + * XFX Directory class definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _IO_DIRECTORY_ +#define _IO_DIRECTORY_ + +#include "../Types.h" + +namespace System +{ + class DateTime; + + namespace IO + { + class DirectoryInfo; + + /// + /// Exposes static methods for creating, moving, and enumerating through directories and subdirectories. This + /// class cannot be inherited. + /// + class Directory + { + private: + Directory(); + + public: + static DirectoryInfo CreateDirectory(char* path); + static void Delete(char* path); + static void Delete(char* path, bool recursive); + static bool Exists(char* path); + static DateTime GetCreationTime(const char* path); + static char* GetCurrentDirectory(); + static char** GetDirectories(char* path); + static char** GetDirectories(char* path, char* searchPattern); + static char* GetDirectoryRoot(char* path); + static char** GetFiles(char* path); + static char** GetFiles(char* path, char* searchPattern); + static char** GetFileSystemEntries(char* path); + static char** GetFileSystemEntries(char* path, char* searchPattern); + static DateTime GetLastAccessTime(char* path); + static DateTime GetLastWriteTime(char* path); + static void Move(char* sourceDirName, char* destDirName); + static void SetCurrentDirectory(char* path); + }; + } +} + +#endif //_IO_DIRECTORY_ diff --git a/include/System/IO/DirectoryInfo.h b/include/System/IO/DirectoryInfo.h new file mode 100644 index 0000000..081350d --- /dev/null +++ b/include/System/IO/DirectoryInfo.h @@ -0,0 +1,45 @@ +#ifndef _IO_DIRECTORYINFO_ +#define _IO_DIRECTORYINFO_ + +#include "../Types.h" +#include "FileSystemInfo.h" + +namespace System +{ + namespace IO + { + /// + /// Exposes instance methods for creating, moving, and enumerating through directories and subdirectories. This + /// class cannot be inherited. + /// + class DirectoryInfo : public FileSystemInfo + { + private: + char* current; + char* parent; + + DirectoryInfo(); + + public: + bool Exists(); + char* Name(); + DirectoryInfo Parent(); + DirectoryInfo Root(); + + DirectoryInfo(const char* path, bool junk); + + void Create(); + DirectoryInfo CreateSubDirectory(const char* path); + void Delete(); + void Delete(bool recursive); + DirectoryInfo *GetDirectories(); + DirectoryInfo *GetDirectories(const char* searchPattern); + FileSystemInfo *GetFileSystemInfos(); + FileSystemInfo *GetFileSystemInfos(const char* searchPatter); + void MoveTo(const char* destDirName); + char* ToString(); + }; + } +} + +#endif //_IO_DIRECTORYINFO_ diff --git a/include/System/IO/Enums.h b/include/System/IO/Enums.h new file mode 100644 index 0000000..66f8e6f --- /dev/null +++ b/include/System/IO/Enums.h @@ -0,0 +1,97 @@ +#ifndef _SYSTEM_IO_ENUMS_ +#define _SYSTEM_IO_ENUMS_ + +namespace System +{ + namespace IO + { + /// + /// Defines constants for read, write, or read/write access to a file. + /// + struct FileAccess + { + enum type + { + Read = 1, + ReadWrite = 3, + Write = 2 + }; + }; + + /// + /// Provides attributes for files and directories. + /// + struct FileAttributes + { + enum type + { + Archive = 32, + Compressed = 2048, + Device = 64, + Directory = 16, + Encrypted = 16384, + Hidden = 2, + Normal = 128, + NotContentIndexed = 8192, + Offline = 4096, + ReadOnly = 1, + ReparsePoint = 1024, + SparseFile = 512, + System = 4, + Temporary = 256 + }; + }; + + /// + /// Specifies how the operating system should open a file. + /// + struct FileMode + { + enum type + { + Append = 6, + Create = 2, + CreateNew = 1, + Open = 3, + OpenOrCreate = 4, + Truncate = 5 + }; + }; + + /// + /// Contains constants for controlling the kind of access other System.IO.FileStream objects can have to the same + /// file. + /// + struct FileShare + { + enum type + { + None = 0, + Read = 1, + ReadWrite = 3, + Write = 2 + }; + }; + + /// + /// Provides the fields that represent reference points in streams for seeking. + /// + struct SeekOrigin + { + enum type + { + Begin, + Current, + End + }; + }; + + typedef FileAccess::type FileAccess_t; + typedef FileAttributes::type FileAttributes_t; + typedef FileMode::type FileMode_t; + typedef FileShare::type FileShare_t; + typedef SeekOrigin::type SeekOrigin_t; + } +} + +#endif //_SYSTEM_IO_ENUMS_ diff --git a/include/System/IO/FileStream.h b/include/System/IO/FileStream.h new file mode 100644 index 0000000..f8fcbf8 --- /dev/null +++ b/include/System/IO/FileStream.h @@ -0,0 +1,71 @@ +/******************************************************** + * FileStream.h * + * * + * XFX FileStream definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _FILESTREAM_ +#define _FILESTREAM_ + +#include "../Types.h" +#include "Enums.h" +#include "Stream.h" + +namespace System +{ + namespace IO + { + /// + /// Exposes a Stream around a file, supporting both synchronous and asynchronous read and write + /// operations. + /// + class FileStream : public Stream + { + private: + int handle; + byte* _buffer; + FileAccess_t _access; + bool canSeek; + bool isAsync; + Int64 _pos; + int _readLen; + int _readPos; + int _writePos; + static const int DefaultBufferSize = 8192; + + void FlushRead(); + void FlushWrite(bool calledFromFinalizer); + + protected: + void Dispose(bool disposing); + + public: + bool CanRead(); + bool CanSeek(); + bool CanWrite(); + virtual bool IsAsync(); + long long Length(); + char* Name(); + long long Position(); //get + void Position(long long newPosition); //set + + FileStream(); + FileStream(char* path, FileMode_t mode); + FileStream(char* path, FileMode_t mode, FileAccess_t access); + FileStream(char* path, FileMode_t mode, FileAccess_t access, FileShare_t share); + FileStream(char* path, FileMode_t mode, FileAccess_t access, FileShare_t share, int bufferSize); + FileStream(char* path, FileMode_t mode, FileAccess_t access, FileShare_t share, int bufferSize, bool useAsync); + virtual ~FileStream(); + + void Flush(); + int Read(byte array[], int offset, int count); + int ReadByte(); + long long Seek(long long offset, SeekOrigin_t origin); + void SetLength(long long value); + void Write(byte array[], int offset, int count); + void WriteByte(byte value); + }; + } +} + +#endif //_FILESTREAM_ diff --git a/include/System/IO/FileSystemInfo.h b/include/System/IO/FileSystemInfo.h new file mode 100644 index 0000000..66fda67 --- /dev/null +++ b/include/System/IO/FileSystemInfo.h @@ -0,0 +1,16 @@ +#ifndef _IO_FILESYSTEMINFO_ +#define _IO_FILESYSTEMINFO_ + +namespace System +{ + namespace IO + { + class FileSystemInfo + { + public: + virtual char* FullName(); + }; + } +} + +#endif //_IO_FILESYSTEMINFO_ diff --git a/include/System/IO/IOException.h b/include/System/IO/IOException.h new file mode 100644 index 0000000..65025d9 --- /dev/null +++ b/include/System/IO/IOException.h @@ -0,0 +1,68 @@ +/******************************************************** + * IOException.h * + * * + * XFX IOException definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_IO_IOEXCEPTION_ +#define _SYSTEM_IO_IOEXCEPTION_ + +#include "../Exception.h" + +namespace System +{ + namespace IO + { + /// + /// The exception that is thrown when an I/O error occurs. + /// + class IOException : public SystemException + { + public: + IOException(); + IOException(char* message); + }; + + /// + /// The exception that is thrown when part of a file or directory cannot be found. + /// + class DirectoryNotFoundException : public IOException + { + public: + DirectoryNotFoundException(); + DirectoryNotFoundException(char* message); + }; + + /// + /// The exception that is thrown when reading is attempted past the end of a stream. + /// + class EndOfStreamException : public IOException + { + public: + EndOfStreamException(); + EndOfStreamException(char* message); + }; + + /// + /// The exception that is thrown when an attempt to access a file that does not exist on disk fails. + /// + class FileNotFoundException : public IOException + { + public: + FileNotFoundException(); + FileNotFoundException(char* message); + }; + + /// + /// The exception that is thrown when a pathname or filename is longer than the system-defined maximum length. + /// + class PathTooLongException : public IOException + { + public: + PathTooLongException(); + PathTooLongException(char* message); + }; + } +} + +#endif //_SYSTEM_IO_IOEXCEPTION_ diff --git a/include/System/IO/MemoryStream.h b/include/System/IO/MemoryStream.h new file mode 100644 index 0000000..5b2e3c2 --- /dev/null +++ b/include/System/IO/MemoryStream.h @@ -0,0 +1,63 @@ +#ifndef _SYSTEM_IO_MEMORYSTREAM_ +#define _SYSTEM_IO_MEMORYSTREAM_ + +#include "../Types.h" +#include "Stream.h" + +namespace System +{ + namespace IO + { + /// + /// Creates a stream whose backing store is memory. + /// + class MemoryStream : public Stream + { + private: + byte* _buffer; + int _capacity; + bool _expandable; + bool _exposable; + bool _isOpen; + int _length; + int _origin; + int _position; + bool _writable; + static const int MemStreamMaxLength; + + bool EnsureCapacity(int value); + + protected: + void Dispose(bool disposing); + + public: + bool CanRead(); + bool CanSeek(); + bool CanWrite(); + virtual int Capacity(); + virtual void Capacity(int value); + Int64 Length(); + Int64 Position; + + MemoryStream(); + MemoryStream(int capacity); + MemoryStream(byte buffer[]); + MemoryStream(byte buffer[], bool writable); + MemoryStream(byte buffer[], int index, int count); + MemoryStream(byte buffer[], int index, int count, bool writable); + MemoryStream(byte buffer[], int index, int count, bool writable, bool publiclyVisible); + void Flush(); + virtual byte* GetBuffer(); + int Read(byte buffer[], int offset, int count); + int ReadByte(); + Int64 Seek(Int64 offset, SeekOrigin_t loc); + void SetLength(Int64 value); + virtual byte* ToArray(); + void Write(byte buffer[], int offset, int count); + void WriteByte(byte value); + virtual void WriteTo(Stream stream); + }; + } +} + +#endif //_SYSTEM_IO_MEMORYSTREAM_ diff --git a/include/System/IO/Path.h b/include/System/IO/Path.h new file mode 100644 index 0000000..e9a569c --- /dev/null +++ b/include/System/IO/Path.h @@ -0,0 +1,55 @@ +/******************************************************** + * Path.h * + * * + * XFX Path definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _PATH_ +#define _PATH_ + +#include + +namespace System +{ + namespace IO + { + /// + /// Performs operations on char* instances that contain file or directory path information. These + /// operations are performed in a cross-platform manner. + /// + class Path + { + private: + static bool dirEqualsVolume; + + Path(); + + static void GetDrive(const char* szPartition, out char* cDriveLetter); + + public: + static const char AltDirectorySeparatorChar; + static const char DirectorySeparatorChar; + static const char* InvalidPathChars; + static const char PathSeparator; + static const char VolumeSeparatorChar; + + static char* ChangeExtension(char* path, char* extension); + static char* Combine(char* path1, char* path2); + static char* GetDirectoryName(char* path); + static char* GetExtension(char* path); + static char* GetFileName(char* path); + static char* GetFileNameWithoutExtension(char* path); + static char* GetFullPath(char* path); + static char *GetInvalidFileNameChars(); + static char *GetInvalidPathChars(); + static char* GetPathRoot(char* path); + static char* GetRandomFileName(); + static char* GetTempFileName(); + static char* GetTempPath(); + static bool HasExtension(char* path); + static bool IsPathRooted(char* path); + }; + } +} + +#endif //_PATH_ diff --git a/include/System/IO/Stream.h b/include/System/IO/Stream.h new file mode 100644 index 0000000..5048bec --- /dev/null +++ b/include/System/IO/Stream.h @@ -0,0 +1,63 @@ +/******************************************************** + * Stream.h * + * * + * XFX Stream definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_IO_STREAM_ +#define _SYSTEM_IO_STREAM_ + +#include "../Types.h" +#include "Enums.h" +#include "../Delegates.h" +#include "../Interfaces.h" + +namespace System +{ + class WaitHandle; + + namespace IO + { + /// + /// Provides a generic view of a sequence of bytes. + /// + class Stream : public IDisposable + { + private: + int _asyncActiveCount; + + protected: + virtual WaitHandle CreateWaitHandle(); + virtual void Dispose(bool disposing); + + public: + Stream(); + + virtual bool CanRead(); + virtual bool CanSeek(); + virtual bool CanTimeOut(); + virtual bool CanWrite(); + virtual Int64 Length(); + Int64 Position; + int ReadTimeOut; + int WriteTimeOut; + static const Stream Null; + + virtual IAsyncResult BeginRead(byte buffer[], int offset, int count, ASyncCallback callback, void* state); + virtual IAsyncResult BeginWrite(byte buffer[], int offset, int count, ASyncCallback callback, void* state); + virtual void Close(); + void Dispose(); + virtual int EndRead(IAsyncResult asyncResult); + virtual void EndWrite(IAsyncResult asyncResult); + virtual void Flush(); + virtual int Read(byte buffer[], int offset, int count); + virtual int ReadByte(); + virtual Int64 Seek(Int64 offset, SeekOrigin_t origin); + virtual void SetLength(Int64 value); + virtual void Write(byte buffer[], int offset, int count); + virtual void WriteByte(byte value); + }; + } +} + +#endif //_SYSTEM_IO_STREAM_ diff --git a/include/System/IO/StreamAsyncResult.h b/include/System/IO/StreamAsyncResult.h new file mode 100644 index 0000000..7966c12 --- /dev/null +++ b/include/System/IO/StreamAsyncResult.h @@ -0,0 +1,45 @@ +/******************************************************** + * StreamAsyncResult.h * + * * + * XFX StreamAsyncResult definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_IO_STREAMASYNCRESULT_ +#define _SYSTEM_IO_STREAMASYNCRESULT_ + +#include "../Exception.h" +#include "../Interfaces.h" +#include "../Types.h" +#include "../Threading/WaitHandle.h" + +namespace System +{ + namespace IO + { + class StreamAsyncResult : public IAsyncResult + { + void* _state; + bool completed; + bool done; + Exception* exc; + int _nbytes; + + public: + void* AsyncState(); + Threading::WaitHandle AsyncWaitHandle(); + virtual bool CompletedSynchronously(); + bool IsCompleted(); + Exception* Exception_(); + int NBytes(); + bool Done; + + StreamAsyncResult(void* state); + StreamAsyncResult(const IAsyncResult &obj); + + void SetComplete(Exception* e); + void SetComplete(Exception* e, int nbytes); + }; + } +} + +#endif //_SYSTEM_IO_STREAMASYNCRESULT_ diff --git a/include/System/IO/StreamReader.h b/include/System/IO/StreamReader.h new file mode 100644 index 0000000..4feea8e --- /dev/null +++ b/include/System/IO/StreamReader.h @@ -0,0 +1,57 @@ +/******************************************************** + * StreamReader.h * + * * + * XFX StreamReader definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _STREAMREADER_ +#define _STREAMREADER_ + +#include "../Text/Encoding.h" +#include "TextReader.h" + +using namespace System::Text; + +namespace System +{ + namespace IO + { + class Stream; + + /// + /// Implements a System::IO::TextReader that reads characters from a byte stream in a particular encoding. + /// + class StreamReader : public TextReader + { + protected: + void Dispose(bool disposing); + + public: + static const StreamReader Null; + Stream BaseStream(); + Encoding CurrentEncoding(); + bool EndOfStream(); + + StreamReader(Stream stream); + StreamReader(Stream stream, bool detectEncodingFromByteOrderMarks); + StreamReader(Stream stream, Encoding encoding); + StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks); + StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize); + StreamReader(char* path); + StreamReader(char* path, bool detectEncodingFromByteOrderMarks); + StreamReader(char* path, Encoding encoding); + StreamReader(char* path, Encoding encoding, bool detectEncodingFromByteOrderMarks); + StreamReader(char* path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize); + + void Close(); + void DiscardBufferedData(); + int Peek(); + int Read(); + int Read(char buffer[], int index, int count); + char* ReadLine(); + char* ReadToEnd(); + }; + } +} + +#endif //_STREAMREADER_ diff --git a/include/System/IO/StreamWriter.h b/include/System/IO/StreamWriter.h new file mode 100644 index 0000000..b70c999 --- /dev/null +++ b/include/System/IO/StreamWriter.h @@ -0,0 +1,69 @@ +/******************************************************** + * StreamWriter.h * + * * + * XFX StreamWriter definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_IO_STREAMWRITER_ +#define _SYSTEM_IO_STREAMWRITER_ + +#include "../Text/Encoding.h" +#include "../Text/Encoder.h" +#include "Stream.h" +#include "TextWriter.h" +#include "../Types.h" + +using namespace System::Text; + +namespace System +{ + class String; + + namespace IO + { + /// + /// Implements a TextWriter for writing characters to a stream in a particular encoding. + /// + class StreamWriter : public TextWriter + { + private: + byte byteBuffer; + char charBuffer[]; + int charLen; + int charPos; + bool closable; + Encoder encoder; + Encoding encoding; + bool haveWrittenPreamble; + Stream stream; + + void Flush(bool flushStream, bool flushEncoder); + + protected: + void Dispose(bool disposing); + + public: + bool AutoFlush; + virtual Stream BaseStream(); + Encoding Encoding_(); + static const StreamWriter Null; + + StreamWriter(const char* path); + StreamWriter(const char* path, bool append); + StreamWriter(const char* path, bool append, Encoding encoding); + StreamWriter(const char* path, bool append, Encoding encoding, int bufferSize); + StreamWriter(Stream stream); + StreamWriter(Stream stream, Encoding encoding); + StreamWriter(Stream stream, Encoding encoding, int bufferSize); + + void Close(); + void Flush(); + void Write(char value); + void Write(char buffer[]); + void Write(char buffer[], int index, int count); + void Write(const char* value); + }; + } +} + +#endif //_SYSTEM_IO_STREAMWRITER_ diff --git a/include/System/IO/TextReader.h b/include/System/IO/TextReader.h new file mode 100644 index 0000000..8f23457 --- /dev/null +++ b/include/System/IO/TextReader.h @@ -0,0 +1,36 @@ +#ifndef _TEXTREADER_ +#define _TEXTREADER_ + +namespace System +{ + class String; + + namespace IO + { + /// + /// Represents a reader that can read a sequential series of characters. + /// + class TextReader + { + protected: + void Dispose(bool disposing); + + TextReader(); + + public: + static const TextReader Null; + + void Close(); + void Dispose(); + int Peek(); + int Read(); + int Read(char buffer[], int index, int count); + int ReadBlock(char buffer[], int index, int count); + String ReadLine(); + String ReadToEnd(); + TextReader Synchronized(TextReader &reader); + }; + } +} + +#endif //_TEXTREADER_ diff --git a/include/System/IO/TextWriter.h b/include/System/IO/TextWriter.h new file mode 100644 index 0000000..57e0a0f --- /dev/null +++ b/include/System/IO/TextWriter.h @@ -0,0 +1,66 @@ +/******************************************************** + * TextWriter.h * + * * + * XFX TextWriter definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_IO_TEXTWRITER_ +#define _SYSTEM_IO_TEXTWRITER_ + +#include "../Interfaces.h" +#include "../String.h" +#include "../Text/Encoding.h" + +namespace System +{ + namespace IO + { + /// + /// Represents a writer that can write a sequential series of characters. This class is abstract. + /// + class TextWriter : public IDisposable + { + protected: + char CoreNewLine[]; + + TextWriter(); + + virtual void Dispose(bool disposing); + + public: + System::Text::Encoding Encoding_(); + char* NewLine; + static const TextWriter Null; + + virtual void Close(); + void Dispose(); + virtual void Flush(); + TextWriter Synchronized(TextWriter writer); + virtual void Write(bool value); + virtual void Write(char value); + virtual void Write(char buffer[]); + virtual void Write(char buffer[], int index, int count); + virtual void Write(double value); + virtual void Write(float value); + virtual void Write(int value); + virtual void Write(long long value); + virtual void Write(const char* value); + virtual void Write(uint value); + virtual void Write(ulong value); + virtual void WriteLine(); + virtual void WriteLine(bool value); + virtual void WriteLine(char value); + virtual void WriteLine(char buffer[]); + virtual void WriteLine(char buffer[], int index, int count); + virtual void WriteLine(double value); + virtual void WriteLine(float value); + virtual void WriteLine(int value); + virtual void WriteLine(long long value); + virtual void WriteLine(const char* value); + virtual void WriteLine(uint value); + virtual void WriteLine(ulong value); + }; + } +} + +#endif //_SYSTEM_IO_TEXTWRITER_ diff --git a/include/System/IO/file.h b/include/System/IO/file.h new file mode 100644 index 0000000..fa2bd9e --- /dev/null +++ b/include/System/IO/file.h @@ -0,0 +1,63 @@ +/******************************************************** + * File.h * + * * + * XFX File definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _FILE_ +#define _FILE_ + +#include "Enums.h" + +#if ENABLE_XBOX +#include +#else +#endif + +namespace System +{ + class DateTime; + + namespace IO + { + class FileStream; + class StreamReader; + class StreamWriter; + + /// + /// Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the + /// creation of FileStream objects. + /// + class File + { + private: +#if ENABLE_XBOX + static int FileAttributeInfo(char* path, PXBOX_FIND_DATA data, bool tryagain, bool returnErrorOnNotFound); +#else + static int FileAttributeInfo(char* path, data, bool tryagain, bool returnErrorOnNotFound); +#endif + + public: + static StreamWriter AppendText(char* path); + static void Copy(char* sourceFileName, char* destFileName); + static void Copy(char* sourceFileName, char* destFileName, bool overwrite); + static FileStream Create(char* path); + static FileStream Create(char* path, int bufferSize); + static StreamWriter CreateText(char* path); + static void Delete(char* path); + static bool Exists(char* path); + static DateTime GetCreationTime(char* path); + static DateTime GetLastAccessTime(char* path); + static DateTime GetLastWriteTime(char* path); + static void Move(char* sourceFileName, char* destFileName); + static FileStream Open(char* path, FileMode_t mode); + static FileStream Open(char* path, FileMode_t mode, FileAccess_t access); + static FileStream Open(char* path, FileMode_t mode, FileAccess_t access, FileShare_t share); + static FileStream OpenRead(char* path); + static StreamReader OpenText(char* path); + static FileStream OpenWrite(char* path); + }; + } +} + +#endif //_FILE_ diff --git a/include/System/Interfaces.h b/include/System/Interfaces.h new file mode 100644 index 0000000..7ed18e2 --- /dev/null +++ b/include/System/Interfaces.h @@ -0,0 +1,71 @@ +#ifndef _SYSTEM_INTERFACES_ +#define _SYSTEM_INTERFACES_ + +#include "Types.h" +#include "Threading/WaitHandle.h" + +namespace System +{ + /// + /// Represents the status of an asynchronous operation. + /// + interface IAsyncResult + { + public: + virtual void *ASyncState(); + virtual Threading::WaitHandle AsyncWaitHandle(); + virtual bool CompletedSynchronously(); + virtual bool IsCompleted(); + }; + + /// + /// Defines a generalized comparison method that a value type or class implements to create a type-specific + /// comparison method for ordering instances. + /// + template + interface IComparable + { + public: + int CompareTo(T other)=0; + }; + + /// + /// Defines a method to release allocated resources. + /// + interface IDisposable + { + public: + virtual void Dispose()=0; + }; + + /// + /// Defines a generalized method that a value type or class implements to create + /// a type-specific method for determining equality of instances. + /// + template + interface IEquatable + { + public: + virtual bool Equals(const T other)=0; + }; + + /// + /// Provides a mechanism for retrieving an object to control formatting. + /// + interface IFormatProvider + { + public: + virtual void *GetProvider()=0; + }; + + /// + /// Provides a mechanism for retrieving an object to control formatting + /// + interface IServiceProvider + { + public: + virtual void* GetService(void* serviceType)=0; + }; +} + +#endif //_SYSTEM_INTERFACES_ diff --git a/include/System/Math.h b/include/System/Math.h new file mode 100644 index 0000000..fd8811a --- /dev/null +++ b/include/System/Math.h @@ -0,0 +1,87 @@ +/******************************************************** + * Math.h * + * * + * XFX Math definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _MATH_ +#define _MATH_ + +#include "Types.h" + +extern "C" { +#include +} + +//Define this here, because, strangely, g++ doesn't contain a FLT_MIN definition +#define FLT_MIN -3.402823e38 + +namespace System +{ + /// + /// Provides constants and static methods for trigonometric, logarithmic, and other common mathematical functions. + /// + class Math + { + private: + Math(); //! Private constructor to prevent instantiation + + public: + static const double E; + static const double PI; + + static double Abs(double value); + static float Abs(float value); + static int Abs(int value); + static long long Abs(long long value); + static sbyte Abs(sbyte value); + static short Abs(short value); + static double Acos(double value); + static double Asin(double value); + static double Atan(double value); + static double Atan2(double value1, double value2); + static double Ceiling(double value); + static double Cos(double value); + static double Cosh(double value); + static double Exp(double value); + static double Floor(double value); + static double IEEERemainder(double value1, double value2); + static double Log(double value); + static double Log10(double value); + static byte Max(byte value1, byte value2); + static double Max(double value1, double value2); + static float Max(float value1, float value2); + static int Max(int value1, int value2); + static long long Max(long long value1, long long value2); + static sbyte Max(sbyte value1, sbyte value2); + static short Max(short value1, short value2); + static uint Max(uint value1, uint value2); + static ulong Max(ulong value1, ulong value2); + static byte Min(byte value1, byte value2); + static double Min(double value1, double value2); + static float Min(float value1, float value2); + static int Min(int value1, int value2); + static long long Min(long long value1, long long value2); + static sbyte Min(sbyte value2, sbyte value2); + static short Min(short value1, short value2); + static uint Min(uint value1, uint value2); + static ulong Min(ulong value1, ulong value2); + static ushort Min(ushort value1, ushort value2); + static double Pow(double x, double y); + static double Round(double value); + static double Round(double value, int digits); + static int Sign(double value); + static int Sign(float value); + static int Sign(int value); + static int Sign(long long value); + static int Sign(sbyte value); + static int Sign(short value); + static double Sin(double value); + static double Sinh(double value); + static double Sqrt(double value); + static double Tan(double value); + static double Tanh(double value); + }; +} + +#endif //MATH_H diff --git a/include/System/Object.h b/include/System/Object.h new file mode 100644 index 0000000..5b95ac9 --- /dev/null +++ b/include/System/Object.h @@ -0,0 +1,28 @@ +/******************************************************** + * Object.h * + * * + * XFX Object definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_OBJECT_ +#define _SYSTEM_OBJECT_ + +namespace System +{ + /// + /// Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. + /// This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy. + /// + class Object + { + public: + virtual bool Equals(Object* obj); + static bool Equals(Object* objA, Object* objB); + virtual int GetHashCode(); + virtual char* ToString(); + }; + + typedef Object object; +} + +#endif //_SYSTEM_OBJECT_ diff --git a/include/System/OperatingSystem.h b/include/System/OperatingSystem.h new file mode 100644 index 0000000..9b550d7 --- /dev/null +++ b/include/System/OperatingSystem.h @@ -0,0 +1,36 @@ +/******************************************************** + * OperatingSystem.h * + * * + * XFX OperatingSystem definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _OPERATINGSYSTEM_ +#define _OPERATINGSYSTEM_ + +#include "Enums.h" + +namespace System +{ + class Version; + + /// + /// Represents information about an operating system, such as the version and platform identifier. This class + /// cannot be inherited. + /// + class OperatingSystem + { + private: + OperatingSystem(); + + public: + PlatformID Platform(); + Version Version_(); + + OperatingSystem(PlatformID platform, Version version); + + OperatingSystem Clone(); + String ToString(); + }; +} + +#endif //_OPERATINGSYSTEM_ diff --git a/include/System/Stack.h b/include/System/Stack.h new file mode 100644 index 0000000..5495910 --- /dev/null +++ b/include/System/Stack.h @@ -0,0 +1,43 @@ +#ifndef _STACK_ +#define _STACK_ + +#include "ICollection.h" +#include "IEnumerable.h" + +using namespace System; + +namespace System +{ + namespace Collections + { + namespace Generic + { + template + class Stack : virtual IEnumerable, virtual System::Collections::ICollection + { + private: + T internalArray[]; + + public: + struct Enumerator; + + Stack(); + Stack(IEnumerable collection); + Stack(int capacity); + + int Count(); + + void Clear(); + int Contains(T item); + void CopyTo(T array[], int arrayIndex); + T Peek(); + T Pop(); + void Push(T item); + T *ToArray(); + void TrimExcess(); + }; + } + } +} + +#endif //_LIST_ diff --git a/include/System/String.h b/include/System/String.h new file mode 100644 index 0000000..d6dc879 --- /dev/null +++ b/include/System/String.h @@ -0,0 +1,87 @@ +/******************************************************** + * String.h * + * * + * XFX String definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_STRING_ +#define _SYSTEM_STRING_ + +#include "Enums.h" +#include + +namespace System +{ + /// + /// Represents text as a series of Unicode characters. + /// + class String + { + private: + int m_arrayLength; + char m_firstChar; + int m_stringLength; + static const int TrimBoth = 2; + static const int TrimHead = 0; + static const int TrimTail = 1; + char* internalString; + + public: + int Length(); + static const String Empty; + + String(); + String(char c, int count); + String(char value[], int startIndex, int length); //Note: can also be used as String(char *value, int startIndex, int length); + String(char* value); + String(const String &obj); // Copy constructor + ~String(); + + String Clone(); + int Compare(String strA, String strB); + static String Concat(String values[]); + static String Concat(String str1, String str2, String str3, String str4); + bool Contains(char* value); + bool EndsWith(char* value); + bool Equals(const String obj); + bool Equals(const String str1, const String str2); + static char* Format(char* format, ...); + int IndexOf(char value); + int IndexOf(char value, int startIndex); + int IndexOf(char value, int startIndex, int count); + static bool IsNullOrEmpty(String value); + static String Join(String &separator, String value[]); + static String Join(String &separator, String value[], int startIndex, int count); + String PadLeft(int totalWidth); + String PadLeft(int totalWidth, char paddingChar); + String PadRight(int totalWidth); + String PadRight(int totalWidth, char paddingChar); + String Replace(char oldChar, char newChar); + String Replace(char* oldValue, char* newValue); + char** Split(String *separator, int count, StringSplitOptions_t options); + char** Split(String *separator, StringSplitOptions_t options); + char** Split(char separator[], int count, StringSplitOptions_t options); + char** Split(char separator[], StringSplitOptions_t options); + char** Split(char separator[], int count); + char** Split(char separator[]); + bool StartsWith(char* value); + String SubString(int startIndex); + String SubString(int startIndex, int length); + char *ToCharArray(int startIndex, int length); + char *ToCharArray(); + String ToLower(); + char* ToString(); + String ToUpper(); + + bool operator!=(const String right); + bool operator==(const String right); + bool operator==(const char* right); + String operator=(const char* right); + String operator=(const String right); + char operator [](int index); + }; + + typedef String string; +} + +#endif //_SYSTEM_STRING_ diff --git a/include/System/Text/ASCIIEncoding.h b/include/System/Text/ASCIIEncoding.h new file mode 100644 index 0000000..8f47ee3 --- /dev/null +++ b/include/System/Text/ASCIIEncoding.h @@ -0,0 +1,35 @@ +/******************************************************** + * ASCIIEncoding.h * + * * + * XFX ASCIIEncoding class definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _ASCIIENCODING_ +#define _ASCIIENCODING_ + +#include "Encoding.h" + +namespace System +{ + namespace Text + { + /// + /// Represents an ASCII character encoding of Unicode characters. + /// + class ASCIIEncoding : public Encoding + { + public: + ASCIIEncoding(); + int GetByteCount(char chars[], int index, int count); + int GetByteCount(String &chars); + int GetBytes(char chars[], int charIndex, int charCount, byte bytes[], int byteIndex); + int GetBytes(String &chars, int charIndex, int charCount, byte bytes[], int byteIndex); + int GetCharCount(byte bytes[], int index, int count); + int GetChars(byte bytes[], int byteIndex, int byteCount, char chars[], int charIndex); + int GetMaxByteCount(int charCount); + int GetMaxCharCount(int byteCount); + }; + } +} + +#endif //_ASCIIENCODING_ diff --git a/include/System/Text/Decoder.h b/include/System/Text/Decoder.h new file mode 100644 index 0000000..ce37956 --- /dev/null +++ b/include/System/Text/Decoder.h @@ -0,0 +1,42 @@ +/******************************************************** + * Decoder.h * + * * + * XFX Decoder class definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _TEXT_DECODER_ +#define _TEXT_DECODER_ + +#include "../Types.h" + +namespace System +{ + namespace Text + { + /// + /// Converts a sequence of encoded bytes into a set of characters. + /// + class Decoder + { + private: + void CheckArguments(char chars[], int charIndex); + void CheckArguments(byte bytes[], int byteIndex, int byteCount); + void CheckArguments(char* chars, int charCount, byte* bytes, int byteCount); + + public: + Decoder(); + + virtual void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed); + virtual void Convert(byte bytes[], int byteIndex, int byteCount, char chars[], int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed); + virtual int GetCharCount(byte* bytes, int count, bool flush); + virtual int GetCharCount(byte bytes[], int index, int count); + virtual int GetCharCount(byte bytes[], int index, int count, bool flush); + virtual int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush); + virtual int GetChars(byte bytes[], int byteIndex, int byteCount, char chars[], int charIndex); + virtual int GetChars(byte bytes[], int byteIndex, int byteCount, char chars[], int charIndex, bool flush); + virtual void Reset(); + }; + } +} + +#endif //_TEXT_DECODER_ diff --git a/include/System/Text/Encoder.h b/include/System/Text/Encoder.h new file mode 100644 index 0000000..d05b2b6 --- /dev/null +++ b/include/System/Text/Encoder.h @@ -0,0 +1,29 @@ +#ifndef _TEXT_ENCODER_ +#define _TEXT_ENCODER_ + +#include "../Types.h" + +namespace System +{ + namespace Text + { + /// + /// Converts a set of characters into a sequence of bytes. + /// + class Encoder + { + protected: + Encoder(); + + public: + virtual void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, int charsUsed, int bytesUsed, bool completed); + virtual void Convert(char chars[], int charIndex, int charCount, byte bytes[], int byteIndex, int byteCount, bool flush, int charsUsed, int bytesUsed, bool completed); + virtual int GetByteCount(char* chars, int count, bool flush); + virtual int GetByteCount(char chars[], int index, int count, bool flush); + virtual int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush); + virtual int GetBytes(char chars[], int charIndex, int charCount, byte bytes[], int byteIndex, bool flush); + }; + } +} + +#endif //_TEXT_ENCODER_ diff --git a/include/System/Text/Encoding.h b/include/System/Text/Encoding.h new file mode 100644 index 0000000..2f31382 --- /dev/null +++ b/include/System/Text/Encoding.h @@ -0,0 +1,68 @@ +/******************************************************** + * Encoding.h * + * * + * XFX Encoding class definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _ENCODING_ +#define _ENCODING_ + +#include "../Types.h" +#include "Decoder.h" +#include "Encoder.h" + +namespace System +{ + class String; + + namespace Text + { + /// + /// Represents a character encoding. + /// + class Encoding + { + public: + Encoding(); + Encoding(int codePage); + + static Encoding ASCII(); + static Encoding BigEndianUnicode(); + virtual int CodePage(); + static Encoding Default(); + static Encoding Unicode(); + static Encoding UTF7(); + static Encoding UTF8(); + virtual String WebName(); + + virtual Encoding Clone(); + static byte *Convert(Encoding &srcEncoding, Encoding &dstEncoding, byte bytes[]); + static byte *Convert(Encoding &srcEncoding, Encoding &dstEncoding, byte bytes[], int index, int count); + bool Equals(Encoding &obj); + virtual int GetByteCount(char chars[]); + virtual int GetByteCount(char chars[], int index, int count); + virtual int GetByteCount(String &s); + virtual byte *GetBytes(char chars[]); + virtual byte *GetBytes(char chars[], int index, int count); + virtual int GetBytes(char chars[], int charIndex, int charCount, byte bytes[], int byteIndex); + virtual byte *GetBytes(String &s); + virtual int GetBytes(String &s, int charIndex, int charCount, byte bytes[], int byteIndex); + virtual int GetCharCount(byte bytes[]); + virtual int GetCharCount(byte bytes[], int index, int count); + virtual char *GetChars(byte bytes[]); + virtual char *GetChars(byte bytes[], int index, int count); + virtual int GetChars(byte bytes[], int byteIndex, int byteCount, char chars[], int charIndex); + virtual Decoder GetDecoder(); + virtual Encoder GetEncoder(); + static Encoding GetEncoding(int codePage); + static Encoding GetEncoding(String &name); + int GetHashCode(); + virtual int GetMaxByteCount(int charCount); + virtual int GetMaxCharCount(int byteCount); + virtual byte *GetPreamble(); + virtual String GetString(byte bytes[], int index, int count); + }; + } +} + +#endif //_ENCODING_ diff --git a/include/System/Threading/Enums.h b/include/System/Threading/Enums.h new file mode 100644 index 0000000..45b63b0 --- /dev/null +++ b/include/System/Threading/Enums.h @@ -0,0 +1,48 @@ +/******************************************************** + * Enums.h * + * * + * System::Threading enumerations definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_THREADING_ENUMS_ +#define _SYSTEM_THREADING_ENUMS_ + +namespace System +{ + namespace Threading + { + /// + /// Indicates whether an System.Threading.EventWaitHandle is reset automatically or manually after receiving a + /// signal. + /// + struct EventResetMode + { + enum type + { + AutoReset, + ManualReset + }; + }; + + /// + /// The System.Threading.Thread can be scheduled after threads with Highest priority and before those with + /// Normal priority. + /// + struct ThreadPriority + { + enum type + { + AboveNormal, + BelowNormal, + Highest = 32, + Lowest = 0, + Normal, + }; + }; + + typedef EventResetMode::type EventResetMode_t; + typedef ThreadPriority::type ThreadPriority_t; + } +} + +#endif //_SYSTEM_THREADING_ENUMS_ diff --git a/include/System/Threading/Thread.h b/include/System/Threading/Thread.h new file mode 100644 index 0000000..f03e0e9 --- /dev/null +++ b/include/System/Threading/Thread.h @@ -0,0 +1,63 @@ +/******************************************************** + * Thread.h * + * * + * XFX Thread definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_THREADING_THREAD_ +#define _SYSTEM_THREADING_THREAD_ + +extern "C" { +#ifdef ENABLE_XBOX +#include +#else +#endif +} + +#include "ThreadState.h" +#include "../TimeSpan.h" + +namespace System +{ + namespace Threading + { + class Thread + { + int lock_thread_id; + HANDLE system_thread_handle; + PKSTART_ROUTINE callback; + int stack_size; + static ULONG Id; + PULONG suspendCount; + + ThreadState_t state; + + private: + void Thread_init(); + + public: + //Creates a new instance of the Thread class with the specified callback function, but doesn't start yet. + Thread(PKSTART_ROUTINE callBack); + //Creates a new instance of the Thread class with the specified callback function and stack size, but doesn't start yet. + Thread(PKSTART_ROUTINE callBack, int stackSize); + ~Thread(); + + void Abort(); + void Interrupt(); + //Returns a value indicating whether the thread is running + bool IsAlive(); + //Resumes a previously suspended thread. + void Resume(); + //Set the thread priority, valid values are 0 (Low), 16 (Low_RealTime), 31 (High), 32 (Maximum) + void SetPriority(int priority); + static void Sleep(int millisecondsTimeout); + static void Sleep(TimeSpan timeout); + //Start executing the thread. + void Start(); + //Suspend the thread execution, call Thread::Resume() to resume the thread. + void Suspend(); + }; + } +} + +#endif //_SYSTEM_THREADING_THREAD_ diff --git a/include/System/Threading/ThreadState.h b/include/System/Threading/ThreadState.h new file mode 100644 index 0000000..442c053 --- /dev/null +++ b/include/System/Threading/ThreadState.h @@ -0,0 +1,35 @@ +/******************************************************** + * ThreadState.h * + * * + * XFX ThreadState enumeration definition file * + * Copyright © Halofreak1990. All Rights Reserved * + ********************************************************/ +#ifndef _THREADSTATE_ +#define _THREADSTATE_ + +namespace System +{ + namespace Threading + { + struct ThreadState + { + enum type + { + Running = 0x00000000, + StopRequested = 0x00000001, + SuspendRequested = 0x00000002, + Background = 0x00000004, + Unstarted = 0x00000008, + Stopped = 0x00000010, + WaitSleepJoin = 0x00000020, + Suspended = 0x00000040, + AbortRequested = 0x00000080, + Aborted = 0x00000100 + }; + }; + + typedef ThreadState::type ThreadState_t; + } +} + +#endif //_THREADSTATE_ diff --git a/include/System/Threading/WaitHandle.h b/include/System/Threading/WaitHandle.h new file mode 100644 index 0000000..643985b --- /dev/null +++ b/include/System/Threading/WaitHandle.h @@ -0,0 +1,37 @@ +/******************************************************** + * WaitHandle.h * + * * + * XFX WaitHandle definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_THREADING_WAITHANDLE_ +#define _SYSTEM_THREADING_WAITHANDLE_ + +#include "../Types.h" + +namespace System +{ + namespace Threading + { + /// + /// Encapsulates operating system–specific objects that wait for exclusive access to shared resources. + /// + class WaitHandle + { + protected: + static const IntPtr InvalidHandle; + + virtual void Dispose(bool explicitDisposing); + WaitHandle(); + + public: + IntPtr Handle; + + virtual void Close(); + virtual bool WaitOne(); + virtual bool WaitOne(int millisecondsTimeout, bool exitContext); + }; + } +} + +#endif //_SYSTEM_THREADING_WAITHANDLE_ diff --git a/include/System/TimeSpan.h b/include/System/TimeSpan.h new file mode 100644 index 0000000..05d6b61 --- /dev/null +++ b/include/System/TimeSpan.h @@ -0,0 +1,79 @@ +/******************************************************** + * TimeSpan.h * + * * + * XFX TimeSpan definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_TIMESPAN_ +#define _SYSTEM_TIMESPAN_ + +#include "Types.h" + +namespace System +{ + class TimeSpan + { + private: + Int64 _ticks; + + static bool CalculateTicks(int days, int hours, int minutes, int seconds, int milliseconds, bool throwExc, out long long result); + static TimeSpan Interval(double value, int scale); + + public: + static const TimeSpan MaxValue; + static const TimeSpan MinValue; + static const TimeSpan Zero; + static const Int64 TicksPerMillisecond; + static const Int64 TicksPerSecond; + static const Int64 TicksPerMinute; + static const Int64 TicksPerHour; + static const Int64 TicksPerDay; + + int Days(); + int Hours(); + int Milliseconds(); + int Minutes(); + int Seconds(); + Int64 Ticks(); + double TotalDays(); + double TotalHours(); + double TotalMilliseconds(); + double TotalMinutes(); + double TotalSeconds(); + + TimeSpan(int hours, int minutes, int seconds); + TimeSpan(int days, int hours, int minutes, int seconds); + TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds); + TimeSpan(long long ticks); + TimeSpan(const TimeSpan &obj); + + TimeSpan Add(TimeSpan ts); + int Compare(TimeSpan t1, TimeSpan t2); + int CompareTo(TimeSpan ts); + bool Equals(TimeSpan obj); + bool Equals(TimeSpan t1, TimeSpan t2); + static TimeSpan FromDays(double value); + static TimeSpan FromHours(double value); + static TimeSpan FromMilliseconds(double value); + static TimeSpan FromMinutes(double value); + static TimeSpan FromSeconds(double value); + static TimeSpan FromTicks(Int64 value); + int GetHashCode(); + TimeSpan Negate(); + TimeSpan Parse(char* s); //! TODO + TimeSpan Subtract(TimeSpan ts); + char* ToString(); //! TODO + + TimeSpan operator+(const TimeSpan other); + bool operator==(const TimeSpan other); + bool operator >(const TimeSpan other); + bool operator>=(const TimeSpan other); + bool operator!=(const TimeSpan other); + bool operator <(const TimeSpan other); + bool operator<=(const TimeSpan other); + TimeSpan operator -(const TimeSpan other); + TimeSpan operator -(); + }; +} + +#endif //_TIMESPAN_ diff --git a/include/System/TimeZone.h b/include/System/TimeZone.h new file mode 100644 index 0000000..08e2987 --- /dev/null +++ b/include/System/TimeZone.h @@ -0,0 +1,40 @@ +/******************************************************** + * TimeZone.h * + * * + * TimeZone definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_TIMEZONE_ +#define _SYSTEM_TIMEZONE_ + +#include + +namespace System +{ + class DateTime; + class String; + class TimeSpan; + + /// + /// Represents a time zone. + /// + class TimeZone + { + protected: + TimeZone(); + + public: + static TimeZone CurrentTimeZone(); + String DaylightName(); + String StandardName(); + + System::Globalization::DaylightTime GetDaylightChanges(int year); + TimeSpan GetUtcOffset(DateTime time); + bool IsDaylightSavingTime(DateTime time); + static bool IsDaylightSavingTime(DateTime time, System::Globalization::DaylightTime daylightTimes); + DateTime ToLocalTime(DateTime time); + DateTime ToUniversalTime(DateTime time); + }; +} + +#endif //_SYSTEM_TIMEZONE_ diff --git a/include/System/Types.h b/include/System/Types.h new file mode 100644 index 0000000..671891c --- /dev/null +++ b/include/System/Types.h @@ -0,0 +1,50 @@ +/******************************************************** + * Types.h * + * * + * Defines types for the entire XFX Framework * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_TYPES_ +#define _SYSTEM_TYPES_ + +#ifndef NULL +#define NULL 0 +#endif + +namespace System +{ + // Type definitions + // + /* SIGNED */ + typedef signed char sbyte, SByte; + typedef signed short Int16; + typedef signed int Int32; + typedef signed long long Int64; + typedef signed int *IntPtr; + /* UNSIGNED */ + typedef unsigned char byte, Byte; + typedef unsigned short ushort, UInt16; + typedef unsigned int uint, UInt32; + typedef unsigned long long ulong, UInt64; + /* FLOATING-POINT */ + typedef float Single; + typedef double Double; + /* OTHER */ + typedef bool Boolean; + +#define null NULL +} + +// Other typedefs +// +#define interface class + +// Documentation +// +#define out + +// Aligning Data types +// +#define ALIGNED __attribute__ ((aligned (16))) + +#endif //_SYSTEM_TYPES_ diff --git a/include/System/Version.h b/include/System/Version.h new file mode 100644 index 0000000..a6e87c9 --- /dev/null +++ b/include/System/Version.h @@ -0,0 +1,51 @@ +/******************************************************** + * Version.h * + * * + * XFX Version definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_VERSION_ +#define _SYSTEM_VERSION_ + +namespace System +{ + /// + /// Represents the version number for a common language runtime assembly. + /// + class Version + { + private: + int _build; + int _major; + int _minor; + int _revision; + + public: + int Build(); + int Major(); + int Minor(); + int Revision(); + + Version(int major, int minor); + Version(int major, int minor, int build); + Version(int major, int minor, int build, int revision); + Version(char* version); + Version(const Version &obj); + + Version Clone(); + int CompareTo(Version value); + bool Equals(Version obj); + int GetHashCode(); + char* ToString(); + char* ToString(int fieldCount); + + bool operator !=(const Version other); + bool operator <(const Version other); + bool operator <=(const Version other); + bool operator ==(const Version other); + bool operator >(const Version other); + bool operator >=(const Version other); + }; +} + +#endif //_SYSTEM_VERSION_ diff --git a/include/System/XKUtils/APICompat.h b/include/System/XKUtils/APICompat.h new file mode 100644 index 0000000..411c777 --- /dev/null +++ b/include/System/XKUtils/APICompat.h @@ -0,0 +1,50 @@ +#ifndef __APICompat_H__ + +#define __APICompat_H__ + + +#include + +#include + + +extern "C" { + +#include + +#include + +#include + +} + + +#define Sleep XSleep + + + +/* Port IO */ + +unsigned char _outp(unsigned short port, unsigned char databyte); + +unsigned short _outpw(unsigned short port, unsigned short dataword); + +unsigned long _outpd(unsigned short port, unsigned long dataword); + +unsigned char _inp(unsigned short port); + +unsigned short _inpw(unsigned short port); + +unsigned long _inpd(unsigned short port); + + + +/* Misc */ + +#define min(A, B) ((A) < (B)) ? (A) : (B) + +char *itoa(int value, char *buffer, int radix); + +void *ZeroMemory(void *s, size_t n); + +#endif diff --git a/include/System/XKUtils/XKCRC.h b/include/System/XKUtils/XKCRC.h new file mode 100644 index 0000000..271b6ab --- /dev/null +++ b/include/System/XKUtils/XKCRC.h @@ -0,0 +1,77 @@ +/* +********************************** +********************************** +** BROUGHT TO YOU BY: ** +********************************** +********************************** +** ** +** [TEAM ASSEMBLY] ** +** ** +** www.team-assembly.com ** +** ** +****************************************************************************************************** +* This is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 2 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +****************************************************************************************************** + +******************************************************************************************************** +** XKCRC.H - General CRC Class' Header +******************************************************************************************************** +** +** This is the Class Header, see the .CPP file for more comments and implementation details. +** +******************************************************************************************************** + +UPDATE LOG: +-------------------------------------------------------------------------------------------------------- +Date: 07/05/2006 +By: friedgold +Reason: OpenXDK Version +-------------------------------------------------------------------------------------------------------- +Date: 02/18/2003 +By: UNDEAD [team-assembly] +Reason: Prepared 0.2 for Public Release +-------------------------------------------------------------------------------------------------------- +Date: 01/06/2003 +By: UNDEAD [team-assembly] +Reason: Prepared for Public Release +-------------------------------------------------------------------------------------------------------- + +*/ + +#ifndef __XKCRC_H__ +#define __XKCRC_H__ + +#if defined (_WINDOWS) + #include // MFC core and standard components +#elif defined (ENABLE_XBOX) +extern "C" { +#include +#include +} +#else + #error ERRR: Have to Define _WINDOWS or ENABLE_XBOX !! +#endif + + +class XKCRC +{ +public: + XKCRC(void); + virtual ~XKCRC(void); + + static void QuickCRC(UCHAR* CRCVAL, UCHAR* inData, DWORD dataLen); + +}; +#endif diff --git a/include/System/XKUtils/XKEEPROM.h b/include/System/XKUtils/XKEEPROM.h new file mode 100644 index 0000000..6aa72f3 --- /dev/null +++ b/include/System/XKUtils/XKEEPROM.h @@ -0,0 +1,270 @@ +/* +********************************** +********************************** +** BROUGHT TO YOU BY: ** +********************************** +********************************** +** ** +** [TEAM ASSEMBLY] ** +** ** +** www.team-assembly.com ** +** ** +****************************************************************************************************** +* This is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 2 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +****************************************************************************************************** + + +******************************************************************************************************** +** XKEEPROM.H - XBOX EEPROM Class' Header +******************************************************************************************************** +** +** This is the Class Header, see the .CPP file for more comments and implementation details. +** +******************************************************************************************************** + +******************************************************************************************************** +** CREDITS: +******************************************************************************************************** +** XBOX-LINUX TEAM: +** --------------- +** Wow, you guys are awsome !! I bow down to your greatness !! the "Friday 13th" Middle +** Message Hack really saved our butts !! +** REFERENCE URL: http://xbox-linux.sourceforge.net +** +******************************************************************************************************** + +UPDATE LOG: +-------------------------------------------------------------------------------------------------------- +Date: 07/05/2006 +By: friedgold +Reason: OpenXDK Version +-------------------------------------------------------------------------------------------------------- +Date: 11/27/2004 +By: Yoshihiro +Reason: Update for xbox 1.6 +-------------------------------------------------------------------------------------------------------- +Date: 02/18/2003 +By: UNDEAD [team-assembly] +Reason: Prepared 0.2 for Public Release +-------------------------------------------------------------------------------------------------------- +Date: 01/25/2003 +By: UNDEAD [team-assembly] +Reason: Added XBOX Specific code to read EEPROM Data from Hardware +-------------------------------------------------------------------------------------------------------- +Date: 01/06/2003 +By: UNDEAD [team-assembly] +Reason: Prepared for Public Release +-------------------------------------------------------------------------------------------------------- +*/ + +#ifndef __XKEEPROM_H__ +#define __XKEEPROM_H__ + +extern "C" { +#include +#include +} + +class XKEEPROM +{ +public: + //Defines for Data structure sizes.. + #define EEPROM_SIZE 0x100 + #define CONFOUNDER_SIZE 0x008 + #define HDDKEY_SIZE 0x010 + #define XBEREGION_SIZE 0x001 + #define SERIALNUMBER_SIZE 0x00C + #define MACADDRESS_SIZE 0x006 + #define ONLINEKEY_SIZE 0x010 + #define DVDREGION_SIZE 0x001 + #define VIDEOSTANDARD_SIZE 0x004 + + //EEPROM Data structe value enums + enum XBOX_VERSION + { + V_NONE = 0x00, + V1_0 = 0x0A, + V1_1 = 0x0B, + V1_6 = 0x0C + }; + + enum DVD_ZONE + { + ZONE_NONE = 0x00, + ZONE1 = 0x01, + ZONE2 = 0x02, + ZONE3 = 0x03, + ZONE4 = 0x04, + ZONE5 = 0x05, + ZONE6 = 0x06 + }; + + enum VIDEO_ASPECT + { + WIDESCREEN=1, + NORMAL=0 + }; + + enum VIDEO_STANDARD + { + VID_INVALID = 0x00000000, + NTSC_M = 0x00400100, + PAL_I = 0x00800300, + NTSC_J = 0x00400200 + }; + + enum XBE_REGION + { + XBE_INVALID = 0x00, + NORTH_AMERICA = 0x01, + JAPAN = 0x02, + EURO_AUSTRALIA = 0x04 + }; + + enum LANGUAGE + { + LANGUAGE_INVALID = 0x00, + LANGUAGE_ENGLISH = 0x01, + LANGUAGE_JAPANESE = 0x02, + LANGUAGE_GERMAN = 0x03, + LANGUAGE_FRENCH = 0x04, + LANGUAGE_SPANISH = 0x05, + LANGUAGE_ITALIAN = 0x06, + LANGUAGE_KOREAN = 0x07, + LANGUAGE_CHINESE = 0x08, + LANGUAGE_PORTUGUESE = 0x09 + }; + + //Structure that holds contents of 256 byte EEPROM image.. + struct EEPROMDATA + { + BYTE HMAC_SHA1_Hash[20]; // 0x00 - 0x13 HMAC_SHA1 Hash + BYTE Confounder[8]; // 0x14 - 0x1B RC4 Encrypted Confounder ?? + BYTE HDDKkey[16]; // 0x1C - 0x2B RC4 Encrypted HDD key + BYTE XBERegion[4]; // 0x2C - 0x2F RC4 Encrypted Region code (0x01 North America, 0x02 Japan, 0x04 Europe) + + BYTE Checksum2[4]; // 0x30 - 0x33 Checksum of next 44 bytes + UCHAR SerialNumber[12]; // 0x34 - 0x3F Xbox serial number + BYTE MACAddress[6]; // 0x40 - 0x45 Ethernet MAC address + BYTE UNKNOWN2[2]; // 0x46 - 0x47 Unknown Padding ? + + BYTE OnlineKey[16]; // 0x48 - 0x57 Online Key ? + + BYTE VideoStandard[4]; // 0x58 - 0x5B ** 0x00014000 = NTSC, 0x00038000 = PAL + + BYTE UNKNOWN3[4]; // 0x5C - 0x5F Unknown Padding ? + + + //Comes configured up to here from factory.. everything after this can be zero'd out... + //To reset XBOX to Factory settings, Make checksum3 0xFFFFFFFF and zero all data below (0x64-0xFF) + //Doing this will Reset XBOX and upon startup will get Language & Setup screen... + BYTE Checksum3[4]; // 0x60 - 0x63 other Checksum of next + + BYTE TimeZoneBias[4]; // 0x64 - 0x67 Zone Bias? + UCHAR TimeZoneStdName[4]; // 0x68 - 0x6B Standard timezone + UCHAR TimeZoneDltName[4]; // 0x5C - 0x6F Daylight timezone + BYTE UNKNOWN4[8]; // 0x70 - 0x77 Unknown Padding ? + BYTE TimeZoneStdDate[4]; // 0x78 - 0x7B 10-05-00-02 (Month-Day-DayOfWeek-Hour) + BYTE TimeZoneDltDate[4]; // 0x7C - 0x7F 04-01-00-02 (Month-Day-DayOfWeek-Hour) + BYTE UNKNOWN5[8]; // 0x80 - 0x87 Unknown Padding ? + BYTE TimeZoneStdBias[4]; // 0x88 - 0x8B Standard Bias? + BYTE TimeZoneDltBias[4]; // 0x8C - 0x8F Daylight Bias? + + BYTE LanguageID[4]; // 0x90 - 0x93 Language ID + + BYTE VideoFlags[4]; // 0x94 - 0x97 Video Settings + BYTE AudioFlags[4]; // 0x98 - 0x9B Audio Settings + + BYTE ParentalControlGames[4]; // 0x9C - 0x9F 0=MAX rating + BYTE ParentalControlPwd[4]; // 0xA0 - 0xA3 7=X, 8=Y, B=LTrigger, C=RTrigger + BYTE ParentalControlMovies[4]; // 0xA4 - 0xA7 0=Max rating + + BYTE XBOXLiveIPAddress[4]; // 0xA8 - 0xAB XBOX Live IP Address.. + BYTE XBOXLiveDNS[4]; // 0xAC - 0xAF XBOX Live DNS Server.. + BYTE XBOXLiveGateWay[4]; // 0xB0 - 0xB3 XBOX Live Gateway Address.. + BYTE XBOXLiveSubNetMask[4]; // 0xB4 - 0xB7 XBOX Live Subnet Mask.. + BYTE OtherSettings[4]; // 0xA8 - 0xBB Other XBLive settings ? + + BYTE DVDPlaybackKitZone[4]; // 0xBC - 0xBF DVD Playback Kit Zone + + BYTE UNKNOWN6[64]; // 0xC0 - 0xFF Unknown Codes / History ? + }; + typedef EEPROMDATA* LPEEPROMDATA; + + XKEEPROM(void); + XKEEPROM(LPEEPROMDATA pEEPROMData, BOOL Encrypted); + ~XKEEPROM(void); + + BOOL ReadFromBINFile(LPCSTR FileName, BOOL IsEncrypted); + BOOL WriteToBINFile(LPCSTR FileName); + +//very XBOX specific funtions to read/write EEPROM from hardware + void ReadFromXBOX(); + void WriteToXBOX(); + + void GetEEPROMData(LPEEPROMDATA pEEPROMData); + void SetDecryptedEEPROMData(XBOX_VERSION Version, LPEEPROMDATA pEEPROMData); + void SetEncryptedEEPROMData(LPEEPROMDATA pEEPROMData); + + XBOX_VERSION GetXBOXVersion(); + + void GetConfounderString(LPSTR Confounder, LPDWORD Length); + void SetConfounderString(LPCSTR Confounder); + + void GetHDDKeyString(LPSTR HDDKey, LPDWORD Length); + void SetHDDKeyString(LPCSTR HDDKey); + + BOOL SetXBERegion(XBE_REGION RegionVal); + XBE_REGION GetXBERegion(); + + void SetLanguage(LANGUAGE lang); + LANGUAGE GetLanguage(); + + void GetSerialNumberString(LPSTR SerialNumber, LPDWORD Length); + void SetSerialNumberString(LPCSTR SerialNumber); + + void GetMACAddressString(LPSTR MACAddress, LPDWORD Length); + void SetMACAddressString(LPCSTR MACAddress); + + void GetOnlineKeyString(LPSTR OnlineKey, LPDWORD Length); + void SetOnlineKeyString(LPCSTR OnlineKey); + + BOOL SetDVDRegion(DVD_ZONE ZoneVal); + DVD_ZONE GetDVDRegion(); + + BOOL SetVideoStandard(VIDEO_STANDARD StandardVal); + VIDEO_STANDARD GetVideoStandard(); + BOOL SetVideoAspect(VIDEO_ASPECT size); + VIDEO_ASPECT GetVideoAspect(); + + BOOL EncryptAndCalculateCRC(); + BOOL EncryptAndCalculateCRC(XBOX_VERSION XBOXVersion); + + BOOL Decrypt(); + BOOL Decrypt(BYTE *EEPROM_Key); + + BOOL IsEncrypted(); + + void CalculateChecksum2(); + void CalculateChecksum3(); + +protected: + EEPROMDATA m_EEPROMData; + XBOX_VERSION m_XBOX_Version; + BOOL m_EncryptedState; + +}; + +#endif diff --git a/include/System/XKUtils/XKFlash.h b/include/System/XKUtils/XKFlash.h new file mode 100644 index 0000000..35a063a --- /dev/null +++ b/include/System/XKUtils/XKFlash.h @@ -0,0 +1,40 @@ + +#ifndef XBOXFLASH_H +#define XBOXFLASH_H + +extern "C" { +#include +#include +} + +typedef struct fci_s { + unsigned char mfct; + unsigned char devc; + const char *text; + unsigned long size; +} fci_t; + +class CXBoxFlash +{ + +public: + CXBoxFlash(void); + ~CXBoxFlash(void); + + bool ReadFromXbox(char *path); + bool WriteToXbox(char *path); + +protected: + fci_t* FindFCI(BYTE manuf, BYTE code); + inline void Write(DWORD address,BYTE data); + inline BYTE Read(DWORD address); + void SetReadMode2(void); + fci_t* CheckID2(void); + fci_t* CheckID(void) ; + void SetReadMode(void); + bool EraseBlock(int block); + bool EraseDevice(fci_t* fci); + bool WaitOnToggle(void); +}; + +#endif diff --git a/include/System/XKUtils/XKGeneral.h b/include/System/XKUtils/XKGeneral.h new file mode 100644 index 0000000..a5e6702 --- /dev/null +++ b/include/System/XKUtils/XKGeneral.h @@ -0,0 +1,95 @@ +/* +********************************** +********************************** +** BROUGHT TO YOU BY: ** +********************************** +********************************** +** ** +** [TEAM ASSEMBLY] ** +** ** +** www.team-assembly.com ** +** ** +****************************************************************************************************** +* This is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 2 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +****************************************************************************************************** + + +******************************************************************************************************** +** XKGENERAL.H - General Utility and Helper function Class' Header +******************************************************************************************************** +** +** This is the Class Header, see the .CPP file for more comments and implementation details. +** +******************************************************************************************************** + +UPDATE LOG: +-------------------------------------------------------------------------------------------------------- +Date: 07/05/2006 +By: friedgold +Reason: OpenXDK Version +-------------------------------------------------------------------------------------------------------- +Date: 02/18/2003 +By: UNDEAD [team-assembly] +Reason: Prepared 0.2 for Public Release +-------------------------------------------------------------------------------------------------------- +Date: 01/06/2003 +By: UNDEAD [team-assembly] +Reason: Prepared for Public Release +-------------------------------------------------------------------------------------------------------- + +*/ + +#ifndef __XKGENERAL_H__ +#define __XKGENERAL_H__ +#if defined (_WINDOWS) + #include // MFC core and standard components +#elif defined (ENABLE_XBOX) + #include +extern "C" { +#include +#include +} +#else + #error ERR: Have to Define _WINDOWS or ENABLE_XBOX !! +#endif + +#ifndef FILENAME_MAX + #define FILENAME_MAX 260 +#endif + +class XKGeneral +{ +protected: +#define HEX_VALUES {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'} + +public: + XKGeneral(void); + ~XKGeneral(void); + + //Generic conversion functions.. + static void BytesToHexStr(BYTE *SrcBytes, DWORD byteCount, LPSTR DstString); + static void BytesToHexStr(BYTE *SrcBytes, DWORD byteCount, LPSTR DstString, UCHAR Seperator); + static void MixedStrToDecStr(LPSTR StringData, LPDWORD StrLen, CHAR Base, BOOL RemoveInvalid); + static void HexStrToBytes(BYTE *StringData, LPDWORD pBufferLen, BOOL RemoveInvalid); + static DWORD HexStrToDWORD(BYTE *StringData, LPDWORD pBufferLen, BOOL RemoveInvalid, BOOL FlipByteOrder); + + //Read items and values from a .INI file.. + static BOOL ReadINIFileItem(LPCSTR INIFileName, LPCSTR INISection, LPCSTR INIItem, LPSTR ItemValue, LPDWORD ValueLen); + + //Strip Quotes from a string.. + static void StripEnclosedChars(LPSTR sString, LPDWORD strLen, CHAR EncloseChar); + static void StripQuotes(LPSTR sString, LPDWORD strLen); +}; +#endif diff --git a/include/System/XKUtils/XKHDD.h b/include/System/XKUtils/XKHDD.h new file mode 100644 index 0000000..6200089 --- /dev/null +++ b/include/System/XKUtils/XKHDD.h @@ -0,0 +1,344 @@ +/* +********************************** +********************************** +** BROUGHT TO YOU BY: ** +********************************** +********************************** +** ** +** [TEAM ASSEMBLY] ** +** ** +** www.team-assembly.com ** +** ** +****************************************************************************************************** +* This is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 2 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +****************************************************************************************************** + + +******************************************************************************************************** +** XKHDD.H - Hard Disk Class Header +******************************************************************************************************** +** +** This is the Class Header, see the .CPP file for more comments and implementation details. +** Member helper function included to parse ATA IDENTIFY data and get HDD Serial, Model etc. +** +** +******************************************************************************************************** + +******************************************************************************************************** +** CREDITS: +******************************************************************************************************** +** SPEEDBUMP: +** ---------- +** My utmost greatfullness and admiration goes towards SpeedBump for all his hard work.. +** I used most of his code and converted to C++ objects etc.. +** +** MRUEL: +** ------- +** Thanks for the pointing us to the Pascall Code that was used for Locking/Unlocking the disk.. +** Great work on UnlockX.. keep it up ! +** +** MARTIN GERDES: +** ------------- +** An editor of the german "c't" magazine. The article we referenced was published in +** c't Magazine 11/91 "Platten-Auslese - Konfiguration von AT-Bus-Platten lesen" +** Thanks!, We ported this Pascall and ASM stuff to CPP to access the IDE Ports directly +** +******************************************************************************************************** + + +******************************************************************************************************** +** References: +******************************************************************************************************** +** +** ATA Specification: +** ------------------ +** This stuff helped us a quite a bit.. so go check it out ! +** REFERENCE URL: ftp://fission.dt.wdc.com/pub/standards/ata/ata-3/ata3-r6.doc +** +******************************************************************************************************** + +UPDATE LOG: +Date: 05/07/2007 +By: friedgold +Reason: OpenXDK Version +-------------------------------------------------------------------------------------------------------- +Date: 02/18/2003 +By: UNDEAD [team-assembly] +Reason: Prepared 0.2 for Public Release +-------------------------------------------------------------------------------------------------------- +Date: 01/06/2003 +By: UNDEAD [team-assembly] +Reason: Prepared for Public Release +-------------------------------------------------------------------------------------------------------- + +*/ +#ifndef __XKHDD_H__ +#define __XKHDD_H__ +extern "C" { +#include +#include +} + +//S.M.A.R.T IDENTIFIY OFFSETS +//CUSTOM S.M.A.R.T READ Values Offsets +#define SMART_RED_HDD_TEMP1 0x065 +#define SMART_RED_HDD_TEMP2 0x067 + + + +// Performs S.M.A.R.T cmd --> Requires valid bFeaturesReg, bCylLowReg, and bCylHighReg +#define IDE_EXECUTE_SMART_FUNCTION 0xB0 + +// Cylinder register values required when issuing SMART command +#define SMART_CYL_LOW 0x4F +#define SMART_CYL_HI 0xC2 + +// Feature register defines for S.M.A.R.T "sub commands" +#define SMART_READ_ATTRIBUTE_VALUES 0xD0 // S.M.A.R.T READ DATA +#define SMART_READ_ATTRIBUTE_THRESHOLDS 0xD1 // Obsoleted in ATA4! +#define SMART_ENABLE_DISABLE_ATTRIBUTE_AUTOSAVE 0xD2 +#define SMART_SAVE_ATTRIBUTE_VALUES 0xD3 +#define SMART_EXECUTE_OFFLINE_IMMEDIATE 0xD4 // ATA4 +#define SMART_ENABLE_SMART_OPERATIONS 0xD8 // Vendor specific command +#define SMART_DISABLE_SMART_OPERATIONS 0xD9 // Vendor specific command +#define SMART_RETURN_SMART_STATUS 0xDA // Vendor specific command + +// bDriverError values +#define SMART_NO_ERROR 0 // No error +#define SMART_IDE_ERROR 1 // Error from IDE controller +#define SMART_INVALID_FLAG 2 // Invalid command flag +#define SMART_INVALID_COMMAND 3 // Invalid command byte +#define SMART_INVALID_BUFFER 4 // Bad buffer (null, invalid addr..) +#define SMART_INVALID_DRIVE 5 // Drive number not valid +#define SMART_INVALID_IOCTL 6 // Invalid IOCTL +#define SMART_ERROR_NO_MEM 7 // Could not lock user's buffer +#define SMART_INVALID_REGISTER 8 // Some IDE Register not valid +#define SMART_NOT_SUPPORTED 9 // Invalid cmd flag set +#define SMART_NO_IDE_DEVICE 10 // Cmd issued to device not present although drive number is valid +// 11-255 reserved + + +//ATA IDENTIFY Structure offsets.. +//As per ATA Spec + +#define HDD_CONFIG 0x000 // 0 +#define HDD_NUM_OF_CYLS_OFFSET 0x002 // 2 +#define HDD_RESERVED_1_OFFSET 0x004 // 4 +#define HDD_NUM_OF_HEADS_OFFSET 0x006 // 6 +#define HDD_BYTE_PERTRACK_OFFSET 0x008 // 8 +#define HDD_BYTE_PERSECTOR_OFFSET 0x00a // 10 +#define HDD_SECTOR_PERTRACK_OFFSET 0x00c // 12 +#define HDD_VENDOR_SPEC_1_OFFSET 0x00e // 14 +#define HDD_SERIAL_OFFSET 0x014 // 20 ->ASCII +#define HDD_BUFFER_TYPE_OFFSET 0x028 // 40 +#define HDD_BUFFER_SIZE_OFFSET 0x02A // 42 +#define HDD_NUM_OF_ECC_BYTE_OFFSET 0x02c // 44 +#define IDE_FIRMWARE_OFFSET 0x02e // 46 ->ASCII +#define HDD_MODEL_OFFSET 0x036 // 54 ->ASCII +#define HDD_MUL_SEC_PER_INT_OFFSET 0x05E // 94 +#define HDD_DWIO_OFFSET 0x060 // 96 +#define HDD_LBADMA_OFFSET 0x062 // 98 +#define HDD_RESERVED_2_OFFSET 0x064 // 100 +#define HDD_PIO_TIMING_MODE_OFFSET 0x066 // 102 +#define HDD_DMA_TIMING_MODE_OFFSET 0x068 // 104 +#define HDD_RESERVED_3_OFFSET 0x06A // 106 +#define HDD_AP_NUM_OF_CYLS_OFFSET 0x06C // 108 +#define HDD_AP_NUM_OF_HEADS_OFFSET 0x06E // 110 +#define HDD_AP_SEC_PER_TRACK_OFFSET 0x070 // 112 +#define HDD_CAPACITY_OFFSET 0x072 // 114 +#define HDD_NUM_SEC_PER_INT_OFFSET 0x076 // 118 +#define HDD_LBA_SECTORS_OFFSET 0x078 // 120 +#define HDD_SIN_DMA_MODES_OFFSET 0x07C // 124 +#define HDD_MUL_DMA_MODES_OFFSET 0x07E // 126 +#define HDD_RESERVED_4_OFFSET 0x080 // 128 +#define HDD_SECURITY_STATUS_OFFSET 0x100 // 256 +#define HDD_RESERVED_5_OFFSET 0x140 // 320 + + +//IDE Port Addresses +#define IDE_PRIMARY_PORT 0x01F0 +#define IDE_SECONDARY_PORT 0x0170 + +//Important ATA Register Values As per ATA Spec +#define IDE_DEVICE_MASTER 0x00A0 +#define IDE_DEVICE_SLAVE 0x00B0 + +//Important ATA Command return register values As per ATA Spec +#define IDE_ERROR_SUCCESS 0x0000 +#define IDE_ERROR_ABORT 0x0004 + +//Our SendATACommand needs this to figure our if we should read or write data to IDE registers.. +#define IDE_COMMAND_READ 0x00 +#define IDE_COMMAND_WRITE 0x01 + +//Important ATA/ATAPI Commands As per ATA Spec +#define IDE_ATAPI_IDENTIFY 0xA1 +#define IDE_ATA_IDENTIFY 0xEC +#define IDE_ATA_COMMAND_SEEK 0x70 +#define IDE_ATA_COMMAND_READ_SECTORS 0x21 +#define IDE_ATA_COMMAND_READ_BUFFER 0xE4 +#define IDE_ATA_COMMAND_WRITE_SECTORS 0x30 +#define IDE_ATA_COMMAND_WRITE_BUFFER 0xE8 +#define IDE_ATA_COMMAND_DIAGNOSTIC 0x90 + +#define IDE_ATA_SECURITY_SETPASSWORD 0xF1 +#define IDE_ATA_SECURITY_UNLOCK 0xF2 +#define IDE_ATA_SECURITY_FREEZE 0xF5 +#define IDE_ATA_SECURITY_DISABLE 0xF6 + +//Important ATA IDENTIFY Data Structure values +//As per ATA Spec +#define IDE_SECURITY_SUPPORTED 0x0001 +#define IDE_SECURITY_ENABLED 0x0002 +#define IDE_SECURITY_PASSWORD_SET 0x0004 +#define IDE_SECURITY_FROZEN 0x0008 +#define IDE_SECURITY_COUNT_EXPIRED 0x0010 +#define IDE_SECURITY_LEVEL_MAX 0x0100 + + + + +// Registers +#define IDE_DATA_REGISTER 0x01F0 +#define IDE_ERROR_REGISTER 0x01F1 +#define IDE_FEATURE_REG IDE_ERROR_REGISTER +#define IDE_SECTOR_COUNT_REGISTER 0x01F2 +#define IDE_SECTOR_NUMBER_REGISTER 0x01F3 +#define IDE_CYLINDER_LOW_REGISTER 0x01F4 +#define IDE_CYLINDER_HIGH_REGISTER 0x01F5 +#define IDE_DRIVE_HEAD_REGISTER 0x01F6 +#define IDE_STATUS_REGISTER 0x01F7 +#define IDE_COMMAND_REGISTER 0x01F7 + +//Drives +#define IDE_DRIVE_0 0xa0 +#define IDE_DRIVE_1 0xb0 + +// Commands +#define IDE_COMMAND_IDENTIFY_DRIVE 0xEC +#define IDE_COMMAND_SEEK 0x70 +#define IDE_COMMAND_READ_SECTORS 0x21 +#define IDE_COMMAND_READ_BUFFER 0xE4 +#define IDE_COMMAND_WRITE_SECTORS 0x30 +#define IDE_COMMAND_WRITE_BUFFER 0xE8 +#define IDE_COMMAND_DIAGNOSTIC 0x90 +#define IDE_COMMAND_ATAPI_IDENT_DRIVE 0xA1 + +// Results words from Identify Drive Request +#define IDE_INDENTIFY_NUM_CYLINDERS 0x01 +#define IDE_INDENTIFY_NUM_HEADS 0x03 +#define IDE_INDENTIFY_NUM_BYTES_TRACK 0x04 +#define IDE_INDENTIFY_NUM_BYTES_SECTOR 0x05 +#define IDE_INDENTIFY_NUM_SECTORS_TRACK 0x06 + + +// bits of Status Register +#define IDE_STATUS_DRIVE_BUSY 0x80 +#define IDE_STATUS_DRIVE_READY 0x40 +#define IDE_STATUS_DRIVE_WRITE_FAULT 0x20 +#define IDE_STATUS_DRIVE_SEEK_COMPLETE 0x10 +#define IDE_STATUS_DRIVE_DATA_REQUEST 0x08 +#define IDE_STATUS_DRIVE_CORRECTED_DATA 0x04 +#define IDE_STATUS_DRIVE_INDEX 0x02 +#define IDE_STATUS_DRIVE_ERROR 0x01 + +// Return codes from various IDE_* functions +#define IDE_ERROR_NO_ERROR 0 +#define IDE_ERROR_BAD_DRIVE -1 +#define IDE_ERROR_INVALID_BLOCK -2 +#define IDE_ERROR_DRIVE_ERROR -3 + +#define LOW_BYTE(x) (x & 0xff) +#define HIGH_BYTE(x) ((x >> 8) & 0xff) + + + + +class XKHDD +{ +private: + +public: + + + //IDE ATA Input Registers Structure + typedef struct IP_IDE_REG + { + BYTE bFeaturesReg; // Used for specifying SMART "commands". + BYTE bSectorCountReg; // IDE sector count register + BYTE bSectorNumberReg; // IDE sector number register + BYTE bCylLowReg; // IDE low order cylinder value + BYTE bCylHighReg; // IDE high order cylinder value + BYTE bDriveHeadReg; // IDE drive/head register + BYTE bCommandReg; // Actual IDE command. + BYTE bReserved; // reserved for future use. Must be zero. + }; + typedef IP_IDE_REG* LPIP_IDE_REG; + + //IDE ATA Output Registers Structure + typedef struct OP_IDE_REG + { + BYTE bErrorReg; + BYTE bSectorCountReg; + BYTE bSectorNumberReg; + BYTE bCylLowReg; + BYTE bCylHighReg; + BYTE bDriveHeadReg; + BYTE bStatusReg; + }; + typedef OP_IDE_REG* LPOP_IDE_REG; + + //Our own object for issuing commands.. + //Includes in/ou register objects and 1 Sector of HDD Data + typedef struct ATA_COMMAND_OBJ + { + IP_IDE_REG IPReg; + OP_IDE_REG OPReg; + BYTE DATA_BUFFER[512]; + ULONG DATA_BUFFSIZE; + }; + typedef ATA_COMMAND_OBJ* LPATA_COMMAND_OBJ; + //Default Constructor/Destructor.. + XKHDD(); + virtual ~XKHDD(void); + + static BOOL GetATAIdentity(WORD IDEPort, UCHAR* IDEData); + + //This is the Function for Sending ATA Commands to the HDD.. + static BOOL SendATACommand(WORD IDEPort, LPATA_COMMAND_OBJ ATACommandObj, UCHAR ReadWrite); + + //Helper Functions to Parse Data from ATA IDENTIFY Command + static void GetIDEModel(UCHAR* IDEData, LPSTR ModelString, LPDWORD StrLen); + static void GetIDESerial(UCHAR* IDEData, LPSTR SerialString, LPDWORD StrLen); + static void GetIDEFirmWare(UCHAR* IDEData, LPSTR SerialString, LPDWORD StrLen); + static WORD GetIDESecurityStatus(UCHAR* IDEData); + + static WORD GetIDENumOfCyls(UCHAR* IDEData); + static WORD GetIDENumOfHeads(UCHAR* IDEData); + static WORD GetIDESecPerTrack(UCHAR* IDEData); + static WORD GetATABefehle(UCHAR* IDEData, BYTE IDEOffset); + + static int CleanATAData(unsigned char *dst, unsigned char *src, int len); + + //Given a XBOX HDDKey and ATA Identify data structure, this function calucates + //Password the xbox will use when trying to unlock a drive.. + static void GenerateHDDPwd(UCHAR* HDDKey, UCHAR* IDEData, UCHAR* HDDPass); + + + static BYTE GetHddSmartTemp(UCHAR* IDEData); + + +}; +#endif diff --git a/include/System/XKUtils/XKRC4.h b/include/System/XKUtils/XKRC4.h new file mode 100644 index 0000000..dc0bb0e --- /dev/null +++ b/include/System/XKUtils/XKRC4.h @@ -0,0 +1,103 @@ +/* +********************************** +********************************** +** BROUGHT TO YOU BY: ** +********************************** +********************************** +** ** +** [TEAM ASSEMBLY] ** +** ** +** www.team-assembly.com ** +** ** +****************************************************************************************************** +* This is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 2 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +****************************************************************************************************** + + +******************************************************************************************************** +** XKRC4.H - General RC4 Encryption Class' Header +******************************************************************************************************** +** +** This is the Class Header, see the .CPP file for more comments and implementation details. +** +******************************************************************************************************** + + +******************************************************************************************************** +** CREDITS: +******************************************************************************************************** +** SPEEDBUMP: +** --------- +** My utmost greatfullness and admiration goes towards SpeedBump for all his hard work.. +** I used most of his code and converted to C++ objects etc.. +** +** XBOX-LINUX TEAM: +** --------------- +** Wow, you guys are awsome !! I bow down to your greatness !! +** REFERENCE URL: http://xbox-linux.sourceforge.net +** +******************************************************************************************************** + +UPDATE LOG: +-------------------------------------------------------------------------------------------------------- +Date: 07/05/2006 +By: friedgold +Reason: OpenXDK Version +-------------------------------------------------------------------------------------------------------- +Date: 02/18/2003 +By: UNDEAD [team-assembly] +Reason: Prepared 0.2 for Public Release +-------------------------------------------------------------------------------------------------------- +Date: 01/06/2003 +By: UNDEAD [team-assembly] +Reason: Prepared for Public Release +-------------------------------------------------------------------------------------------------------- + +*/ +#ifndef __XKRC4_H__ +#define __XKRC4_H__ +#if defined (_WINDOWS) + #include // MFC core and standard components +#elif defined (ENABLE_XBOX) +extern "C" { +#include +#include +} +#else + #error ERR: Have to Define _WINDOWS or ENABLE_XBOX !! +#endif + +class XKRC4 +{ +protected: + void swap_byte(UCHAR* a, UCHAR* b); + +public: + struct RC4KEY + { + UCHAR state[256]; + UCHAR x; + UCHAR y; + }; + + XKRC4(void); + virtual ~XKRC4(void); + + void InitRC4Key(UCHAR* pRC4KeyData, int KeyLen, RC4KEY* pRC4Key); + void RC4EnDecrypt(UCHAR* pData, int DataLen, RC4KEY* pRC4key); + + +}; +#endif diff --git a/include/System/XKUtils/XKSHA1.h b/include/System/XKUtils/XKSHA1.h new file mode 100644 index 0000000..2ce4ea7 --- /dev/null +++ b/include/System/XKUtils/XKSHA1.h @@ -0,0 +1,140 @@ +/* +********************************** +********************************** +** BROUGHT TO YOU BY: ** +********************************** +********************************** +** ** +** [TEAM ASSEMBLY] ** +** ** +** www.team-assembly.com ** +** ** +****************************************************************************************************** +* This is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 2 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +****************************************************************************************************** + + +******************************************************************************************************** +** XKSHA1.H - General SHA1 and HMAC_SHA1 Class' Header +******************************************************************************************************** +** +** This is the Class Header, see the .CPP file for more comments and implementation details. +** +** This file implements the Secure Hashing Algorithm 1 as +** defined in FIPS PUB 180-1 published April 17, 1995. +** +** +** Added Funcionality to NOT require the KEY when doing HMAC_SHA1 hashes +** as per xbox-Linux groups "Fridaym 13th Middle Message Hack" +** +******************************************************************************************************** + + +******************************************************************************************************** +** CREDITS: +******************************************************************************************************** +** SPEEDBUMP: +** My utmost greatfullness and admiration goes towards SpeedBump for all his hard work.. +** I used most of his code and converted to C++ objects etc.. +** +** XBOX-LINUX TEAM: +** --------------- +** In particular "Franz", Wow, you guys are awsome !! I bow down to your greatness !! +** The "Friday 13th" Middle Message Hack really saved our butts !! +** REFERENCE URL: http://xbox-linux.sourceforge.net +** +******************************************************************************************************** + +UPDATE LOG: +-------------------------------------------------------------------------------------------------------- +Date: 07/05/2006 +By: friedgold +Reason: OpenXDK Version +-------------------------------------------------------------------------------------------------------- +Date: 02/18/2003 +By: UNDEAD [team-assembly] +Reason: Prepared 0.2 for Public Release +-------------------------------------------------------------------------------------------------------- +Date: 01/06/2003 +By: UNDEAD [team-assembly] +Reason: Prepared for Public Release +-------------------------------------------------------------------------------------------------------- + +*/ +#ifndef __XKSHA1_H__ +#define __XKSHA1_H__ +#if defined (_WINDOWS) + #include // MFC core and standard components +#elif defined (ENABLE_XBOX) +extern "C" { +#include +#include +} +#else + #error ERR: Have to Define _WINDOWS or ENABLE_XBOX !! +#endif + +typedef UINT UINT32; +#define SHA1HashSize 20 +#define SHA1CircularShift(bits,word) \ + (((word) << (bits)) | ((word) >> (32-(bits)))) + +class XKSHA1 +{ + struct SHA1Context + { + UINT32 Intermediate_Hash[SHA1HashSize / 4]; /* Message Digest */ + + UINT32 Length_Low; /* Message length in bits */ + UINT32 Length_High; /* Message length in bits */ + + DWORD Message_Block_Index; /* Index into message block array */ + UCHAR Message_Block[64]; /* 512-bit message blocks */ + + int Computed; /* Is the digest computed? */ + int Corrupted; /* Is the message digest corrupted? */ + }; + + enum + { + shaSuccess = 0, + shaNull, /* Null pointer parameter */ + shaInputTooLong, /* input data too long */ + shaStateError /* called Input after Result */ + }; + +public: + XKSHA1(void); + ~XKSHA1(void); + + void HMAC_SHA1(UCHAR* result, UCHAR* key, int key_length, UCHAR* text1, int text1_length, UCHAR* text2, int text2_length); + void quick_SHA1( UCHAR* SHA1_result, ... ); + + //Skip the Key used from eeprom.. Kudos franz@caos.at + void XBOX_HMAC_SHA1(int version, UCHAR* result, ... ); + +private: + int SHA1Reset(SHA1Context*); + int SHA1Input(SHA1Context*, const UCHAR* , unsigned int); + int SHA1Result(SHA1Context*, UCHAR Message_Digest[SHA1HashSize]); + void SHA1ProcessMessageBlock(SHA1Context* context); + void SHA1PadMessage(SHA1Context* context); + + //Skip the Key used from eeprom.. Kudos franz@caos.at + int HMAC1Reset(int version, SHA1Context *context); + int HMAC2Reset(int version, SHA1Context *context); + +}; +#endif diff --git a/include/System/XKUtils/XKStrings.h b/include/System/XKUtils/XKStrings.h new file mode 100644 index 0000000..d27259b --- /dev/null +++ b/include/System/XKUtils/XKStrings.h @@ -0,0 +1,45 @@ +/* +****************************************************************************************************** +* This is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 2 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +****************************************************************************************************** + +EEPROM string helper functions +*/ + +#ifndef __XKSTRINGS_H__ +#define __XKSTRINGS_H__ + +extern "C" { +#include +#include +} +#include "XKUtils.h" +#include "XKEEPROM.h" + +class XKStrings +{ + public: + static const char *AVPackToString(XKUtils::AV_PACK av); + static const char *TrayStateToString(XKUtils::TRAY_STATE state); + static const char *XBOXVersionToString(XKUtils::XBOX_VERSION version); + static const char *EEPROMXBOXVersionToString(XKEEPROM::XBOX_VERSION version); + static const char *DVDZoneToString(XKEEPROM::DVD_ZONE zone); + static const char *XBERegionToString(XKEEPROM::XBE_REGION region); + static const char *VideoStandardToString(XKEEPROM::VIDEO_STANDARD std); + static const char *VideoEncoderToString(XKUtils::VIDEO_ENCODER_TYPE encoder); + static const char *LanguageToString(XKEEPROM::LANGUAGE lang); +}; + +#endif diff --git a/include/System/XKUtils/XKUtils.h b/include/System/XKUtils/XKUtils.h new file mode 100644 index 0000000..626d6e4 --- /dev/null +++ b/include/System/XKUtils/XKUtils.h @@ -0,0 +1,296 @@ +/* +********************************** +********************************** +** BROUGHT TO YOU BY: ** +********************************** +********************************** +** ** +** [TEAM ASSEMBLY] ** +** ** +** www.team-assembly.com ** +** ** +****************************************************************************************************** +* This is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 2 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +****************************************************************************************************** + + +******************************************************************************************************** +** XKUTILS.H - XBOX Utility Class' Header +******************************************************************************************************** +** +** This is the Class Header, see the .CPP file for more comments and implementation details. +** +******************************************************************************************************** + +******************************************************************************************************** +** CREDITS: +******************************************************************************************************** +** XBOX-LINUX TEAM: +** --------------- +** Wow, you guys are awsome !! I bow down to your greatness !! +** REFERENCE URL: http://xbox-linux.sourceforge.net +** +******************************************************************************************************** + +UPDATE LOG: +-------------------------------------------------------------------------------------------------------- +Date: 07/05/2006 +By: friedgold +Reason: OpenXDK Version +-------------------------------------------------------------------------------------------------------- +Date: 02/18/2003 +By: UNDEAD [team-assembly] +Reason: Prepared 0.2 for Public Release +-------------------------------------------------------------------------------------------------------- + +*/ +#ifndef __XKUTILS_H__ +#define __XKUTILS_H__ +#if defined (ENABLE_XBOX) + //This complete file is only supported for XBOX.. +extern "C" { +#include +#include +} + +class XKUtils +{ +public: + + //Enum for Devices on SMBus + enum SMBUS_DEVICES + { + SMBDEV_PIC16L = 0x20, + SMBDEV_VIDEO_ENCODER_CONEXANT = 0x8a, + SMBDEV_VIDEO_ENCODER_FOCUS = 0xd4, + SMBDEV_VIDEO_ENCODER_XCALIBUR = 0xe0, + SMBDEV_TEMP_MONITOR = 0x98, + SMBDEV_EEPROM = 0xA8 + }; + + // AV Pack Type definitions + enum AV_PACK + { + AV_PACK_SCART = 0x00, + AV_PACK_HDTV = 0x01, + AV_PACK_VGA = 0x02, + AV_PACK_RFU = 0x03, + AV_PACK_SVideo = 0x04, + AV_PACK_Undefined = 0x05, + AV_PACK_Standard = 0x06, + AV_PACK_Missing = 0x07 + }; + + //Commands that can be sent to the PIC + enum PIC16L_CMD + { + PIC16L_CMD_PIC_VERSION = 0x01, + PIC16L_CMD_POWER = 0x02, + PIC16L_CMD_TRAY = 0x03, + PIC16L_CMD_AV_PACK = 0x04, + PIC16L_CMD_FAN_MODE = 0x05, + PIC16L_CMD_FAN_SPEED = 0x06, + PIC16L_CMD_LED_MODE = 0x07, + PIC16L_CMD_LED_REGISTER = 0x08, + PIC16L_CMD_CPU_TEMPERATURE = 0x09, + PIC16L_CMD_BOARD_TEMPERATURE = 0x0A, + PIC16L_CMD_EJECT = 0x0C, + PIC16L_CMD_READ_FAN_SPEED = 0x10, + PIC16L_CMD_INTERRUPT_REASON = 0x11, + PIC16L_CMD_RESET_ON_EJECT = 0x19, + PIC16L_CMD_SCRATCH_REGISTER = 0x1B + }; + + //Commands that can be sent to PIC fan mode command + enum + { + FAN_MODE_SUBCMD_AUTO = 0x00, + FAN_MODE_SUBCMD_MANUAL = 0x01 + }; + + //Sub commands for the PIC Power command + enum POWER_SUBCMD + { + POWER_SUBCMD_RESET = 0x01, + POWER_SUBCMD_CYCLE = 0x40, + POWER_SUBCMD_POWER_OFF = 0x80 + + }; + //Commands that can be sent to the Video Encoder + enum VIDEO_ENCODER_CMD + { + VIDEO_ENCODER_CMD_DETECT = 0x00 + }; + + //Values For Video Encoder + enum VIDEO_ENCODER_TYPE + { + VIDEO_ENCODER_UNKNOWN = 0, + VIDEO_ENCODER_CONEXANT = 1, + VIDEO_ENCODER_FOCUS = 2, + VIDEO_ENCODER_XCALIBUR = 3 + }; + + //Sub Command for the PIC LED command + enum LED_MODE_SUBCMD + { + LED_MODE_SUBCMD_DEFAULT_MODE = 0x00, + LED_MODE_SUBCMD_CUSTOM_MODE = 0x01 + }; + + //Sub Command for the PIC LED command + enum LED_REGISTER_CYCLE + { + LED_REGISTER_CYCLE3_GREEN = 0x01, + LED_REGISTER_CYCLE2_GREEN = 0x02, + LED_REGISTER_CYCLE1_GREEN = 0x04, + LED_REGISTER_CYCLE0_GREEN = 0x08, + + LED_REGISTER_CYCLE3_RED = 0x10, + LED_REGISTER_CYCLE2_RED = 0x20, + LED_REGISTER_CYCLE1_RED = 0x40, + LED_REGISTER_CYCLE0_RED = 0x80, + + LED_REGISTER_CYCLE3_ORANGE = 0x11, + LED_REGISTER_CYCLE2_ORANGE = 0x22, + LED_REGISTER_CYCLE1_ORANGE = 0x44, + LED_REGISTER_CYCLE0_ORANGE = 0x88 + + }; + + + //Sub commands for the PIC EJECT command + enum EJECT_SUBCMD + { + EJECT_SUBCMD_EJECT = 0x00, + EJECT_SUBCMD_LOAD = 0x01 + }; + + //Reason for interrupt + enum INTERRUPT_REASON_BITVALUE + { + INTERRUPT_REASON_BITVALUE_POWER_BUTTON = 0x01, + INTERRUPT_REASON_BITVALUE_AV_REMOVED = 0x10, + INTERRUPT_REASON_BITVALUE_EJECT_BUTTON = 0x20 + }; + + //subcommands for Reset on Eject PIC command + enum RESET_ON_EJECT_SUBCMD + { + RESET_ON_EJECT_SUBCMD_ENABLE = 0x00, + RESET_ON_EJECT_SUBCMD_DISABLE = 0x01 + + }; + + //Scratch register values.. + enum SCRATCH_REGISTER_BITVALUE + { + SCRATCH_REGISTER_BITVALUE_EJECT_AFTER_BOOT = 0x01, + SCRATCH_REGISTER_BITVALUE_DISPLAY_ERROR = 0x02, + SCRATCH_REGISTER_BITVALUE_NO_ANIMATION = 0x04, + SCRATCH_REGISTER_BITVALUE_RUN_DASHBOARD = 0x08 + }; + + // Sub commands for the AMD 1032 temperature sensor + enum TEMP_MONITOR + { + TEMP_MONITOR_HIGH_BYTE = 0x01, + TEMP_MONITOR_LOW_BYTE = 0x10, + }; + + //Tray state values + enum TRAY_STATE + { + TRAY_STATE_NOT_READY = 0x00, + TRAY_STATE_OPEN = 0x10, + TRAY_STATE_OPENING = 0x20, + TRAY_STATE_CLOSED_NO_MEDIA = 0x40, + TRAY_STATE_CLOSED_MEDIA_PRESENT = 0x60 + }; + + //Xbox versions + enum XBOX_VERSION + { + XBOX_VERSION_1_0 = 0, + XBOX_VERSION_1_1 = 1, + XBOX_VERSION_1_2_OR_1_3 = 2, + XBOX_VERSION_1_4 = 3, + XBOX_VERSION_1_6 = 4, + XBOX_VERSION_DEVKIT = 5, + XBOX_VERSION_DEVKIT_GREEN = 6, + XBOX_VERSION_UNKNOWN = 7 + }; + + XKUtils(); + virtual ~XKUtils(); + + static void DVDEjectLoadTray(); + static void DVDEjectTray(); + static void DVDLoadTray(); + static void DVDDisableEjectReset(); + static void DVDEnableEjectReset(); + static LONG MountDiskC(); + static LONG MountDiskD(); + static LONG MountDiskE(); + static LONG MountDiskF(); + static void MountAllDisks(); + static LONG UnMountDiskC(); + static LONG UnMountDiskD(); + static LONG UnMountDiskE(); + static LONG UnMountDiskF(); + static void UnMountAllDisks(); + + static LONG MountDevice(LPSTR sSymbolicLinkName, LPSTR sDeviceName); + static LONG UnMountDevice(LPSTR sSymbolicLinkName); + + static void WriteEEPROMToXBOX(BYTE *EEPROMDATA, UCHAR STARTPOS, UCHAR ENDPOS); + static bool ReadEEPROMFromXBOX(BYTE *EEPROMDATA, UCHAR STARTPOS, UCHAR ENDPOS); + + static void XBOXRebootToDash(); + static void XBOXReset(); + static void XBOXPowerOff(); + static void XBOXPowerCycle(); + /* Set the LED Status from a bitwise OR of the LED_REGISTER_CYCLE + values above */ + static void SetXBOXLEDStatus(UCHAR LEDStatus); + /* Set the LED Status from a string in the form "ABCD" where ABCD are + the states in the four phases the LED passes through. The possible + states are: 'r' (red), 'g' (green), 'o' (orange) or 'x' (off).*/ + static void SetXBOXLEDStatus(char *s); + + static int GetFanSpeed(); + static void SetFanSpeed(int speed); + static void SetAutomaticFanSpeed(); + + static int GetBoardTemp(); + /* Read the CPU temperature from the PIC */ + static int PICGetCPUTemp(); + /* Read the CPU temperature. */ + static double GetCPUTemp(int version); + /* Read the CPU temperature, autodetecting the Xbox version */ + static double GetCPUTemp(); + + static AV_PACK GetAVPack(); + static TRAY_STATE GetTrayState(); + static VIDEO_ENCODER_TYPE GetVideoEncoderType(); + /* Reads the PIC Version string to version. At least 4 bytes must be allocated for the version string. */ + static bool GetPICVersion(char *version); + static XBOX_VERSION GetXBOXVersion(); + + //static void GetMODCHIPVersion(); + +}; +#endif +#endif diff --git a/include/System/XKUtils/flashtypes.h b/include/System/XKUtils/flashtypes.h new file mode 100644 index 0000000..bd5645e --- /dev/null +++ b/include/System/XKUtils/flashtypes.h @@ -0,0 +1,175 @@ +/** + * Raincoat Flash Types. + * Copyright (C) Thomas "ShALLaX" Pedley (me@shallax.com) + * + * Derived from ShepD's Unauthorised FlashBIOS. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + + // Please keep these in order of manID, prodID. + + { 0x01, 0x0c, "AMD_Am29DL400BT", 0x80000 }, + { 0x01, 0x0f, "AMD_Am29DL400BB", 0x80000 }, + { 0x01, 0x23, "AMD_Am29F400BT", 0x80000 }, + { 0x01, 0x34, "AMD_Am29F002BB/NBB", 0x40000 }, + { 0x01, 0x37, "AMD_Am29LV008BB", 0x100000 }, + { 0x01, 0x38, "AMD_Am29LV080B", 0x100000 }, + { 0x01, 0x3b, "AMD_Am29LV200BT", 0x40000 }, + { 0x01, 0x3e, "AMD_Am29LV008BT", 0x100000 }, + { 0x01, 0x40, "AMD_Am29LV002BT", 0x40000 }, + { 0x01, 0x4a, "AMD_Am29DL800BT", 0x100000 }, + { 0x01, 0x4f, "AMD_Am29LV040B", 0x80000 }, + { 0x01, 0x51, "AMD_Am29F200BT", 0x40000 }, + { 0x01, 0x57, "AMD_Am29F200BB", 0x40000 }, + { 0x01, 0x58, "AMD_Am29F800BB", 0x100000 }, + { 0x01, 0x5b, "AMD_Am29LV800BB/DB", 0x100000 }, + { 0x01, 0x77, "AMD_Am29F004BT", 0x80000 }, + { 0x01, 0x7b, "AMD_Am29F004BB", 0x80000 }, + { 0x01, 0xa4, "AMD_Am29F040B", 0x80000 }, + { 0x01, 0xab, "AMD_Am29F400BB", 0x80000 }, + { 0x01, 0xad, "XECUTER3", 0x200000 }, + { 0x01, 0xb0, "AMD_Am29F002BT/NBT", 0x40000 }, + { 0x01, 0xb5, "AMD_Am29LV004BT", 0x80000 }, + { 0x01, 0xb6, "AMD_Am29LV004BB", 0x80000 }, + { 0x01, 0xb9, "AMD_Am29LV400BT", 0x80000 }, + { 0x01, 0xba, "AMD_Am29LV400BB", 0x80000 }, + { 0x01, 0xbf, "AMD_Am29LV200BB", 0x40000 }, + { 0x01, 0xc2, "AMD_Am29LV002BB", 0x40000 }, + { 0x01, 0xcb, "AMD_Am29DL800BB", 0x100000 }, + { 0x01, 0xd5, "AMD_Am29F080B", 0x100000 }, + { 0x01, 0xd6, "AMD_Am29F800BT", 0x100000 }, + { 0x01, 0xda, "AMD_Am29LV800BT/DT", 0x100000 }, + { 0x04, 0x0c, "Fujitsu_MBM29DL400TC", 0x80000 }, + { 0x04, 0x0f, "Fujitsu_MBM29DL400BC", 0x80000 }, + { 0x04, 0x23, "Fujitsu_MBM29F400TC", 0x80000 }, + { 0x04, 0x34, "Fujitsu_MBM29F002BC", 0x40000 }, + { 0x04, 0x37, "Fujitsu_MBM29LV008BA", 0x100000 }, + { 0x04, 0x38, "Fujitsu_MBM29LV080A", 0x100000 }, + { 0x04, 0x3b, "Fujitsu_MBM29LV200TC", 0x40000 }, + { 0x04, 0x3e, "Fujitsu_MBM29LV008TA", 0x100000 }, + { 0x04, 0x40, "Fujitsu_MBM29LV002TC", 0x40000 }, + { 0x04, 0x4a, "Fujitsu_MBM29DL800TA", 0x100000 }, + { 0x04, 0x51, "Fujitsu_MBM29F200TC", 0x40000 }, + { 0x04, 0x57, "Fujitsu_MBM29F200BC", 0x40000 }, + { 0x04, 0x58, "Fujitsu_MBM29F800BA", 0x100000 }, + { 0x04, 0x5b, "Fujitsu_MBM29LV800BA/BE", 0x100000 }, + { 0x04, 0x77, "Fujitsu_MBM29F004TC", 0x80000 }, + { 0x04, 0x7b, "Fujitsu_MBM29F004BC", 0x80000 }, + { 0x04, 0xa4, "Fujitsu_MBM29F040C", 0x80000 }, + { 0x04, 0xab, "Fujitsu_MBM29F400BC", 0x80000 }, + { 0x04, 0xb0, "Fujitsu_MBM29F002TC", 0x40000 }, + { 0x04, 0xb5, "Fujitsu_MBM29LV004TC", 0x80000 }, + { 0x04, 0xb6, "Fujitsu_MBM29LV004BC", 0x80000 }, + { 0x04, 0xb9, "Fujitsu_MBM29LV400TC", 0x80000 }, + { 0x04, 0xba, "Fujitsu_MBM29LV400BC", 0x80000 }, + { 0x04, 0xbf, "Fujitsu_MBM29LV200BC", 0x40000 }, + { 0x04, 0xc2, "Fujitsu_MBM29LV002BC", 0x40000 }, + { 0x04, 0xcb, "Fujitsu_MBM29DL800BA", 0x100000 }, + { 0x04, 0xd5, "Fujitsu_MBM29F080A", 0x100000 }, + { 0x04, 0xd6, "Fujitsu_MBM29F800TA", 0x100000 }, + { 0x04, 0xda, "Fujitsu_MBM29LV800TA/TE", 0x100000 }, + { 0x20, 0x34, "ST_M29F002B/BB", 0x40000 }, + { 0x20, 0x58, "ST_M29F800DB", 0x100000 }, + { 0x20, 0xb0, "ST_M29F002T/NT/BT/BNT", 0x40000 }, + { 0x20, 0xd3, "ST_M29F200BT", 0x40000 }, + { 0x20, 0xd4, "ST_M29F200BB", 0x40000 }, + { 0x20, 0xd5, "ST_M29F400T/BT", 0x80000 }, + { 0x20, 0xd6, "ST_M29F400B/BB", 0x80000 }, + { 0x20, 0xe2, "ST_M29F040_series", 0x80000 }, + { 0x20, 0xec, "ST_M29F800DT", 0x100000 }, + { 0x20, 0xf1, "ST_M29F080_series", 0x100000 }, + { 0x37, 0x0d, "AMIC_A29002U/290021U", 0x40000 }, + { 0x37, 0x0e, "AMIC_A29800T", 0x100000 }, + { 0x37, 0x1a, "AMIC_A29L008T/A29L800T", 0x100000 }, + { 0x37, 0x31, "AMIC_A29400U/294001U", 0x80000 }, + { 0x37, 0x34, "AMIC_A29L004T/A29L400T", 0x80000 }, + { 0x37, 0x86, "AMIC_A29040A", 0x80000 }, + { 0x37, 0x8c, "AMIC_A29002T/290021T", 0x40000 }, + { 0x37, 0x8f, "AMIC_A29800U", 0x100000 }, + { 0x37, 0x92, "AMIC_A29L040", 0x80000 }, + { 0x37, 0x9b, "AMIC_A29L008U/A29L800U", 0x100000 }, + { 0x37, 0xb0, "AMIC_A29400T/294001T", 0x80000 }, + { 0x37, 0xb5, "AMIC_A29L004U/A29L400U", 0x80000 }, + { 0x89, 0xa2, "Sharp_LH28F008SA_series", 0x100000 }, + { 0x89, 0xa6, "Sharp_LH28F008SC_series", 0x100000 }, + { 0xad, 0x23, "Hynix_HY29F400T/AT", 0x80000 }, + { 0xad, 0x58, "Hynix_HY29F800B/AB", 0x100000 }, + { 0xad, 0x5b, "Hynix_HY29LV800B", 0x100000 }, + { 0xad, 0xa4, "Hynix_HY29F040A", 0x80000 }, + { 0xad, 0xab, "Hynix_HY29F400B/AB", 0x80000 }, + { 0xad, 0xb0, "Hynix_HY29F002", 0x40000 }, + { 0xad, 0xb9, "Hynix_HY29LV400T", 0x80000 }, + { 0xad, 0xba, "Hynix_HY29LV400B", 0x80000 }, + { 0xad, 0xd5, "Hynix_HY29F080", 0x100000 }, + { 0xad, 0xd6, "Hynix_HY29F800T/AT", 0x100000 }, + { 0xad, 0xda, "Hynix_HY29LV800T", 0x100000 }, + { 0xb0, 0x4b, "Sharp_LH28F800BVxx-BTL_series", 0x100000 }, + { 0xb0, 0x4c, "Sharp_LH28F800BVxx-TV_series", 0x100000 }, + { 0xb0, 0x4d, "Sharp_LH28F800BVxx-BV_series", 0x100000 }, + { 0xb0, 0xc9, "Sharp_LHF00L02/L06/L07", 0x100000 }, + { 0xb0, 0xcf, "Sharp_LHF00L03/L04/L05", 0x100000 }, + { 0xb0, 0xec, "Sharp_LH28F008BJxx-PT_series", 0x100000 }, + { 0xb0, 0xed, "Sharp_LH28F008BJxx-PB_series", 0x100000 }, + { 0xbf, 0x10, "SST_29EE020", 0x40000 }, + { 0xbf, 0x12, "SST_29LE020/29VE020", 0x40000 }, + { 0xbf, 0x13, "SST_29SF040", 0x80000 }, + { 0xbf, 0x14, "SST_29VF040", 0x80000 }, + { 0xbf, 0x1b, "SST_49LF003A", 0x60000 }, + { 0xbf, 0x1c, "SST_49LF030A", 0x60000 }, + { 0xbf, 0x51, "SST_49LF040", 0x80000 }, + { 0xbf, 0x52, "SST_49LF020A", 0x40000 }, + { 0xbf, 0x57, "SST_49LF002A", 0x40000 }, + { 0xbf, 0x5a, "SST_49LF008A", 0x100000 }, + { 0xbf, 0x5b, "SST_49LF080A", 0x100000 }, + { 0xbf, 0x60, "SST_49LF004A/B", 0x80000 }, + { 0xbf, 0x61, "SST_49LF020", 0x40000 }, + { 0xbf, 0xb6, "SST_39SF020A", 0x40000 }, + { 0xbf, 0xb7, "SST_39SF040", 0x80000 }, + { 0xbf, 0xd6, "SST_39LF020/39VF020", 0x40000 }, + { 0xbf, 0xd7, "SST_39LF040/39VF040", 0x80000 }, + { 0xbf, 0xd8, "SST_39LF080/39VF080/39VF088", 0x100000 }, + { 0xc2, 0x23, "Macronix_MX29F400T", 0x80000 }, + { 0xc2, 0x34, "Macronix_MX29F002B/NB", 0x40000 }, + { 0xc2, 0x36, "Macronix_MX29F022T/NT", 0x40000 }, + { 0xc2, 0x37, "Macronix_MX29LV008B", 0x100000 }, + { 0xc2, 0x38, "Macronix_MX29LV081", 0x100000 }, + { 0xc2, 0x3e, "Macronix_MX29LV008T", 0x100000 }, + { 0xc2, 0x45, "Macronix_MX29F004T", 0x80000 }, + { 0xc2, 0x46, "Macronix_MX29F004B", 0x80000 }, + { 0xc2, 0x4f, "Macronix_MX29LV040", 0x80000 }, + { 0xc2, 0x51, "Macronix_MX29F200T", 0x40000 }, + { 0xc2, 0x57, "Macronix_MX29F200B", 0x40000 }, + { 0xc2, 0x58, "Macronix_MX29F800B", 0x100000 }, + { 0xc2, 0x5b, "Macronix_MX29LV800B", 0x100000 }, + { 0xc2, 0xa4, "Macronix_MX29F040", 0x80000 }, + { 0xc2, 0xab, "Macronix_MX29F400B", 0x80000 }, + { 0xc2, 0xb0, "Macronix_MX29F002T/NT", 0x40000 }, + { 0xc2, 0xb5, "Macronix_MX29LV004T", 0x80000 }, + { 0xc2, 0xb6, "Macronix_MX29LV004B", 0x80000 }, + { 0xc2, 0xb9, "Macronix_MX29LV400T", 0x80000 }, + { 0xc2, 0xba, "Macronix_MX29LV400B", 0x80000 }, + { 0xc2, 0xd5, "Macronix_MX29F080", 0x100000 }, + { 0xc2, 0xd6, "Macronix_MX29F800T", 0x100000 }, + { 0xc2, 0xda, "Macronix_MX29LV800T", 0x100000 }, + { 0xda, 0x0b, "Winbond_W49F002U", 0x40000 }, + { 0xda, 0x3d, "Winbond_W39V040A", 0x80000 }, + { 0xda, 0x45, "Winbond_W29C020", 0x40000 }, + { 0xda, 0x46, "Winbond_W29C040", 0x40000 }, + { 0xda, 0x8c, "Winbond_W49F020", 0x40000 }, + { 0xda, 0xb0, "Winbond_W49V002A", 0x40000 }, + { 0xda, 0xb5, "Winbond_W39L020", 0x40000 }, + { 0xda, 0xb6, "Winbond_W39L040", 0x80000 }, + { 0, 0, "", 0 } // Terminator - dont remove. diff --git a/include/System/Xml/XPath/XPathException.h b/include/System/Xml/XPath/XPathException.h new file mode 100644 index 0000000..f86fdca --- /dev/null +++ b/include/System/Xml/XPath/XPathException.h @@ -0,0 +1,19 @@ +namespace System +{ + namespace Xml + { + namespace XPath + { + /// + /// Provides the exception thrown when an error occurs while processing an XPath expression. + /// + class XPathException : SystemException + { + public: + XPathException(); + XPathException(const char *message); + XPathException(const char *message, Exception &innerException); + }; + } + } +} diff --git a/include/System/Xml/Xsl/XsltException.h b/include/System/Xml/Xsl/XsltException.h new file mode 100644 index 0000000..ff34cef --- /dev/null +++ b/include/System/Xml/Xsl/XsltException.h @@ -0,0 +1,30 @@ +#ifndef _XSLTEXCEPTION_ +#define _XSLTEXCEPTION_ + +#include "../../SystemException.h" + +namespace System +{ + namespace Xml + { + namespace Xsl + { + /// + /// The exception that is thrown when an error occurs while processing an XSLT transformation. + /// + class XsltException : SystemException + { + public: + int LineNumber(); + int LinePosition(); + const char* SourceUri(); + + XsltException(); + XsltException(const char *message); + XsltException(const char *message, Exception &innerException); + }; + } + } +} + +#endif //_XSLTEXCEPTION_ diff --git a/include/System/misc.h b/include/System/misc.h new file mode 100644 index 0000000..4ebd52d --- /dev/null +++ b/include/System/misc.h @@ -0,0 +1,20 @@ +/******************************************************************************/ +/* */ +/* File: misc.h */ +/* Author: bkenwright@xbdev.net */ +/* Desc: Misc functions, making our usb/gamepad code lib independent */ +/* Modified and SSE optimized by Halofreak1990 */ +/* */ +/******************************************************************************/ +#ifndef _MISC_H +#define _MISC_H + +#include + +void Sleep(long timemilliseconds); + +void *memcpy(void *dest, const void *src, size_t count); + +void *malloc(size_t size); + +void *memset(void *s, char c, size_t count); diff --git a/include/Thread.h b/include/Thread.h new file mode 100644 index 0000000..2375a19 --- /dev/null +++ b/include/Thread.h @@ -0,0 +1,61 @@ +/******************************************************** + * Thread.h * + * * + * XFX Thread definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef THREAD_H +#define THREAD_H + +#ifdef ENABLE_XBOX +extern "C" { +#include +} +#endif + +#include "ThreadState.h" +#include "TimeSpan.h" + +namespace System +{ + namespace Threading + { + class Thread + { + int lock_thread_id; + HANDLE system_thread_handle; + PKSTART_ROUTINE callback; + int stack_size; + static ULONG Id; + PULONG suspendCount; + + ThreadState state; + + private: + void Thread_init(); + + public: + //Creates a new instance of the Thread class with the specified callback function, but doesn't start yet. + Thread(PKSTART_ROUTINE callBack); + //Creates a new instance of the Thread class with the specified callback function and stack size, but doesn't start yet. + Thread(PKSTART_ROUTINE callBack, int stackSize); + + void Abort(); + void Interrupt(); + //Returns a value indicating whether the thread is running + int IsAlive(); + //Resumes a previously suspended thread. + void Resume(); + //Set the thread priority, valid values are 0 (Low), 16 (Low_RealTime), 31 (High), 32 (Maximum) + void SetPriority(int priority); + static void Sleep(int millisecondsTimeout); + static void Sleep(TimeSpan timeout); + //Start executing the thread. + void Start(); + //Suspend the thread execution, call Thread::Resume() to resume the thread. + void Suspend(); + }; + } +} + +#endif //THREAD_H diff --git a/include/ThreadState.h b/include/ThreadState.h new file mode 100644 index 0000000..a37ab3b --- /dev/null +++ b/include/ThreadState.h @@ -0,0 +1,30 @@ +/******************************************************** + * ThreadState.h * + * * + * XFX ThreadState enumeration definition file * + * Copyright © Halofreak1990. All Rights Reserved * + ********************************************************/ +#ifndef THREADSTATE_H +#define THREADSTATE_H + +namespace System +{ + namespace Threading + { + enum ThreadState + { + Running = 0x00000000, + StopRequested = 0x00000001, + SuspendRequested = 0x00000002, + Background = 0x00000004, + Unstarted = 0x00000008, + Stopped = 0x00000010, + WaitSleepJoin = 0x00000020, + Suspended = 0x00000040, + AbortRequested = 0x00000080, + Aborted = 0x00000100 + }; + } +} + +#endif //THREADSTATE_H diff --git a/include/Vector2.h b/include/Vector2.h new file mode 100644 index 0000000..b4fc6d7 --- /dev/null +++ b/include/Vector2.h @@ -0,0 +1,102 @@ +/******************************************************** + * Vector2.h * + * * + * XFX Vector2 definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_VECTOR2_ +#define _XFX_VECTOR2_ + +#include + +namespace XFX +{ + struct Matrix; + struct Quaternion; + + /// + /// Defines a vector with two components. + /// + struct Vector2 + { + float X, Y; + static const Vector2 One; + static const Vector2 Zero; + + Vector2(float x, float y); + Vector2(float value); + Vector2(const Vector2 &obj); + Vector2(); + + static Vector2 Add(Vector2 value1, Vector2 value2); + static void Add(Vector2 value1, Vector2 value2, out Vector2 result); + static Vector2 Baricentric(Vector2 value1, Vector2 value2, Vector2 value3, float amount1, float amount2); + static void Baricentric(Vector2 value1, Vector2 value2, Vector2 value3, float amount1, float amount2, out Vector2 result); + static Vector2 CatmullRom(Vector2 value1, Vector2 value2, Vector2 value3, Vector2 value4, float amount); + static void CatmullRom(Vector2 value1, Vector2 value2, Vector2 value3, Vector2 value4, float amount, out Vector2 result); + static Vector2 Clamp(Vector2 value, Vector2 min, Vector2 max); + static void Clamp(Vector2 value, Vector2 min, Vector2 max, out Vector2 result); + static float Distance(Vector2 value1, Vector2 value2); + static void Distance(Vector2 value1, Vector2 value2, out float result); + static float DistanceSquared(Vector2 value1, Vector2 value2); + static void DistanceSquared(Vector2 value1, Vector2 value2, out float result); + static Vector2 Divide(Vector2 value1, float divider); + static void Divide(Vector2 value1, float divider, out Vector2 result); + static Vector2 Divide(Vector2 value1, Vector2 value2); + static void Divide(Vector2 value1, Vector2 value2, out Vector2 result); + static float Dot(Vector2 value1, Vector2 value2); + static void Dot(Vector2 value1, Vector2 value2, out float result); + bool Equals(Vector2 obj); + int GetHashCode(); + static Vector2 Hermite(Vector2 value1, Vector2 tangent1, Vector2 value2, Vector2 tangent2, float amount); + static void Hermite(Vector2 value1, Vector2 tangent1, Vector2 value2, Vector2 tangent2, float amount, out Vector2 result); + float Length(); + float LengthSquared(); + static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount); + static void Lerp(Vector2 value1, Vector2 value2, float amount, out Vector2 result); + static Vector2 Max(Vector2 value1, Vector2 value2); + static void Max(Vector2 value1, Vector2 value2, out Vector2 result); + static Vector2 Min(Vector2 value1, Vector2 value2); + static void Min(Vector2 value1, Vector2 value2, out Vector2 result); + static Vector2 Multiply(Vector2 value, float scaleFactor); + void Multiply(Vector2 value1, float scaleFactor, out Vector2 result); + static Vector2 Multiply(Vector2 value1, Vector2 value2); + void Multiply(Vector2 value1, Vector2 value2, out Vector2 result); + static Vector2 Negate(Vector2 value); + static void Negate(Vector2 value, out Vector2 result); + void Normalize(); + static Vector2 Normalize(Vector2 value); + static void Normalize(Vector2 value, out Vector2 result); + static Vector2 Reflect(Vector2 vector, Vector2 normal); + static void Reflect(Vector2 vector, Vector2 normal, out Vector2 result); + static Vector2 SmoothStep(Vector2 value1, Vector2 value2, float amount); + static void SmoothStep(Vector2 value1, Vector2 value2, float amount, out Vector2 result); + static Vector2 Subtract(Vector2 value1, Vector2 value2); + static void Subtract(Vector2 value1, Vector2 value2, out Vector2 result); + static Vector2 Transform(Vector2 position, Matrix matrix); + static void Transform(Vector2 position, Matrix matrix, out Vector2 result); + static Vector2 Transform(Vector2 position, Quaternion rotation); + static void Transform(Vector2 position, Quaternion rotation, out Vector2 result); + static void Transform(Vector2 sourceArray[], int sourceIndex, Matrix matrix, Vector2 destinationArray[], int destinationIndex, int length); + static void Transform(Vector2 sourceArray[], int sourceIndex, Quaternion rotation, Vector2 destinationArray[], int destinationIndex, int length); + static void Transform(Vector2 sourceArray[], Matrix matrix, Vector2 destinationArray[]); + static void Transform(Vector2 sourceArray[], Quaternion rotation, Vector2 destinationArray[]); + static Vector2 TransformNormal(Vector2 normal, Matrix matrix); + static void TransformNormal(Vector2 normal, Matrix matrix, out Vector2 result); + static void TransformNormal(Vector2 sourceArray[], int sourceIndex, Matrix matrix, Vector2 destinationArray[], int destinationIndex, int length); + static void TransformNormal(Vector2 sourceArray[], Matrix matrix, Vector2 destinationArray[]); + + Vector2 operator-(const Vector2 other); + Vector2 operator-(); + Vector2 operator+(const Vector2 other); + Vector2 operator/(float divider); + Vector2 operator/(const Vector2 other); + bool operator==(const Vector2 other); + bool operator!=(const Vector2 other); + Vector2 operator*(const float scaleFactor); + Vector2 operator*(const Vector2 other); + Vector2 operator=(const Vector2 other); + } ALIGNED; +} + +#endif //_XFX_VECTOR2_ diff --git a/include/Vector3.h b/include/Vector3.h new file mode 100644 index 0000000..e5aa5f3 --- /dev/null +++ b/include/Vector3.h @@ -0,0 +1,116 @@ +/******************************************************** + * Vector3.h * + * * + * XFX Vector3 definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_VECTOR3_ +#define _XFX_VECTOR3_ + +#include + +namespace XFX +{ + struct Matrix; + struct Quaternion; + struct Vector2; + + /// + /// Defines a vector with three components. + /// + struct Vector3 + { + public: + float X, Y, Z; + static const Vector3 Backward; + static const Vector3 Down; + static const Vector3 Forward; + static const Vector3 Left; + static const Vector3 One; + static const Vector3 Right; + static const Vector3 UnitX; + static const Vector3 UnitY; + static const Vector3 UnitZ; + static const Vector3 Up; + static const Vector3 Zero; + + Vector3(float value); + Vector3(float x, float y, float z); + Vector3(Vector2 value, float z); + Vector3(const Vector3 &obj); + Vector3(); + + static Vector3 Add(Vector3 value1, Vector3 value2); + static void Add(Vector3 value1, Vector3 value2, out Vector3 result); + static Vector3 Baricentric(Vector3 value1, Vector3 value2, Vector3 value3, float amount1, float amount2); + static void Baricentric(Vector3 value1, Vector3 value2, Vector3 value3, float amount1, float amount2, out Vector3 result); + static Vector3 CatmullRom(Vector3 value1, Vector3 value2, Vector3 value3, Vector3 value4, float amount); + static void CatmullRom(Vector3 value1, Vector3 value2, Vector3 value3, Vector3 value4, float amount, out Vector3 result); + static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max); + static void Clamp(Vector3 value1, Vector3 min, Vector3 max, out Vector3 result); + static Vector3 Cross(Vector3 vector1, Vector3 vector2); + static void Cross(Vector3 vector1, Vector3 vector2, out Vector3 result); + static float Distance(Vector3 value1, Vector3 value2); + static void Distance(Vector3 value1, Vector3 value2, out float result); + static float DistanceSquared(Vector3 value1, Vector3 value2); + static void DistanceSquared(Vector3 value1, Vector3 value2, out float result); + static Vector3 Divide(Vector3 value1, float value2); + static void Divide(Vector3 value1, float value2, out Vector3 result); + static Vector3 Divide(Vector3 value1, Vector3 value2); + static void Divide(Vector3 value1, Vector3 value2, out Vector3 result); + static float Dot(Vector3 value1, Vector3 value2); + static void Dot(Vector3 value1, Vector3 value2, out float result); + bool Equals(Vector3 obj); + int GetHashCode(); + static Vector3 Hermite(Vector3 value1, Vector3 tangent1, Vector3 value2, Vector3 tangent2, float amount); + static void Hermite(Vector3 value1, Vector3 tangent1, Vector3 value2, Vector3 tangent2, float amount, out Vector3 result); + float Length(); + float LengthSquared(); + static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount); + static void Lerp(Vector3 value1, Vector3 value2, float amount, out Vector3 result); + static Vector3 Max(Vector3 value1, Vector3 value2); + static void Max(Vector3 value1, Vector3 value2, out Vector3 result); + static Vector3 Min(Vector3 value1, Vector3 value2); + static void Min(Vector3 value1, Vector3 value2, out Vector3 result); + static Vector3 Multiply(Vector3 value1, float scaleFactor); + static void Multiply(Vector3 value1, float scaleFactor, out Vector3 result); + static Vector3 Multiply(Vector3 value1, Vector3 value2); + static void Multiply(Vector3 value1, Vector3 value2, out Vector3 result); + static Vector3 Negate(Vector3 value); + static void Negate(Vector3 value, out Vector3 result); + void Normalize(); + static Vector3 Normalize(Vector3 value); + static void Normalize(Vector3 value, out Vector3 result); + static Vector3 Reflect(Vector3 vector, Vector3 normal); + static void Reflect(Vector3 vector, Vector3 normal, out Vector3 result); + static Vector3 SmoothStep(Vector3 value1, Vector3 value2, float amount); + static void SmoothStep(Vector3 value1, Vector3 value2, float amount, out Vector3 result); + static Vector3 Subtract(Vector3 value1, Vector3 value2); + static void Subtract(Vector3 value1, Vector3 value2, out Vector3 result); + static Vector3 Transform(Vector3 position, Matrix matrix); + static void Transform(Vector3 position, Matrix matrix, out Vector3 result); + static Vector3 Transform(Vector3 position, Quaternion rotation); + static void Transform(Vector3 position, Quaternion rotation, out Vector3 result); + static void Transform(Vector3 sourceArray[], int sourceIndex, Matrix matrix, Vector3 destinationArray[], int destinationIndex, int length); + static void Transform(Vector3 sourceArray[], int sourceIndex, Quaternion rotation, Vector3 destinationArray[], int destinationIndex, int length); + static void Transform(Vector3 sourceArray[], Matrix matrix, Vector3 destinationArray[]); + static void Transform(Vector3 sourceArray[], Quaternion rotation, Vector3 destinationArray[]); + static Vector3 TransformNormal(Vector3 normal, Matrix matrix); + static void TransformNormal(Vector3 normal, Matrix matrix, out Vector3 result); + static void TransformNormal(Vector3 sourceArray[], int sourceIndex, Matrix matrix, Vector3 destinationArray[], int destinationIndex, int length); + static void TransformNormal(Vector3 sourceArray[], Matrix matrix, Vector3 destinationArray[]); + + Vector3 operator+(Vector3 other); + Vector3 operator/(float divider); + Vector3 operator/(Vector3 other); + bool operator==(const Vector3 other); + bool operator!=(const Vector3 other); + Vector3 operator*(float scaleFactor); + Vector3 operator*(Vector3 other); + Vector3 operator-(Vector3 other); + Vector3 operator-(); + Vector3 operator=(const Vector3 other); + } ALIGNED; +} + +#endif //_XFX_VECTOR3_ diff --git a/include/Vector4.h b/include/Vector4.h new file mode 100644 index 0000000..d831c8f --- /dev/null +++ b/include/Vector4.h @@ -0,0 +1,111 @@ +/******************************************************** + * Vector4.h * + * * + * XFX Vector4 definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_VECTOR4_ +#define _XFX_VECTOR4_ + +#include + +namespace XFX +{ + struct Matrix; + struct Quaternion; + struct Vector2; + struct Vector3; + + /// + /// Defines a vector with four components. + /// + struct Vector4 + { + float W, X, Y, Z; + static const Vector4 One; + static const Vector4 UnitW; + static const Vector4 UnitX; + static const Vector4 UnitY; + static const Vector4 UnitZ; + static const Vector4 Zero; + + Vector4(float value); + Vector4(float x, float y, float z, float w); + Vector4(Vector2 value, float z, float w); + Vector4(Vector3 value, float w); + Vector4(const Vector4 &obj); + Vector4(); + + static Vector4 Add(Vector4 vector1, Vector4 vector2); + static void Add(Vector4 vector1, Vector4 vector2, out Vector4 result); + static Vector4 Baricentric(Vector4 value1, Vector4 value2, Vector4 value3, float amount1, float amount2); + static void Baricentric(Vector4 value1, Vector4 value2, Vector4 value3, float amount1, float amount2, out Vector4 result); + static Vector4 CatmullRom(Vector4 value1, Vector4 value2, Vector4 value3, Vector4 value4, float amount); + static void CatmullRom(Vector4 value1, Vector4 value2, Vector4 value3, Vector4 value4, float amount, out Vector4 result); + static Vector4 Clamp(Vector4 value1, Vector4 min, Vector4 max); + static void Clamp(Vector4 value1, Vector4 min, Vector4 max, out Vector4 result); + static float Distance(Vector4 value1, Vector4 value2); + static void Distance(Vector4 value1, Vector4 value2, out float result); + static float DistanceSquared(Vector4 value1, Vector4 value2); + static void DistanceSquared(Vector4 value1, Vector4 value2, out float result); + static Vector4 Divide(Vector4 value, float scale); + static void Divide(Vector4 value, float scale, out Vector4 result); + static Vector4 Divide(Vector4 vector1, Vector4 vector2); + static void Divide(Vector4 vector1, Vector4 vector2, out Vector4 result); + bool Equals(Vector4 obj); + int GetHashCode(); + static Vector4 Hermite(Vector4 value1, Vector4 tangent1, Vector4 value2, Vector4 tangent2, float amount); + static void Hermite(Vector4 value1, Vector4 tangent1, Vector4 value2, Vector4 tangent2, float amount, out Vector4 result); + float Length(); + float LengthSquared(); + static Vector4 Lerp(Vector4 value1, Vector4 value2, float amount); + static void Lerp(Vector4 value1, Vector4 value2, float amount, out Vector4 result); + static Vector4 Max(Vector4 value1, Vector4 value2); + static void Max(Vector4 value1, Vector4 value2, out Vector4 result); + static Vector4 Min(Vector4 value1, Vector4 value2); + static void Min(Vector4 value1, Vector4 value2, out Vector4 result); + static Vector4 Multiply(Vector4 value1, float scaleFactor); + static void Multiply(Vector4 value1, float scaleFactor, out Vector4 result); + static Vector4 Multiply(Vector4 value1, Vector4 value2); + static void Multiply(Vector4 value1, Vector4 value2, out Vector4 result); + static Vector4 Negate(Vector4 value); + static void Negate(Vector4 value, out Vector4 result); + void Normalize(); + static Vector4 Normalize(Vector4 value); + static void Normalize(Vector4 value, out Vector4 result); + static Vector4 SmoothStep(Vector4 value1, Vector4 value2, float amount); + static void SmoothStep(Vector4 value1, Vector4 value2, float amount, out Vector4 result); + static Vector4 Subtract(Vector4 value1, Vector4 value2); + static void Subtract(Vector4 value1, Vector4 value2, out Vector4 result); + static void Transform(Vector4 sourceArray[], Quaternion rotation, Vector4 destinationArray[]); + static void Transform(Vector4 sourceArray[], int sourceIndex, Quaternion rotation, Vector4 destinationArray[], int destinationIndex, int length); + static void Transform(Vector4 sourceArray[], Matrix matrix, Vector4 destinationArray[]); + static void Transform(Vector4 sourceArray[], int sourceIndex, Matrix matrix, Vector4 destinationArray[], int destinationIndex, int length); + static Vector4 Transform(Vector4 vector, Quaternion rotation); + static void Transform(Vector4 vector, Quaternion rotation, out Vector4 result); + static Vector4 Transform(Vector3 vector, Quaternion rotation); + static void Transform(Vector3 vector, Quaternion rotation, out Vector4 result); + static Vector4 Transform(Vector2 vector, Quaternion rotation); + static void Transform(Vector2 vector, Quaternion rotation, out Vector4 result); + static Vector4 Transform(Vector4 vector, Matrix matrix); + static void Transform(Vector4 vector, Matrix matrix, out Vector4 result); + static Vector4 Transform(Vector3 position, Matrix matrix); + static void Transform(Vector3 position, Matrix matrix, out Vector4 result); + static Vector4 Transform(Vector2 vector, Matrix matrix); + static void Transform(Vector2 vector, Matrix matrix, out Vector4 result); + + const Vector4 operator-(const Vector4 other); + const Vector4 operator-(); + bool operator!=(const Vector4 other); + const Vector4 operator*(const float scaleFactor); + const Vector4 operator*(const Vector4 other); + const Vector4 operator /(const float divider); + const Vector4 operator /(const Vector4 other); + const Vector4 operator+(const Vector4 other); + bool operator==(const Vector4 other); + Vector4 operator =(const Vector4 other); + } ALIGNED; +} + +#endif //_XFX_VECTOR4_ + diff --git a/include/XFX.h b/include/XFX.h new file mode 100644 index 0000000..974c307 --- /dev/null +++ b/include/XFX.h @@ -0,0 +1,43 @@ +/******************************************************** + * XFX.h * + * * + * XFX namespace include file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _XFX_ +#define _XFX_ + +// +//Data types +// +#include "BoundingBox.h" +#include "BoundingSphere.h" +#include "GameTime.h" +#include "MathHelper.h" +#include "Matrix.h" +#include "Point.h" +#include "Quaternion.h" +#include "Ray.h" +#include "Rectangle.h" +#include "Vector2.h" +#include "Vector3.h" +#include "Vector4.h" + +#include "Enums.h" + +// +//Interfaces +// +#include "IDrawable.h" +#include "IGameComponent.h" +#include "IGraphicsDeviceManager.h" +#include "IUpdateable.h" + +// +//Namespaces +// +#include "Audio.h" +#include "Graphics.h" +#include "Media.h" + +#endif //_XFX_ diff --git a/src/Layout XFX.txt b/src/Layout XFX.txt new file mode 100644 index 0000000..59645d9 --- /dev/null +++ b/src/Layout XFX.txt @@ -0,0 +1,64 @@ +============== += What is XFX? +================ +XFX or XNA For XBOX is a set of libraries created on top of OpenXDK to allow XNA-style +programming on the XBOX console. +Almost every function you can find in the XNA 2.0 libraries is present here, +so you've got all the tools required to create stunning games and apps for the XBOX. +Also, because the functions match those in the XNA libraries, you can use the MSDN documentation +in case you need to know the specifics about any function. Just don't forget you're coding in C++, +instead of C#. + +NOTE: because of limitations, the XNA 'Content Pipeline' is not represented. +Instead, files are processed as necessary when loaded by the program, and not at compile time. +If you want, though, you can use .xnb files with XFX, as loading them has been implemented in +the ContentReader + +========== += Contents +============ +The XFX Framework consists of the following libraries: + +libmscorlib.a + Custom implementation of the XBOX360 mscorlib.dll file, used to specify data types used + by the XFX libraries, and for easier general purpose XBOX programming + +libSystem.a + Custom implementation of the XBOX360 System.dll file. + +libSystem.Xml.a + Custom implementation of the XBOX360 System.Xml.dll file, implementing Xml manipulation + on the XBOX console. + +libXFX.a + Custom implementation of the XBOX360 version of the Microsoft.Xna.Framework.dll + This is the core of XFX, allowing XNA-style coding for the XBOX console. + +libXFX.Game.a + Custom implementation of the XBOX360 version of the Microsoft.Xna.Framework.Game.dll + +============== += Requirements +================ +To compile software with these libraries, you'll need the following: + +Basic Cygwin installation, with at least the following components: + - autoconf + - automake + - binutils + - gcc-3 (NOTE: version 3 is preferred due to compatibility issues with gcc-4) + - g++-3 (NOTE: version 3 is preferred due to compatibility issues with g++-4) + - make + +OpenXDK 0.0.7 or higher + + +That's pretty much it. +See the makefile for file locations. + +* For editing the XFX Framework's source code, we advise you install Visual Studio 2005 +or higher, since it is what we used to manage the source code ourselves. IntelliSense really helped +speed up the coding, and being able to go to faulty code with just a double-click is just perfect. +One thing, though: In order to successfully be able to compile the XFX libraries from within VS2005, +one thing is needed after the install of Cygwin; You will need to add the Cygwin bin directory, +often located at C:\cygwin\bin to the PATH environment variable, so Visual Studio can access make.exe \ No newline at end of file diff --git a/src/libSystem.Xml/libSystem.Xml.vcproj b/src/libSystem.Xml/libSystem.Xml.vcproj new file mode 100644 index 0000000..cb595fc --- /dev/null +++ b/src/libSystem.Xml/libSystem.Xml.vcproj @@ -0,0 +1,160 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/libSystem.Xml/makefile b/src/libSystem.Xml/makefile new file mode 100644 index 0000000..949182a --- /dev/null +++ b/src/libSystem.Xml/makefile @@ -0,0 +1,53 @@ +# +# update this variable to wherever you installed the OpenXDK libraries +# +######################################################################### +# +# The ENABLE_XBOX definition is there because of intentions to eventually +# support Linux as well +# +PREFIX = /usr/local/openxdk + +CC = gcc +CCAS = gcc +CPP = g++ +AR = ar rcu +RANLIB = ranlib +CXBE = $(PREFIX)/bin/cxbe + +SDLFLAGS = -DENABLE_XBOX -DDEBUG +CC_FLAGS = -c -g -std=gnu99 -ffreestanding -nostdlib -fno-builtin -fno-exceptions -mno-cygwin -march=i386 $(SDLFLAGS) +CCAS_FLAGS = -g -O2 +CPP_FLAGS = -c -O2 -Wall -nostdlib -fno-builtin -mno-cygwin -march=i386 $(SDLFLAGS) +INCLUDE = -I$(PREFIX)/i386-pc-xbox/include -I$(PREFIX)/include -I$(PREFIX)/include/SDL -I../../include + +CLINK = -nostdlib +ALIGN = -Wl,--file-alignment,0x20 -Wl,--section-alignment,0x20 +SHARED = -shared +ENTRYPOINT = -Wl,--entry,_WinMainCRTStartup +STRIP = -Wl,--strip-all +LD_FLAGS = $(CLINK) $(ALIGN) $(SHARED) $(ENTRYPOINT) $(STRIP) +LD_DIRS = -L$(PREFIX)/i386-pc-xbox/lib -L$(PREFIX)/lib +LD_LIBS = $(LD_DIRS) -lxkutils -lm -lopenxdk -lhal -lc -lusb -lc -lxboxkrnl -lc -lhal -lxboxkrnl -lhal -lopenxdk -lc -lstdc++ -lgcc + +OBJS = + +all: libSystem.Xml.a + +rebuild: clean libSystem.Xml.a + +libSystem.Xml.a: $(OBJS) + $(AR) $@ $(OBJS) + $(RANLIB) $@ + +.c.o: + $(CC) -c $< $(CC_FLAGS) $(INCLUDE) + +.cpp.o: + $(CPP) -c $< $(CPP_FLAGS) $(INCLUDE) + +.s.o: + $(CCAS) -c $< $(CCAS_FLAGS) + +clean: + rm -f *.o *.exe *.dll *.xbe *.cxbe *.lib *.a diff --git a/src/libSystem/IDisposable.h b/src/libSystem/IDisposable.h new file mode 100644 index 0000000..47422f1 --- /dev/null +++ b/src/libSystem/IDisposable.h @@ -0,0 +1,19 @@ +/******************************************************** + * IDisposable.h * + * * + * XFX IDisposable interface definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _IDISPOSABLE_ +#define _IDISPOSABLE_ + +namespace System +{ + interface IDisposable + { + public: + void Dispose(); + }; +} + +#endif //_IDISPOSABLE_ diff --git a/src/libSystem/IServiceProvider.h b/src/libSystem/IServiceProvider.h new file mode 100644 index 0000000..72afdac --- /dev/null +++ b/src/libSystem/IServiceProvider.h @@ -0,0 +1,14 @@ +#ifndef ISERVICEPROVIDER_H +#define ISERVICEPROVIDER_H + +#include "System.h" + +namespace System +{ + interface IServiceProvider + { + //object GetService(type serviceType); + }; +} + +#endif //ISERVICEPROVIDER_H diff --git a/src/libSystem/System.h b/src/libSystem/System.h new file mode 100644 index 0000000..1696ee6 --- /dev/null +++ b/src/libSystem/System.h @@ -0,0 +1,35 @@ +/******************************************************** + * System.h * + * * + * XFX System namespace include file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef SYSTEM_H +#define SYSTEM_H + +//For more resemblance to XNA and easier differentiating between normal classes and interface types +#define interface class + +//For documentation purposes +#define out + +#ifdef ENABLE_XBOX +//Include commonly used OpenXDK headers +extern "C" { +#include +#include +#include +#include +#include +#endif + +#include +} + +#include "IDisposable.h" +#include "IServiceProvider.h" +#include "Math.h" +#include "Thread.h" +#include "TimeSpan.h" + +#endif //SYSTEM_H diff --git a/src/libSystem/Thread.h b/src/libSystem/Thread.h new file mode 100644 index 0000000..eee88e6 --- /dev/null +++ b/src/libSystem/Thread.h @@ -0,0 +1,63 @@ +/******************************************************** + * Thread.h * + * * + * XFX Thread definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _THREAD_ +#define _THREAD_ + +extern "C" { +#ifdef ENABLE_XBOX +#include +#else +#endif +} + +#include "ThreadState.h" +#include "TimeSpan.h" + +namespace System +{ + namespace Threading + { + class Thread + { + int lock_thread_id; + HANDLE system_thread_handle; + PKSTART_ROUTINE callback; + int stack_size; + static ULONG Id; + PULONG suspendCount; + + ThreadState state; + + private: + void Thread_init(); + ~Thread(); + + public: + //Creates a new instance of the Thread class with the specified callback function, but doesn't start yet. + Thread(PKSTART_ROUTINE callBack); + //Creates a new instance of the Thread class with the specified callback function and stack size, but doesn't start yet. + Thread(PKSTART_ROUTINE callBack, int stackSize); + + void Abort(); + void Interrupt(); + //Returns a value indicating whether the thread is running + int IsAlive(); + //Resumes a previously suspended thread. + void Resume(); + //Set the thread priority, valid values are 0 (Low), 16 (Low_RealTime), 31 (High), 32 (Maximum) + void SetPriority(int priority); + static void Sleep(int millisecondsTimeout); + static void Sleep(TimeSpan timeout); + //Start executing the thread. + void Start(); + //Suspend the thread execution, call Thread::Resume() to resume the thread. + void Suspend(); + }; + } +} + +#endif //_THREAD_ \ No newline at end of file diff --git a/src/libSystem/ThreadState.h b/src/libSystem/ThreadState.h new file mode 100644 index 0000000..a37ab3b --- /dev/null +++ b/src/libSystem/ThreadState.h @@ -0,0 +1,30 @@ +/******************************************************** + * ThreadState.h * + * * + * XFX ThreadState enumeration definition file * + * Copyright © Halofreak1990. All Rights Reserved * + ********************************************************/ +#ifndef THREADSTATE_H +#define THREADSTATE_H + +namespace System +{ + namespace Threading + { + enum ThreadState + { + Running = 0x00000000, + StopRequested = 0x00000001, + SuspendRequested = 0x00000002, + Background = 0x00000004, + Unstarted = 0x00000008, + Stopped = 0x00000010, + WaitSleepJoin = 0x00000020, + Suspended = 0x00000040, + AbortRequested = 0x00000080, + Aborted = 0x00000100 + }; + } +} + +#endif //THREADSTATE_H diff --git a/src/libSystem/TimeSpan.h b/src/libSystem/TimeSpan.h new file mode 100644 index 0000000..91963b7 --- /dev/null +++ b/src/libSystem/TimeSpan.h @@ -0,0 +1,48 @@ +/******************************************************** + * TimeSpan.h * + * * + * XFX TimeSpan definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef TIMESPAN_H +#define TIMESPAN_H + +extern "C" { +#ifdef ENABLE_XBOX +#include +#else +#include +#endif +} + +namespace System +{ + class TimeSpan + { + long _ticks; + + public: + static const TimeSpan Zero; + static const long TicksPerMillisecond; + static const long TicksPerSecond; + static const long TicksPerMinute; + static const long long TicksPerHour; + static const long long TicksPerDay; + + long Ticks(); + int Days(); + int Hours(); + int Milliseconds(); + int Minutes(); + int Seconds(); + + TimeSpan(long ticks); + TimeSpan(const TimeSpan &obj); + TimeSpan(); + + int operator!=(const TimeSpan &other); + int operator==(const TimeSpan &other); + }; +} + +#endif //TIMESPAN_H diff --git a/src/libSystem/libSystem.vcproj b/src/libSystem/libSystem.vcproj new file mode 100644 index 0000000..a53fe01 --- /dev/null +++ b/src/libSystem/libSystem.vcproj @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/libXFX.Game/DrawableGameComponent.cpp b/src/libXFX.Game/DrawableGameComponent.cpp new file mode 100644 index 0000000..b4873da --- /dev/null +++ b/src/libXFX.Game/DrawableGameComponent.cpp @@ -0,0 +1,105 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace XFX +{ + GraphicsDevice DrawableGameComponent::GraphicsDevice_() + { + return _graphicsService.GraphicsDevice_; + } + + DrawableGameComponent::DrawableGameComponent(Game game) + : GameComponent(game) + { + _visible = true; + } + + void DrawableGameComponent::Dispose(bool disposing) + { + if(disposing) + { + UnloadContent(); + } + GameComponent::Dispose(); + } + + int DrawableGameComponent::DrawOrder() + { + return _drawOrder; + } + + void DrawableGameComponent::DrawOrder(int value) + { + if (_drawOrder != value) + { + _drawOrder = value; + OnDrawOrderChanged(this, EventArgs::Empty); + } + } + + void DrawableGameComponent::Initialize() + { + LoadContent(); + } + + void DrawableGameComponent::OnDrawOrderChanged(void* sender, EventArgs args) + { + if (DrawOrderChanged != null) + DrawOrderChanged(sender, args); + } + + void DrawableGameComponent::OnVisibleChanged(void* sender, EventArgs args) + { + if (VisibleChanged != null) + VisibleChanged(sender, args); + } + + void DrawableGameComponent::Update(GameTime gameTime) + { + if(Enabled()) + { + } + + GameComponent::Update(gameTime); + } + + bool DrawableGameComponent::Visible() + { + return _visible; + } + + void DrawableGameComponent::Visible(bool value) + { + if (_visible != value) + { + _visible = value; + OnVisibleChanged(this, EventArgs::Empty); + } + } +} diff --git a/src/libXFX.Game/Game.cpp b/src/libXFX.Game/Game.cpp new file mode 100644 index 0000000..0be87e8 --- /dev/null +++ b/src/libXFX.Game/Game.cpp @@ -0,0 +1,207 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +extern "C" { +#ifdef ENABLE_XBOX +#include "../libXFX/xinput.h" +#include +#else +#endif +} + +#include + +namespace XFX +{ + const Int64 Game::DefaultTargetElapsedTicks = 10000000L / 60L; + + bool Game::IsActive() + { + return isActive; + } + + Game::Game() + { + inRun = false; + + IsFixedTimeStep = true; + + visibleDrawable = List(); + enabledUpdateable = List(); + + components = new GameComponentCollection(); + + services = new GameServiceContainer(); + + content = new ContentManager(); + + gameTime = GameTime(TimeSpan::Zero, TimeSpan::Zero, TimeSpan::Zero, TimeSpan::Zero); + + inactiveSleepTime = TimeSpan::FromTicks(0); + TargetElapsedTime = TimeSpan::FromTicks(DefaultTargetElapsedTicks); + + isActive = true; + } + + GameComponentCollection Game::Components() + { + return components; + } + + GraphicsDevice Game::GraphicsDevice_() + { + return graphicsService.GraphicsDevice_; + } + + GameServiceContainer Game::Services() + { + return services; + } + + bool Game::BeginDraw() + { + return graphicsManager.BeginDraw(); + } + + void Game::Dispose() + { + Dispose(true); + } + + void Game::Dispose(bool disposing) + { + if(disposed) + return; + + if(disposing) + { + /* + foreach (IGameComponent component in components) + { + IDisposable disposable = component as IDisposable; + if (disposable != null) + disposable.Dispose(); + } + */ + } + + disposed = true; + if(Disposed != null) + Disposed(*this, EventArgs::Empty); + } + + void Game::Draw(GameTime gameTime) + { + /* + foreach (IDrawable drawable in visibleDrawable) + { + drawable.Draw(gameTime); + } + */ + } + + void Game::EndDraw() + { + graphicsManager.EndDraw(); + } + + void Game::Exit() + { + XSleep(1000); + XReboot(); + } + + void Game::Initialize() + { + /* + this.graphicsService = this.Services.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService; + + foreach (IGameComponent component in components) + { + component.Initialize(); + }*/ + + LoadContent(); + } + +#if !ENABLE_XBOX + void Game::OnActivated(void* sender, EventArgs args) + { + if (Activated != null) + Activated(sender, args); + } + + void Game::OnDeactivated(void* sender, EventArgs args) + { + if (Deactivated != null) + Deactivated(sender, args); + } +#endif + + void Game::OnExiting(void* sender, EventArgs args) + { + if (Exiting != null) + Exiting(sender, args); + } + + void Game::Run() + { + if(inRun) + throw InvalidOperationException("Run Method called more than once"); + + inRun = true; + BeginRun(); + + Initialize(); + + Tick(); + + EndRun(); + } + + void Game::Tick() + { + + Update(gameTime); + + if(BeginDraw()) + { + Draw(gameTime); + EndDraw(); + } + } + + void Game::Update(GameTime gameTime) + { + /* + foreach (IUpdateable updateable in enabledUpdateable) + { + updateable.Update(gameTime); + } + */ + } +} diff --git a/src/libXFX.Game/GameComponent.cpp b/src/libXFX.Game/GameComponent.cpp new file mode 100644 index 0000000..179108e --- /dev/null +++ b/src/libXFX.Game/GameComponent.cpp @@ -0,0 +1,120 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace XFX +{ + bool GameComponent::Enabled() + { + return _enabled; + } + + void GameComponent::Enabled(bool value) + { + if(_enabled != value) + { + _enabled = value; + OnEnabledChanged(*this, EventArgs::Empty); + } + } + + Game GameComponent::Game_() + { + return _game; + } + + int GameComponent::UpdateOrder() + { + return _updateOrder; + } + + void GameComponent::UpdateOrder(int value) + { + if(_updateOrder != value) + { + _updateOrder = value; + OnUpdateOrderChanged(*this, EventArgs::Empty); + } + } + + void GameComponent::Dispose() + { + Dispose(true); + } + + void GameComponent::Dispose(bool disposing) + { + if (!_disposed) + { + _disposed = true; + if (Disposed != null) + Disposed(this, EventArgs.Empty); + } + } + + void GameComponent::Dispose() + { + Dispose(true); + } + + GameComponent::GameComponent(Game game) + { + _game = game; + _enabled = true; + } + + GameComponent::~GameComponent() + { + Dispose(false); + } + + Game GameComponent::Game_() + { + return _game; + } + + void GameComponent::Initialize() + { + } + + void GameComponent::OnEnabledChanged(void* sender, EventArgs args) + { + if (EnabledChanged != null) + EnabledChanged(*this, args); + } + + void GameComponent::OnUpdateOrderChanged(void* sender, EventArgs args) + { + if (UpdateOrderChanged != null) + UpdateOrderChanged(this, args); + } + + void GameComponent::Update(GameTime gameTime) + { + } +} diff --git a/src/libXFX.Game/GameTime.cpp b/src/libXFX.Game/GameTime.cpp new file mode 100644 index 0000000..5772343 --- /dev/null +++ b/src/libXFX.Game/GameTime.cpp @@ -0,0 +1,64 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace XFX +{ + bool GameTime::IsRunningSlowly() + { + return _isRunningSlowly; + } + + TimeSpan GameTime::TotalGameTime() + { + return _totalGameTime; + } + + TimeSpan GameTime::TotalRealTime() + { + return _totalRealTime; + } + + GameTime::GameTime() + { + } + + GameTime::GameTime(TimeSpan totalRealTime, TimeSpan elapsedRealTime, TimeSpan totalGameTime, TimeSpan elapsedGameTime) + { + GameTime(totalRealTime, elapsedRealTime, totalGameTime, elapsedGameTime, false); + } + + GameTime::GameTime(TimeSpan totalRealTime, TimeSpan elapsedRealTime, TimeSpan totalGameTime, TimeSpan elapsedGameTime, bool isRunningSlowly) + { + _totalRealTime = totalRealTime; + _elapsedRealTime = elapsedRealTime; + _totalGameTime = totalGameTime; + _elapsedGameTime = elapsedGameTime; + _isRunningSlowly = isRunningSlowly; + } +} diff --git a/src/libXFX.Game/GamerServicesComponent.cpp b/src/libXFX.Game/GamerServicesComponent.cpp new file mode 100644 index 0000000..ccfcc95 --- /dev/null +++ b/src/libXFX.Game/GamerServicesComponent.cpp @@ -0,0 +1,49 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace XFX +{ + namespace GamerServices + { + GamerServicesComponent::GamerServicesComponent(Game game) + : GameComponent(game) + { + } + + void GamerServicesComponent::Initialize() + { + GameComponent::Initialize(); + } + + void GamerServicesComponent::Update(GameTime gameTime) + { + GameComponent::Update(gameTime); + } + } +} diff --git a/src/libXFX.Game/GraphicsDeviceManager.cpp b/src/libXFX.Game/GraphicsDeviceManager.cpp new file mode 100644 index 0000000..89328b9 --- /dev/null +++ b/src/libXFX.Game/GraphicsDeviceManager.cpp @@ -0,0 +1,93 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include "PBKit/pbKit.h" + +namespace XFX +{ +#if ENABLE_XBOX + const int GraphicsDeviceManager::DefaultBackBufferWidth = 640; + const int GraphicsDeviceManager::DefaultBackBufferHeight = 480; + const DeviceType_t GraphicsDeviceManager::ValidDeviceTypes[] = { DeviceType::Hardware }; +#else + const int GraphicsDeviceManager::DefaultBackBufferWidth = 800; + const int GraphicsDeviceManager::DefaultBackBufferHeight = 600; +#endif + + GraphicsDevice GraphicsDeviceManager::GraphicsDevice_() + { + return graphicsDevice; + } + + bool IsFullScreen() + { +#if ENABLE_XBOX //On the XBOX we always run Fullscreen + return true; +#else + return isFullScreen; +#endif + } + + void GraphicsDeviceManager::ApplyChanges() + { + + } + + void IGraphicsDeviceManager::CreateDevice() + { + + } + + GraphicsDeviceManager::GraphicsDeviceManager(Game game) + { + _game = game; + if (game.Services().GetService(typeof(IGraphicsDeviceManager)) != null) + { + throw ArgumentException("A graphics device manager is already registered. The graphics device manager cannot be changed once it is set."); + } + game.Services().AddService(typeof(IGraphicsDeviceManager), this); + game.Services().AddService(typeof(IGraphicsDeviceService), this); +#if !ENABLE_XBOX + game.Window.ClientSizeChanged += new EventHandler(this.GameWindowClientSizeChanged); + game.Window.ScreenDeviceNameChanged += new EventHandler(this.GameWindowScreenDeviceNameChanged); +#endif + } + + void GraphicsDeviceManager::ToggleFullscreen() + { +#if !ENABLE_XBOX + isFullScreen != isFullScreen; + //graphicsDevice.PresentationParameters. +#endif + } + + bool IGraphicsDeviceManager::BeginDraw() + { + return true; + } +} diff --git a/src/libXFX.Game/libXFX.Game.vcproj b/src/libXFX.Game/libXFX.Game.vcproj new file mode 100644 index 0000000..49ef8ea --- /dev/null +++ b/src/libXFX.Game/libXFX.Game.vcproj @@ -0,0 +1,197 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/libXFX.Game/makefile b/src/libXFX.Game/makefile new file mode 100644 index 0000000..a4a748b --- /dev/null +++ b/src/libXFX.Game/makefile @@ -0,0 +1,55 @@ +# +# update this variable to wherever you installed the OpenXDK libraries +# +######################################################################### +# +# The ENABLE_XBOX definition is there because of intentions to eventually +# support Linux as a platform as well +# +PREFIX = /usr/local/openxdk +XFX_PREFIX = /cygdrive/j/XFX + +CC = gcc +CCAS = gcc +CPP = g++ +AR = ar rcu +RANLIB = ranlib +CXBE = $(PREFIX)/bin/cxbe + +SDLFLAGS = -DENABLE_XBOX -DDEBUG +CC_FLAGS = -c -g -std=gnu99 -ffreestanding -nostdlib -fno-builtin -fno-exceptions -mno-cygwin -march=i386 $(SDLFLAGS) +CCAS_FLAGS = -g -O2 +CPP_FLAGS = -c -O2 -Wall -nostdlib -fno-builtin -mno-cygwin -march=i386 -mmmx -msse -mfpmath=sse $(SDLFLAGS) +INCLUDE = -I$(PREFIX)/i386-pc-xbox/include -I$(PREFIX)/include -I$(PREFIX)/include/SDL -I$(XFX_PREFIX)/include + +CLINK = -nostdlib +ALIGN = -Wl,--file-alignment,0x20 -Wl,--section-alignment,0x20 +SHARED = -shared +ENTRYPOINT = -Wl,--entry,_WinMainCRTStartup +STRIP = -Wl,--strip-all +LD_FLAGS = $(CLINK) $(ALIGN) $(SHARED) $(ENTRYPOINT) $(STRIP) +LD_DIRS = -L$(PREFIX)/i386-pc-xbox/lib -L$(PREFIX)/lib +LD_LIBS = $(LD_DIRS) -lm -lopenxdk -lhal -lc -lusb -lc -lxboxkrnl -lc -lhal -lxboxkrnl -lhal -lopenxdk -lc -lstdc++ -lgcc + +OBJS = DrawableGameComponent.o Game.o GameComponent.o GamerServicesComponent.o GameTime.o GraphicsDeviceManager.o + +all: libXFX.Game.a + +rebuild: clean libXFX.Game.a + +libXFX.Game.a: $(OBJS) + $(AR) $@ $(OBJS) + $(RANLIB) $@ + +.c.o: + $(CC) -c $< $(CC_FLAGS) $(INCLUDE) + +.cpp.o: + $(CPP) -c $< $(CPP_FLAGS) $(INCLUDE) + +.s.o: + $(CCAS) -c $< $(CCAS_FLAGS) + +clean: + rm -f *.o *.exe *.dll *.xbe *.cxbe *.lib *.a + \ No newline at end of file diff --git a/src/libXFX/BasicEffect.cpp b/src/libXFX/BasicEffect.cpp new file mode 100644 index 0000000..c5fd14a --- /dev/null +++ b/src/libXFX/BasicEffect.cpp @@ -0,0 +1,68 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace XFX +{ + namespace Graphics + { + BasicEffect::BasicEffect(GraphicsDevice &device, BasicEffect &clone) + : Effect(device, clone) + { + } + BasicEffect::BasicEffect(GraphicsDevice &device, EffectPool &effectPool) + { + } + + Effect BasicEffact::Clone(GraphicsDevice &device) + { + BasicEffect effect = BasicEffect(device, *this); + return effect; + } + + void BasicEffect::EnableDefaultLighting() + { + LightingEnabled = true; + AmbientLightColor = Vector3(0.05333332f, 0.09882354f, 0.1819608f); + Vector3 color = Vector3(1f, 0.9607844f, 0.8078432f); + DirectionalLight0.DiffuseColor = color; + DirectionalLight0.Direction = Vector3(-0.5265408f, -0.5735765f, -0.6275069f); + DirectionalLight0.SpecularColor = color; + DirectionalLight0.Enabled = true; + DirectionalLight1.DiffuseColor = Vector3(0.9647059f, 0.7607844f, 0.4078432f); + DirectionalLight1.Direction = Vector3(0.7198464f, 0.3420201f, 0.6040227f); + DirectionalLight1.SpecularColor = Vector3.Zero; + DirectionalLight1.Enabled = true; + color = Vector3(0.3231373f, 0.3607844f, 0.3937255f); + DirectionalLight2.DiffuseColor = color; + DirectionalLight2.Direction = Vector3(0.4545195f, -0.7660444f, 0.4545195f); + DirectionalLight2.SpecularColor = color; + DirectionalLight2.Enabled = true; + } + } +} diff --git a/src/libXFX/BoundingBox.cpp b/src/libXFX/BoundingBox.cpp new file mode 100644 index 0000000..b532ea3 --- /dev/null +++ b/src/libXFX/BoundingBox.cpp @@ -0,0 +1,309 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include +#include + +using namespace System; + +namespace XFX +{ + const int BoundingBox::CornerCount = 8; + + BoundingBox::BoundingBox(Vector3 min, Vector3 max) + { + Min = min; + Max = max; + } + + BoundingBox::BoundingBox(const BoundingBox &obj) + { + Min = obj.Min; + Max = obj.Max; + } + + BoundingBox::BoundingBox() + { + Min = Vector3::Zero; + Max = Vector3::Zero; + } + + ContainmentType_t BoundingBox::Contains(BoundingBox box) + { + if( Max.X < box.Min.X || Min.X > box.Max.X ) + return ContainmentType::Disjoint; + + if( Max.Y < box.Min.Y || Min.Y > box.Max.Y ) + return ContainmentType::Disjoint; + + if( Max.Z < box.Min.Z || Min.Z > box.Max.Z ) + return ContainmentType::Disjoint; + + if( Min.X <= box.Min.X && box.Max.X <= Max.X && Min.Y <= box.Min.Y && + box.Max.Y <= Max.Y && Min.Z <= box.Min.Z && box.Max.Z <= Max.Z ) + return ContainmentType::Contains; + + return ContainmentType::Intersects; + } + + void BoundingBox::Contains(BoundingBox box, out ContainmentType_t result) + { + if( Max.X < box.Min.X || Min.X > box.Max.X ) + result = ContainmentType::Disjoint; + + if( Max.Y < box.Min.Y || Min.Y > box.Max.Y ) + result = ContainmentType::Disjoint; + + if( Max.Z < box.Min.Z || Min.Z > box.Max.Z ) + result = ContainmentType::Disjoint; + + if( Min.X <= box.Min.X && box.Max.X <= Max.X && Min.Y <= box.Min.Y && + box.Max.Y <= Max.Y && Min.Z <= box.Min.Z && box.Max.Z <= Max.Z ) + result = ContainmentType::Contains; + + result = ContainmentType::Intersects; + } + + ContainmentType_t BoundingBox::Contains(BoundingSphere sphere) + { + float dist; + Vector3 clamped; + + Vector3::Clamp(sphere.Center, Min, Max, clamped); + + float x = sphere.Center.X - clamped.X; + float y = sphere.Center.Y - clamped.Y; + float z = sphere.Center.Z - clamped.Z; + + dist = (x * x) + (y * y) + (z * z); + float radius = sphere.Radius; + + if(dist > (radius * radius)) + return ContainmentType::Disjoint; + + if(Min.X + radius <= sphere.Center.X && sphere.Center.X <= Max.X - radius && + Max.X - Min.X > radius && Min.Y + radius <= sphere.Center.Y && + sphere.Center.Y <= Max.Y - radius && Max.Y - Min.Y > radius && + Min.Z + radius <= sphere.Center.Z && sphere.Center.Z <= Max.Z - radius && + Max.X - Min.X > radius) + return ContainmentType::Contains; + + return ContainmentType::Intersects; + } + + void BoundingBox::Contains(BoundingSphere sphere, out ContainmentType_t result) + { + float dist; + Vector3 clamped; + + Vector3::Clamp(sphere.Center, Min, Max, clamped); + + float x = sphere.Center.X - clamped.X; + float y = sphere.Center.Y - clamped.Y; + float z = sphere.Center.Z - clamped.Z; + + dist = (x * x) + (y * y) + (z * z); + float radius = sphere.Radius; + + if(dist > (radius * radius)) + result = ContainmentType::Disjoint; + + if(Min.X + radius <= sphere.Center.X && sphere.Center.X <= Max.X - radius && + Max.X - Min.X > radius && Min.Y + radius <= sphere.Center.Y && + sphere.Center.Y <= Max.Y - radius && Max.Y - Min.Y > radius && + Min.Z + radius <= sphere.Center.Z && sphere.Center.Z <= Max.Z - radius && + Max.X - Min.X > radius) + result = ContainmentType::Contains; + + result = ContainmentType::Intersects; + } + + ContainmentType_t BoundingBox::Contains(Vector3 vector) + { + if(Min.X <= vector.X && vector.X <= Max.X && Min.Y <= vector.Y && + vector.Y <= Max.Y && Min.Z <= vector.Z && vector.Z <= Max.Z) + return ContainmentType::Contains; + + return ContainmentType::Disjoint; + } + + void BoundingBox::Contains(Vector3 vector, out ContainmentType_t result) + { + if(Min.X <= vector.X && vector.X <= Max.X && Min.Y <= vector.Y && + vector.Y <= Max.Y && Min.Z <= vector.Z && vector.Z <= Max.Z) + result = ContainmentType::Contains; + + result = ContainmentType::Disjoint; + } + + BoundingBox BoundingBox::CreateFromPoints(Vector3 points[]) + { + if(points == NULL || Array::Length(points) <= 0 ) + return BoundingBox(); + + Vector3 min = FLT_MIN; + Vector3 max = MAXFLOAT; + + for(int i = 0; i < Array::Length(points); i++) + { + Vector3::Min( min, points[i], min ); + Vector3::Max( max, points[i], max ); + } + + return BoundingBox(min, max); + } + + BoundingBox BoundingBox::CreateFromSphere(BoundingSphere sphere) + { + BoundingBox result; + result.Min = Vector3(sphere.Center.X - sphere.Radius, sphere.Center.Y - sphere.Radius, sphere.Center.Z - sphere.Radius ); + result.Max = Vector3(sphere.Center.X + sphere.Radius, sphere.Center.Y + sphere.Radius, sphere.Center.Z + sphere.Radius ); + return result; + } + + void BoundingBox::CreateFromSphere(BoundingSphere sphere, out BoundingBox result) + { + result.Min = Vector3(sphere.Center.X - sphere.Radius, sphere.Center.Y - sphere.Radius, sphere.Center.Z - sphere.Radius ); + result.Max = Vector3(sphere.Center.X + sphere.Radius, sphere.Center.Y + sphere.Radius, sphere.Center.Z + sphere.Radius ); + } + + BoundingBox BoundingBox::CreateMerged(BoundingBox box1, BoundingBox box2) + { + BoundingBox result; + Vector3::Min(box1.Min, box2.Min, result.Min); + Vector3::Max(box1.Max, box2.Max, result.Max); + return result; + } + + void BoundingBox::CreateMerged(BoundingBox box1, BoundingBox box2, out BoundingBox result) + { + Vector3::Min(box1.Min, box2.Min, result.Min); + Vector3::Max(box1.Max, box2.Max, result.Max); + } + + bool BoundingBox::Equals(BoundingBox obj) + { + return ((Max == obj.Max) && (Min == obj.Min)); + } + + int BoundingBox::Intersects(BoundingBox box) + { + if (Max.X < box.Min.X || Min.X > box.Max.X) + return false; + + if (Max.Y < box.Min.Y || Min.Y > box.Max.Y) + return false; + + return (Max.Z >= box.Min.Z && Min.Z <= box.Max.Z); + } + + void BoundingBox::Intersects(BoundingBox box, out int result) + { + if (Max.X < box.Min.X || Min.X > box.Max.X) + result = false; + + if (Max.Y < box.Min.Y || Min.Y > box.Max.Y) + result = false; + + result = (Max.Z >= box.Min.Z && Min.Z <= box.Max.Z); + } + + int BoundingBox::Intersects(BoundingSphere sphere) + { + float dist; + Vector3 clamped; + + Vector3::Clamp(sphere.Center, Min, Max, clamped); + + float x = sphere.Center.X - clamped.X; + float y = sphere.Center.Y - clamped.Y; + float z = sphere.Center.Z - clamped.Z; + + dist = (x * x) + (y * y) + (z * z); + + return (dist <= (sphere.Radius * sphere.Radius)); + } + + void BoundingBox::Intersects(BoundingSphere sphere, out int result) + { + float dist; + Vector3 clamped; + + Vector3::Clamp(sphere.Center, Min, Max, clamped); + + float x = sphere.Center.X - clamped.X; + float y = sphere.Center.Y - clamped.Y; + float z = sphere.Center.Z - clamped.Z; + + dist = (x * x) + (y * y) + (z * z); + + result = (dist <= (sphere.Radius * sphere.Radius)); + } + + PlaneIntersectionType_t BoundingBox::Intersects(Plane plane) + { + return plane.Intersects(*this); + } + + void BoundingBox::Intersects(Plane plane, out PlaneIntersectionType_t result) + { + result = plane.Intersects(*this); + } + + float BoundingBox::Intersects(Ray ray) + { + float distance = 0; + ray.Intersects(*this, distance); + return distance; + } + + void BoundingBox::Intersects(Ray ray, out float distance) + { + ray.Intersects(*this, distance); + } + + bool BoundingBox::operator!=(const BoundingBox other) + { + return !Equals(other); + } + + bool BoundingBox::operator==(const BoundingBox other) + { + return Equals(other); + } + + BoundingBox BoundingBox::operator=(const BoundingBox other) + { + Max = other.Max; + Min = other.Min; + return *this; + } +} diff --git a/src/libXFX/BoundingFrustrum.cpp b/src/libXFX/BoundingFrustrum.cpp new file mode 100644 index 0000000..6811895 --- /dev/null +++ b/src/libXFX/BoundingFrustrum.cpp @@ -0,0 +1,467 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// software without specific prior written permission. +// +// SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include +#include +#include + +using namespace System; + +namespace XFX +{ + BoundingFrustrum::BoundingFrustrum() + { + planes = { Plane(), Plane(), Plane(), Plane(), Plane(), Plane() }; + cornerArray = { Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3() }; + } + + BoundingFrustrum::BoundingFrustrum(Matrix value) + { + planes = { Plane(), Plane(), Plane(), Plane(), Plane(), Plane() }; + cornerArray = { Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3() }; + SetMatrix(value); + } + + BoundingFrustrum::BoundingFrustrum(const BoundingFrustrum &obj) + { + Array::Copy(obj.planes, 0, planes, 0, 6); + Array::Copy(obj.cornerArray, 0, cornerArray, 0, 8); + SetMatrix(obj.matrix); + } + + Plane BoundingFrustrum::Bottom() + { + return planes[5]; + } + + Plane BoundingFrustrum::Far() + { + return planes[1]; + } + + Plane BoundingFrustrum::Left() + { + return planes[2]; + } + + Matrix BoundingFrustrum::Matrix_() + { + return matrix; + } + + void BoundingFrustrum::Matrix_(Matrix value) + { + SetMatrix(value); + } + + Plane BoundingFrustrum::Near() + { + return planes[0]; + } + + Plane BoundingFrustrum::Right() + { + return planes[3]; + } + + Plane BoundingFrustrum::Top() + { + return planes[4]; + } + + Vector3 BoundingFrustrum::ComputeIntersection(Plane plane, Ray ray) + { + float num = (-plane.D - Vector3::Dot(plane.Normal, ray.Position)) / Vector3::Dot(plane.Normal, ray.Direction); + return (ray.Position + (ray.Direction * num)); + } + + Ray BoundingFrustrum::ComputeIntersectionLine(Plane p1, Plane p2) + { + Ray ray = Ray(); + ray.Direction = Vector3::Cross(p1.Normal, p2.Normal); + float num = ray.Direction.LengthSquared(); + ray.Position = (Vector3::Cross(((p2.Normal * -p1.D) + (p1.Normal * p2.D)), ray.Direction) / num); + return ray; + } + + ContainmentType_t BoundingFrustrum::Contains(BoundingBox box) + { + bool flag = false; + for(int i = 0; i < Array::Length(planes); i++) + { + switch (box.Intersects(planes[i])) + { + case PlaneIntersectionType::Front: + return ContainmentType::Disjoint; + + case PlaneIntersectionType::Intersecting: + flag = true; + break; + } + } + if (!flag) + { + return ContainmentType::Contains; + } + return ContainmentType::Intersects; + } + + ContainmentType_t BoundingFrustrum::Contains(BoundingFrustrum frustrum) + { + ContainmentType_t disjoint = ContainmentType::Disjoint; + if (Intersects(frustrum)) + { + disjoint = ContainmentType::Contains; + for (int i = 0; i < Array::Length(cornerArray); i++) + { + if (Contains(frustrum.cornerArray[i]) == ContainmentType::Disjoint) + { + return ContainmentType::Intersects; + } + } + } + return disjoint; + } + + ContainmentType_t BoundingFrustrum::Contains(BoundingSphere sphere) + { + Vector3 center = sphere.Center; + float radius = sphere.Radius; + int num2 = 0; + for (int i = 0; i < Array::Length(planes); i++) + { + float num5 = ((planes[i].Normal.X * center.X) + (planes[i].Normal.Y * center.Y)) + (planes[i].Normal.Z * center.Z); + float num3 = num5 + planes[i].D; + if (num3 > radius) + { + return ContainmentType::Disjoint; + } + if (num3 < -radius) + { + num2++; + } + } + if (num2 != 6) + { + return ContainmentType::Intersects; + } + return ContainmentType::Contains; + } + + ContainmentType_t BoundingFrustrum::Contains(Vector3 point) + { + for (int i = 0; i < Array::Length(planes); i++) + { + float num2 = (((planes[i].Normal.X * point.X) + (planes[i].Normal.Y * point.Y)) + (planes[i].Normal.Z * point.Z)) + planes[i].D; + if (num2 > 1E-05f) + { + return ContainmentType::Disjoint; + } + } + return ContainmentType::Contains; + } + + void BoundingFrustrum::Contains(BoundingBox box, out ContainmentType_t result) + { + bool flag = false; + for (int i = 0; i < Array::Length(planes); i++) + { + switch (box.Intersects(planes[i])) + { + case PlaneIntersectionType::Front: + result = ContainmentType::Disjoint; + return; + + case PlaneIntersectionType::Intersecting: + flag = true; + break; + } + } + result = flag ? ContainmentType::Intersects : ContainmentType::Contains; + } + + void BoundingFrustrum::Contains(BoundingSphere sphere, out ContainmentType_t result) + { + Vector3 center = sphere.Center; + float radius = sphere.Radius; + int num2 = 0; + for (int i = 0; i < Array::Length(planes); i++) + { + float num5 = ((planes[i].Normal.X * center.X) + (planes[i].Normal.Y * center.Y)) + (planes[i].Normal.Z * center.Z); + float num3 = num5 + planes[i].D; + if (num3 > radius) + { + result = ContainmentType::Disjoint; + return; + } + if (num3 < -radius) + { + num2++; + } + } + result = (num2 == 6) ? ContainmentType::Contains : ContainmentType::Intersects; + } + + void BoundingFrustrum::Contains(Vector3 point, out ContainmentType_t result) + { + for (int i = 0; i < Array::Length(planes); i++) + { + float num2 = (((planes[i].Normal.X * point.X) + (planes[i].Normal.Y * point.Y)) + (planes[i].Normal.Z * point.Z)) + planes[i].D; + if (num2 > 1E-05f) + { + result = ContainmentType::Disjoint; + return; + } + } + result = ContainmentType::Contains; + } + + bool BoundingFrustrum::Equals(BoundingFrustrum other) + { + return (matrix == other.matrix); + } + + Vector3* BoundingFrustrum::GetCorners() + { + return cornerArray; + } + + void BoundingFrustrum::GetCorners(Vector3 corners[]) + { + if (corners == null) + { + throw ArgumentNullException("corners"); + } + Array::Copy(cornerArray, 0, corners, 0, Array::Length(cornerArray)); + } + + int BoundingFrustrum::GetHashCode() + { + return matrix.GetHashCode(); + } + + bool BoundingFrustrum::Intersects(BoundingBox box) + { + bool flag; + Intersects(box, flag); + return flag; + } + + bool BoundingFrustrum::Intersects(BoundingFrustrum frustrum) + { + throw NotImplementedException(); + } + + bool BoundingFrustrum::Intersects(BoundingSphere sphere) + { + bool flag; + Intersects(sphere, flag); + return flag; + } + + PlaneIntersectionType_t BoundingFrustrum::Intersects(Plane plane) + { + int num = 0; + for (int i = 0; i < 8; i++) + { + float num3; + Vector3::Dot(cornerArray[i], plane.Normal, num3); + if ((num3 + plane.D) > 0f) + { + num |= 1; + } + else + { + num |= 2; + } + if (num == 3) + { + return PlaneIntersectionType::Intersecting; + } + } + if (num != 1) + { + return PlaneIntersectionType::Back; + } + return PlaneIntersectionType::Front; + } + + float BoundingFrustrum::Intersects(Ray ray) + { + float result; + Intersects(ray, result); + return result; + } + + void BoundingFrustrum::Intersects(BoundingBox box, out bool result) + { + throw NotImplementedException(); + } + + void BoundingFrustrum::Intersects(BoundingSphere sphere, out bool result) + { + throw NotImplementedException(); + } + + void BoundingFrustrum::Intersects(Plane plane, out PlaneIntersectionType_t result) + { + int num = 0; + for (int i = 0; i < 8; i++) + { + float num3; + Vector3::Dot(cornerArray[i], plane.Normal, num3); + if ((num3 + plane.D) > 0f) + { + num |= 1; + } + else + { + num |= 2; + } + if (num == 3) + { + result = PlaneIntersectionType::Intersecting; + return; + } + } + result = (num == 1) ? PlaneIntersectionType::Front : PlaneIntersectionType::Back; + } + + void BoundingFrustrum::Intersects(Ray ray, out float result) + { + ContainmentType_t type; + Contains(ray.Position, type); + if (type == ContainmentType::Contains) + { + result = 0f; + } + else + { + float minValue = float.MinValue; + float maxValue = float.MaxValue; + result = 0; + for (int i = 0; i < Array::Length(planes); i++) + { + float num3; + float num6; + Vector3 normal = planes[i].Normal; + Vector3::Dot(ray.Direction, normal, num6); + Vector3::Dot(ray.Position, normal, num3); + num3 += planes[i].D; + if (Math::Abs(num6) < 1E-05f) + { + if (num3 > 0f) + { + return; + } + } + else + { + float num = -num3 / num6; + if (num6 < 0f) + { + if (num > maxValue) + { + return; + } + if (num > minValue) + { + minValue = num; + } + } + else + { + if (num < minValue) + { + return; + } + if (num < maxValue) + { + maxValue = num; + } + } + } + } + float num7 = (minValue >= 0f) ? minValue : maxValue; + if (num7 >= 0f) + { + result = new float?(num7); + } + } + } + + void BoundingFrustrum::SetMatrix(Matrix value) + { + matrix = value; + planes[2].Normal.X = -value.M14 - value.M11; + planes[2].Normal.Y = -value.M24 - value.M21; + planes[2].Normal.Z = -value.M34 - value.M31; + planes[2].D = -value.M44 - value.M41; + planes[3].Normal.X = -value.M14 + value.M11; + planes[3].Normal.Y = -value.M24 + value.M21; + planes[3].Normal.Z = -value.M34 + value.M31; + planes[3].D = -value.M44 + value.M41; + planes[4].Normal.X = -value.M14 + value.M12; + planes[4].Normal.Y = -value.M24 + value.M22; + planes[4].Normal.Z = -value.M34 + value.M32; + planes[4].D = -value.M44 + value.M42; + planes[5].Normal.X = -value.M14 - value.M12; + planes[5].Normal.Y = -value.M24 - value.M22; + planes[5].Normal.Z = -value.M34 - value.M32; + planes[5].D = -value.M44 - value.M42; + planes[0].Normal.X = -value.M13; + planes[0].Normal.Y = -value.M23; + planes[0].Normal.Z = -value.M33; + planes[0].D = -value.M43; + planes[1].Normal.X = -value.M14 + value.M13; + planes[1].Normal.Y = -value.M24 + value.M23; + planes[1].Normal.Z = -value.M34 + value.M33; + planes[1].D = -value.M44 + value.M43; + for (int i = 0; i < 6; i++) + { + float num2 = planes[i].Normal.Length(); + planes[i].Normal = (planes[i].Normal / num2); + planes[i].D /= num2; + } + Ray ray = ComputeIntersectionLine(planes[0], planes[2]); + cornerArray[0] = ComputeIntersection(planes[4], ray); + cornerArray[3] = ComputeIntersection(planes[5], ray); + ray = ComputeIntersectionLine(planes[3], planes[0]); + cornerArray[1] = ComputeIntersection(planes[4], ray); + cornerArray[2] = ComputeIntersection(planes[5], ray); + ray = ComputeIntersectionLine(planes[2], planes[1]); + cornerArray[4] = ComputeIntersection(planes[4], ray); + cornerArray[7] = ComputeIntersection(planes[5], ray); + ray = ComputeIntersectionLine(planes[1], planes[3]); + cornerArray[5] = ComputeIntersection(planes[4], ray); + cornerArray[6] = ComputeIntersection(planes[5], ray); + } +} diff --git a/src/libXFX/BoundingSphere.cpp b/src/libXFX/BoundingSphere.cpp new file mode 100644 index 0000000..0282e07 --- /dev/null +++ b/src/libXFX/BoundingSphere.cpp @@ -0,0 +1,67 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace XFX +{ + BoundingSphere::BoundingSphere(Vector3 center, float radius) + { + Center = center; + Radius = radius; + } + + BoundingSphere::BoundingSphere(const BoundingSphere &obj) + { + Center = obj.Center; + Radius = obj.Radius; + } + + BoundingSphere::BoundingSphere() + { + Center = Vector3::Zero; + Radius = 0.0f; + } + + int BoundingSphere::operator!=(const BoundingSphere other) + { + return !((Center == other.Center) && (Radius == other.Radius)); + } + + int BoundingSphere::operator==(const BoundingSphere other) + { + return ((Center == other.Center) && (Radius == other.Radius)); + } + + BoundingSphere BoundingSphere::operator=(const BoundingSphere other) + { + Center = other.Center; + Radius = other.Radius; + + return *this; + } +} diff --git a/src/libXFX/Color.cpp b/src/libXFX/Color.cpp new file mode 100644 index 0000000..f799f66 --- /dev/null +++ b/src/libXFX/Color.cpp @@ -0,0 +1,284 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include + +using namespace XFX; + +namespace XFX +{ + namespace Graphics + { + uint Color::RGBAtoARGB(uint value) + { + uint x = ((value >> 0) ^ (value >> 25)) & ((1U << 8) - 1); // XOR temporary + return value ^ ((x << 0) | (x << 25)); + } + + /*** COLOR DEFINITIONS ***/ + const Color Color::AliceBlue = Color(((uint)255 << 24) + ((uint)240 << 16) + ((uint)248 << 8) + 255); + const Color Color::AntiqueWhite = Color(((uint)255 << 24) + ((uint)250 << 16) + ((uint)235 << 8) + 215); + const Color Color::Aqua = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)255 << 8) + 255); + const Color Color::AquaMarine = Color(((uint)255 << 24) + ((uint)127 << 16) + ((uint)255 << 8) + 212); + const Color Color::Azure = Color(((uint)255 << 24) + ((uint)240 << 16) + ((uint)255 << 8) + 255); + const Color Color::Beige = Color(((uint)255 << 24) + ((uint)245 << 16) + ((uint)245 << 8) + 220); + const Color Color::Bisque = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)228 << 8) + 196); + const Color Color::Black = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)0 << 8) + 0); + const Color Color::BlanchedAlmond = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)235 << 8) + 205); + const Color Color::Blue = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)0 << 8) + 255); + const Color Color::BlueViolet = Color(((uint)255 << 24) + ((uint)138 << 16) + ((uint)43 << 8) + 226); + const Color Color::Brown = Color(((uint)255 << 24) + ((uint)165 << 16) + ((uint)42 << 8) + 42); + const Color Color::BurlyWood = Color(((uint)255 << 24) + ((uint)222 << 16) + ((uint)184 << 8) + 135); + const Color Color::CadetBlue = Color(((uint)255 << 24) + ((uint)95 << 16) + ((uint)158 << 8) + 160); + const Color Color::Chartreuse = Color(((uint)255 << 24) + ((uint)127 << 16) + ((uint)255 << 8) + 0); + const Color Color::Chocolate = Color(((uint)255 << 24) + ((uint)210 << 16) + ((uint)105 << 8) + 30); + const Color Color::Coral = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)127 << 8) + 80); + const Color Color::CornflowerBlue = Color(((uint)255 << 24) + ((uint)100 << 16) + ((uint)149 << 8) + 237); + const Color Color::Cornsilk = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)248 << 8) + 220); + const Color Color::Crimson = Color(((uint)255 << 24) + ((uint)220 << 16) + ((uint)20 << 8) + 60); + const Color Color::Cyan = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)255 << 8) + 255); + const Color Color::DarkBlue = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)0 << 8) + 139); + const Color Color::DarkCyan = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)139 << 8) + 139); + const Color Color::DarkGoldenrod = Color(((uint)255 << 24) + ((uint)184 << 16) + ((uint)134 << 8) + 11); + const Color Color::DarkGray = Color(((uint)255 << 24) + ((uint)169 << 16) + ((uint)169 << 8) + 169); + const Color Color::DarkGreen = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)100 << 8) + 0); + const Color Color::DarkKhaki = Color(((uint)255 << 24) + ((uint)189 << 16) + ((uint)183 << 8) + 107); + const Color Color::DarkMagenta = Color(((uint)255 << 24) + ((uint)139 << 16) + ((uint)0 << 8) + 139); + const Color Color::DarkOliveGreen = Color(((uint)255 << 24) + ((uint)85 << 16) + ((uint)107 << 8) + 47); + const Color Color::DarkOrange = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)140 << 8) + 0); + const Color Color::DarkOrchid = Color(((uint)255 << 24) + ((uint)153 << 16) + ((uint)50 << 8) + 204); + const Color Color::DarkRed = Color(((uint)255 << 24) + ((uint)139 << 16) + ((uint)0 << 8) + 0); + const Color Color::DarkSalmon = Color(((uint)255 << 24) + ((uint)233 << 16) + ((uint)150 << 8) + 122); + const Color Color::DarkSeaGreen = Color(((uint)255 << 24) + ((uint)143 << 16) + ((uint)188 << 8) + 139); + const Color Color::DarkSlateBlue = Color(((uint)255 << 24) + ((uint)72 << 16) + ((uint)61 << 8) + 139); + const Color Color::DarkSlateGray = Color(((uint)255 << 24) + ((uint)47 << 16) + ((uint)79 << 8) + 79); + const Color Color::DarkTurquoise = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)206 << 8) + 209); + const Color Color::DarkViolet = Color(((uint)255 << 24) + ((uint)148 << 16) + ((uint)0 << 8) + 211); + const Color Color::DeepPink = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)20 << 8) + 147); + const Color Color::DeepSkyBlue = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)191 << 8) + 255); + const Color Color::DimGray = Color(((uint)255 << 24) + ((uint)105 << 16) + ((uint)105 << 8) + 105); + const Color Color::DodgerBlue = Color(((uint)255 << 24) + ((uint)30 << 16) + ((uint)144 << 8) + 255); + const Color Color::FireBrick = Color(((uint)255 << 24) + ((uint)178 << 16) + ((uint)34 << 8) + 34); + const Color Color::FloralWhite = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)250 << 8) + 240); + const Color Color::ForestGreen = Color(((uint)255 << 24) + ((uint)34 << 16) + ((uint)139 << 8) + 34); + const Color Color::Fuchsia = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)0 << 8) + 255); + const Color Color::Gainsboro = Color(((uint)255 << 24) + ((uint)220 << 16) + ((uint)220 << 8) + 220); + const Color Color::GhostWhite = Color(((uint)255 << 24) + ((uint)248 << 16) + ((uint)248 << 8) + 255); + const Color Color::Gold = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)215 << 8) + 0); + const Color Color::Goldenrod = Color(((uint)255 << 24) + ((uint)218 << 16) + ((uint)165 << 8) + 32); + const Color Color::Gray = Color(((uint)255 << 24) + ((uint)128 << 16) + ((uint)128 << 8) + 128); + const Color Color::Green = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)128 << 8) + 0); + const Color Color::GreenYellow = Color(((uint)255 << 24) + ((uint)173 << 16) + ((uint)255 << 8) + 47); + const Color Color::Honeydew = Color(((uint)255 << 24) + ((uint)240 << 16) + ((uint)255 << 8) + 240); + const Color Color::HotPink = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)105 << 8) + 180); + const Color Color::IndianRed = Color(((uint)255 << 24) + ((uint)205 << 16) + ((uint)92 << 8) + 92); + const Color Color::Indigo = Color(((uint)255 << 24) + ((uint)75 << 16) + ((uint)0 << 8) + 130); + const Color Color::Ivory = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)255 << 8) + 240); + const Color Color::Khaki = Color(((uint)255 << 24) + ((uint)240 << 16) + ((uint)230 << 8) + 140); + const Color Color::Lavender = Color(((uint)255 << 24) + ((uint)230 << 16) + ((uint)230 << 8) + 250); + const Color Color::LavenderBlush = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)240 << 8) + 245); + const Color Color::LawnGreen = Color(((uint)255 << 24) + ((uint)124 << 16) + ((uint)252 << 8) + 0); + const Color Color::LemonChiffon = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)250 << 8) + 205); + const Color Color::LightBlue = Color(((uint)255 << 24) + ((uint)173 << 16) + ((uint)216 << 8) + 230); + const Color Color::LightCoral = Color(((uint)255 << 24) + ((uint)240 << 16) + ((uint)128 << 8) + 128); + const Color Color::LightCyan = Color(((uint)255 << 24) + ((uint)224 << 16) + ((uint)255 << 8) + 255); + const Color Color::LightGoldenrodYellow = Color(((uint)255 << 24) + ((uint)250 << 16) + ((uint)250 << 8) + 210); + const Color Color::LightGray = Color(((uint)255 << 24) + ((uint)211 << 16) + ((uint)211 << 8) + 211); + const Color Color::LightGreen = Color(((uint)255 << 24) + ((uint)144 << 16) + ((uint)238 << 8) + 144); + const Color Color::LightPink = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)182 << 8) + 193); + const Color Color::LightSalmon = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)160 << 8) + 122); + const Color Color::LightSeaGreen = Color(((uint)255 << 24) + ((uint)32 << 16) + ((uint)178 << 8) + 170); + const Color Color::LightSkyBlue = Color(((uint)255 << 24) + ((uint)135 << 16) + ((uint)206 << 8) + 250); + const Color Color::LightSlateGray = Color(((uint)255 << 24) + ((uint)119 << 16) + ((uint)136 << 8) + 153); + const Color Color::LightSteelBlue = Color(((uint)255 << 24) + ((uint)176 << 16) + ((uint)196 << 8) + 222); + const Color Color::LightYellow = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)255 << 8) + 224); + const Color Color::Lime = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)255 << 8) + 0); + const Color Color::LimeGreen = Color(((uint)255 << 24) + ((uint)50 << 16) + ((uint)205 << 8) + 50); + const Color Color::Linen = Color(((uint)255 << 24) + ((uint)250 << 16) + ((uint)240 << 8) + 230); + const Color Color::Magenta = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)0 << 8) + 255); + const Color Color::Maroon = Color(((uint)255 << 24) + ((uint)128 << 16) + ((uint)0 << 8) + 0); + const Color Color::MediumAquamarine = Color(((uint)255 << 24) + ((uint)102 << 16) + ((uint)205 << 8) + 170); + const Color Color::MediumBlue = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)0 << 8) + 205); + const Color Color::MediumOrchid = Color(((uint)255 << 24) + ((uint)186 << 16) + ((uint)85 << 8) + 211); + const Color Color::MediumPurple = Color(((uint)255 << 24) + ((uint)147 << 16) + ((uint)112 << 8) + 219); + const Color Color::MediumSeaGreen = Color(((uint)255 << 24) + ((uint)60 << 16) + ((uint)179 << 8) + 113); + const Color Color::MediumSlateBlue = Color(((uint)255 << 24) + ((uint)123 << 16) + ((uint)104 << 8) + 238); + const Color Color::MediumSpringGreen = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)250 << 8) + 154); + const Color Color::MediumTurquoise = Color(((uint)255 << 24) + ((uint)72 << 16) + ((uint)209 << 8) + 204); + const Color Color::MediumVioletRed = Color(((uint)255 << 24) + ((uint)199 << 16) + ((uint)21 << 8) + 133); + const Color Color::MidnightBlue = Color(((uint)255 << 24) + ((uint)25 << 16) + ((uint)25 << 8) + 112); + const Color Color::MintCream = Color(((uint)255 << 24) + ((uint)245 << 16) + ((uint)255 << 8) + 250); + const Color Color::MistyRose = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)228 << 8) + 225); + const Color Color::Moccasin = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)228 << 8) + 181); + const Color Color::NavajoWhite = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)222 << 8) + 173); + const Color Color::Navy = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)0 << 8) + 128); + const Color Color::OldLace = Color(((uint)255 << 24) + ((uint)253 << 16) + ((uint)245 << 8) + 230); + const Color Color::Olive = Color(((uint)255 << 24) + ((uint)128 << 16) + ((uint)128 << 8) + 0); + const Color Color::OliveDrab = Color(((uint)255 << 24) + ((uint)107 << 16) + ((uint)142 << 8) + 35); + const Color Color::Orange = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)165 << 8) + 0); + const Color Color::OrangeRed = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)69 << 8) + 0); + const Color Color::Orchid = Color(((uint)255 << 24) + ((uint)218 << 16) + ((uint)112 << 8) + 214); + const Color Color::PaleGoldenrod = Color(((uint)255 << 24) + ((uint)238 << 16) + ((uint)232 << 8) + 170); + const Color Color::PaleGreen = Color(((uint)255 << 24) + ((uint)152 << 16) + ((uint)251 << 8) + 152); + const Color Color::PaleTurquoise = Color(((uint)255 << 24) + ((uint)175 << 16) + ((uint)238 << 8) + 238); + const Color Color::PaleVioletRed = Color(((uint)255 << 24) + ((uint)219 << 16) + ((uint)112 << 8) + 147); + const Color Color::PapayaWhip = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)239 << 8) + 213); + const Color Color::PeachPuff = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)218 << 8) + 185); + const Color Color::Peru = Color(((uint)255 << 24) + ((uint)205 << 16) + ((uint)133 << 8) + 63); + const Color Color::Pink = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)192 << 8) + 203); + const Color Color::Plum = Color(((uint)255 << 24) + ((uint)221 << 16) + ((uint)160 << 8) + 221); + const Color Color::PowderBlue = Color(((uint)255 << 24) + ((uint)176 << 16) + ((uint)224 << 8) + 230); + const Color Color::Purple = Color(((uint)255 << 24) + ((uint)128 << 16) + ((uint)0 << 8) + 128); + const Color Color::Red = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)0 << 8) + 0); + const Color Color::RosyBrown = Color(((uint)255 << 24) + ((uint)188 << 16) + ((uint)143 << 8) + 143); + const Color Color::RoyalBlue = Color(((uint)255 << 24) + ((uint)65 << 16) + ((uint)105 << 8) + 225); + const Color Color::SaddleBrown = Color(((uint)255 << 24) + ((uint)139 << 16) + ((uint)69 << 8) + 19); + const Color Color::Salmon = Color(((uint)255 << 24) + ((uint)250 << 16) + ((uint)128 << 8) + 114); + const Color Color::SandyBrown = Color(((uint)255 << 24) + ((uint)244 << 16) + ((uint)164 << 8) + 96); + const Color Color::SeaGreen = Color(((uint)255 << 24) + ((uint)46 << 16) + ((uint)139 << 8) + 87); + const Color Color::SeaShell = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)245 << 8) + 238); + const Color Color::Sienna = Color(((uint)255 << 24) + ((uint)160 << 16) + ((uint)82 << 8) + 45); + const Color Color::Silver = Color(((uint)255 << 24) + ((uint)192 << 16) + ((uint)192 << 8) + 192); + const Color Color::SkyBlue = Color(((uint)255 << 24) + ((uint)135 << 16) + ((uint)206 << 8) + 235); + const Color Color::SlateBlue = Color(((uint)255 << 24) + ((uint)106 << 16) + ((uint)90 << 8) + 205); + const Color Color::SlateGray = Color(((uint)255 << 24) + ((uint)112 << 16) + ((uint)128 << 8) + 144); + const Color Color::Snow = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)250 << 8) + 250); + const Color Color::SpringGreen = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)255 << 8) + 127); + const Color Color::SteelBlue = Color(((uint)255 << 24) + ((uint)70 << 16) + ((uint)130 << 8) + 180); + const Color Color::Tan = Color(((uint)255 << 24) + ((uint)210 << 16) + ((uint)180 << 8) + 140); + const Color Color::Teal = Color(((uint)255 << 24) + ((uint)0 << 16) + ((uint)128 << 8) + 128); + const Color Color::Thistle = Color(((uint)255 << 24) + ((uint)216 << 16) + ((uint)191 << 8) + 216); + const Color Color::Tomato = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)99 << 8) + 71); + const Color Color::Turquoise = Color(((uint)255 << 24) + ((uint)64 << 16) + ((uint)224 << 8) + 208); + const Color Color::Violet = Color(((uint)255 << 24) + ((uint)238 << 16) + ((uint)130 << 8) + 238); + const Color Color::Wheat = Color(((uint)255 << 24) + ((uint)245 << 16) + ((uint)222 << 8) + 179); + const Color Color::White = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)255 << 8) + 255); + const Color Color::WhiteSmoke = Color(((uint)255 << 24) + ((uint)245 << 16) + ((uint)245 << 8) + 245); + const Color Color::Yellow = Color(((uint)255 << 24) + ((uint)255 << 16) + ((uint)255 << 8) + 0); + const Color Color::YellowGreen = Color(((uint)255 << 24) + ((uint)154 << 16) + ((uint)205 << 8) + 50); + /*** END OF COLOR DEFINITIONS ***/ + + byte Color::A() + { + return (uint)((_packedValue >> 24 & 0xff)); + } + + byte Color::B() + { + return (uint)(_packedValue & 0xff); + } + + byte Color::G() + { + return (uint)((_packedValue >> 8 & 0xff)); + } + + byte Color::R() + { + return (uint)((_packedValue >> 16 & 0xff)); + } + + Color::Color(uint packedValue) + { + _packedValue = packedValue; + } + + Color::Color(Vector3 vector) + { + _packedValue = InitializeFromVector3(vector); + } + + Color::Color(Vector4 vector) + { + _packedValue = InitializeFromVector4(vector); + } + + Color::Color(byte r, byte g, byte b) + { + _packedValue = (uint)(255 << 24) + (uint)(r << 16) + (uint)(g << 8) + b; + } + + Color::Color(byte r, byte g, byte b, byte a) + { + _packedValue = (uint)(a << 24) + (uint)(r << 16) + (uint)(g << 8) + b; + } + + bool Color::Equals(Color other) + { + return (_packedValue == other._packedValue); + } + + int Color::GetHashCode() + { + return (int)_packedValue; + } + + uint Color::PackedValue() + { + return _packedValue; + } + + uint Color::InitializeFromVector4(Vector4 value) + { + byte r = (byte)(Math::Round(value.X * 255)); + byte g = (byte)(Math::Round(value.Y * 255)); + byte b = (byte)(Math::Round(value.Z * 255)); + byte a = (byte)(Math::Round(value.W * 255)); + return ((uint)a << 24) + ((uint)r << 16) + ((uint)g << 8) + b; + } + + uint Color::InitializeFromVector3(Vector3 value) + { + byte r = (byte)(Math::Round(value.X * 255)); + byte g = (byte)(Math::Round(value.Y * 255)); + byte b = (byte)(Math::Round(value.Z * 255)); + return ((uint)255 << 24) + ((uint)r << 16) + ((uint)g << 8) + b; + } + + Vector4 Color::ToVector4() + { + return Vector4((float)R() / 255, (float)G() / 255, (float)B() / 255, (float)A() / 255); + } + + Vector3 Color::ToVector3() + { + return Vector3((float)R() / 255, (float)G() / 255, (float)B() / 255); + } + + bool Color::operator!=(const Color other) + { + return !Equals(other); + } + + bool Color::operator==(const Color other) + { + return Equals(other); + } + } +} diff --git a/src/libXFX/ContentManager.cpp b/src/libXFX/ContentManager.cpp new file mode 100644 index 0000000..46306b0 --- /dev/null +++ b/src/libXFX/ContentManager.cpp @@ -0,0 +1,180 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include +#include +#include + +#include + +#if ENABLE_XBOX +extern "C" { +#include +} +#else + +#endif + +using namespace System; + +namespace XFX +{ + namespace Content + { + ContentManager::ContentManager() + { + RootDirectory = ""; + } + + ContentManager::ContentManager(char* rootDirectory) + { + if(rootDirectory == null) + throw ArgumentNullException("'rootDirectory' cannot be NULL."); + + RootDirectory = rootDirectory; + } + + ContentManager::~ContentManager() + { + Dispose(false); + } + + void ContentManager::Dispose(bool disposing) + { + if (!disposed) + { + if (disposing) + { + // Dispose any managed resources + Unload(); + } + // Dispose any unmanaged resources + disposed = true; + } + } + + void ContentManager::Dispose() + { + Dispose(true); + } + + template + T ContentManager::Load(char* assetName) + { + /* TODO: port the C# code below to C++ + object obj2; + if (this.loadedAssets == null) + { + throw new ObjectDisposedException(this.ToString()); + } + if (string.IsNullOrEmpty(assetName)) + { + throw new ArgumentNullException("assetName"); + } + assetName = GetCleanPath(assetName); + if (this.loadedAssets.TryGetValue(assetName, out obj2)) + { + if (!(obj2 is T)) + { + throw new ContentLoadException(string.Format(CultureInfo.CurrentCulture, FrameworkResources.BadXnbWrongType, new object[] { assetName, obj2.GetType(), typeof(T) })); + } + return (T) obj2; + } + T local = this.ReadAsset(assetName, null); + this.loadedAssets.Add(assetName, local); + return local; + */ + } + + Stream ContentManager::OpenStream(char* assetName) + { + Stream stream; + try + { + int len = strlen(assetName); + + if (assetName[len-4] != '.') + { + //! XNA-style assetName, huh? Then it must be an .xnb file. + char* path = Path::Combine(RootDirectory, strcat(assetName, ".xnb")); + stream = File::OpenRead(path); + } + else + { + //! just a normal, for example, .png file + stream = File::OpenRead(assetName); + } + } + catch(FileNotFoundException fileNotFound) + { + throw ContentLoadException("The content file was not found.", fileNotFound); + } + catch(DirectoryNotFoundException directoryNotFound) + { + throw ContentLoadException("The directory was not found.", directoryNotFound); + } + catch(Exception exception) + { + throw ContentLoadException("Error opening stream.", exception); + } + return stream; + } + + template + T ContentManager::ReadAsset(char* assetName) + { + if(disposed) + throw ObjectDisposedException("ContentManager"); + + if (assetName == "" || assetName == null) + throw ArgumentNullException("assetName"); + + Stream assetStream = OpenStream(assetName); + + ContentReader reader = ContentReader(this, assetStream, assetName); + + return reader.ReadAsset(); + } + + void ContentManager::Unload() + { + if(disposed) + throw ObjectDisposedException("ContentManager"); + + for(int i = 0; i < disposableAssets.Count(); i++) + { + disposableAssets[i].Dispose(); + } + //loadedAssets.Clear(); + disposableAssets.Clear(); + } + } +} diff --git a/src/libXFX/ContentReader.cpp b/src/libXFX/ContentReader.cpp new file mode 100644 index 0000000..5db4a69 --- /dev/null +++ b/src/libXFX/ContentReader.cpp @@ -0,0 +1,86 @@ +#include +#include +#include +#include +#include +#include + +namespace XFX +{ + namespace Content + { + const short ContentReader::XnbVersion = 2; + + ContentReader::ContentReader(ContentManager manager, Stream stream, GraphicsDevice graphicsDevice) + : BinaryReader(stream) + { + _graphicsDevice = graphicsDevice; + } + + ContentReader::ContentReader(ContentManager manager, Stream input, char* assetName) + : BinaryReader(PrepareStream(input, assetName)) + { + contentManager = manager; + _assetName = assetName; + } + + Matrix ContentReader::ReadMatrix() + { + Matrix result; + result.M11 = ReadSingle(); + result.M12 = ReadSingle(); + result.M13 = ReadSingle(); + result.M14 = ReadSingle(); + result.M21 = ReadSingle(); + result.M22 = ReadSingle(); + result.M23 = ReadSingle(); + result.M24 = ReadSingle(); + result.M31 = ReadSingle(); + result.M32 = ReadSingle(); + result.M33 = ReadSingle(); + result.M34 = ReadSingle(); + result.M41 = ReadSingle(); + result.M42 = ReadSingle(); + result.M43 = ReadSingle(); + result.M44 = ReadSingle(); + return result; + } + + Quaternion ContentReader::ReadQuaternion() + { + Quaternion result; + result.X = ReadSingle(); + result.Y = ReadSingle(); + result.Z = ReadSingle(); + result.W = ReadSingle(); + return result; + } + + Vector2 ContentReader::ReadVector2() + { + Vector2 result; + result.X = ReadSingle(); + result.Y = ReadSingle(); + return result; + } + + Vector3 ContentReader::ReadVector3() + { + Vector3 result; + result.X = ReadSingle(); + result.Y = ReadSingle(); + result.Z = ReadSingle(); + return result; + } + + Vector4 ContentReader::ReadVector4() + { + Vector4 result; + result.X = ReadSingle(); + result.Y = ReadSingle(); + result.Z = ReadSingle(); + result.W = ReadSingle(); + return result; + } + } +} diff --git a/src/libXFX/DepthStencilBuffer.cpp b/src/libXFX/DepthStencilBuffer.cpp new file mode 100644 index 0000000..8a81824 --- /dev/null +++ b/src/libXFX/DepthStencilBuffer.cpp @@ -0,0 +1,73 @@ +#include + +namespace XFX +{ + namespace Graphics + { + DepthStencilBuffer() + { + _width = 0; + _height = 0; + _format = DepthFormat::Unknown; + _multiSampleType = MultiSampleType::None; + isDisposed = false; + } + + DepthStencilBuffer::DepthStencilBuffer(GraphicsDevice &graphicsDevice, int width, int height, DepthFormat_t format) + { + _width = width; + _height = height; + _format = format; + _multiSampleType = MultiSampleType::None; + isDisposed = false; + } + + DepthStencilBuffer(GraphicsDevice &graphicsDevice, int width, int height, DepthFormat_t format, MultiSampleType_t multiSampleType, int multiSampleQuality) + { + _width = width; + _height = height; + _format = format; + _multiSampleType = multiSampleType; + isDisposed = false; + } + + DepthFormat_t DepthStencilBuffer::Format() + { + return _format; + } + + GraphicsDevice DepthStencilBuffer::GraphicsDevice_() + { + return _graphicsDevice; + } + + int DepthStencilBuffer::IsDisposed() + { + return isDisposed(); + } + + int DepthStencilBuffer::Height() + { + return _height; + } + + int DepthStencilBuffer::Width() + { + return _width; + } + + void DepthStencilBuffer::Dispose() + { + Dispose(true); + } + + void DepthStencilBuffer::Dispose(int __p1) + { + if(__p1) + { + } + + isDisposed = true; + } + } +} diff --git a/src/libXFX/DisplayMode.cpp b/src/libXFX/DisplayMode.cpp new file mode 100644 index 0000000..32cac2a --- /dev/null +++ b/src/libXFX/DisplayMode.cpp @@ -0,0 +1,80 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include + +namespace XFX +{ + namespace Graphics + { + float DisplayMode::AspectRatio() + { + return Width / Height; + } + + Rectangle DisplayMode::TitleSafeArea() + { +#if !ENABLE_XBOX //if we're running on a computer, this is the full screen. + return Rectangle(0, 0, Width, Height); +#else + //based on my own findings on an SD TV set, this roughly equates to a resolution of 600 * 450 + //however, that's on a normal 4:3 TV, and not a Widescreen 0_o' + //Either I get a widescreen or let someone else verify correctness. + return Rectangle(20, 0, Width - 20, Height - 30); +#endif + } + + DisplayMode::DisplayMode() + { + Width = 0; + Height = 0; + Format = SurfaceFormat::Unknown; + RefreshRate = 50; + } + + bool DisplayMode::Equals(const DisplayMode other) + { + return ((Width == other.Width) && (Height == other.Height) && (Format == other.Format)); + } + + int DisplayMode::GetHashCode() + { + return (int)AspectRatio() ^ Width ^ Height ^ TitleSafeArea().GetHashCode() ^ Format ^ RefreshRate; + } + + bool DisplayMode::operator!=(const DisplayMode other) + { + return !Equals(other); + } + + bool DisplayMode::operator==(const DisplayMode other) + { + return Equals(other); + } + } +} diff --git a/src/libXFX/GamePad.cpp b/src/libXFX/GamePad.cpp new file mode 100644 index 0000000..2cea878 --- /dev/null +++ b/src/libXFX/GamePad.cpp @@ -0,0 +1,171 @@ +// Copyright (C) 2010-2012, Halofreak_1990 +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +extern "C"{ +#ifdef ENABLE_XBOX +#include "xinput.h" +#else +#endif +} + +#include +#include + +namespace XFX +{ + namespace Input + { + GamePadState g_State; + + GamePadState GamePad::GetState(PlayerIndex_t playerIndex) + { + //Update IsConnected + g_State.IsConnected = g_Pads[playerIndex].hPresent; + + //Update Button presses + if(g_Pads[playerIndex].PressedButtons.ucAnalogButtons[XPAD_A]) + g_State.Buttons.A = ButtonState::Pressed; + else + g_State.Buttons.A = ButtonState::Released; + if(g_Pads[playerIndex].PressedButtons.ucAnalogButtons[XPAD_B]) + g_State.Buttons.B = ButtonState::Pressed; + else + g_State.Buttons.B = ButtonState::Released; + if(g_Pads[playerIndex].CurrentButtons.usDigitalButtons & XPAD_BACK) + g_State.Buttons.Back = ButtonState::Pressed; + else + g_State.Buttons.Back = ButtonState::Released; + if(g_Pads[playerIndex].PressedButtons.ucAnalogButtons[XPAD_BLACK]) + g_State.Buttons.Black = ButtonState::Pressed; + else + g_State.Buttons.Black = ButtonState::Released; + if(g_Pads[playerIndex].PressedButtons.ucAnalogButtons[XPAD_LEFT_THUMB]) + g_State.ThumbSticks.Left = ButtonState::Pressed; + else + g_State.ThumbSticks.Left = ButtonState::Released; + if(g_Pads[playerIndex].PressedButtons.ucAnalogButtons[XPAD_RIGHT_THUMB]) + g_State.ThumbSticks.Right = ButtonState::Pressed; + else + g_State.ThumbSticks.Right = ButtonState::Released; + if(g_Pads[playerIndex].CurrentButtons.usDigitalButtons & XPAD_START) + g_State.Buttons.Start = ButtonState::Pressed; + else + g_State.Buttons.Start = ButtonState::Released; + if(g_Pads[playerIndex].PressedButtons.ucAnalogButtons[XPAD_WHITE]) + g_State.Buttons.B = ButtonState::Pressed; + else + g_State.Buttons.B = ButtonState::Released; + if(g_Pads[playerIndex].PressedButtons.ucAnalogButtons[XPAD_X]) + g_State.Buttons.X = ButtonState::Pressed; + else + g_State.Buttons.X = ButtonState::Released; + if(g_Pads[playerIndex].PressedButtons.ucAnalogButtons[XPAD_Y]) + g_State.Buttons.Y = ButtonState::Pressed; + else + g_State.Buttons.Y = ButtonState::Released; + + //Update DPad + if(g_Pads[playerIndex].CurrentButtons.usDigitalButtons & XPAD_DPAD_DOWN) + g_State.DPad.Down = ButtonState::Pressed; + else + g_State.DPad.Down = ButtonState::Released; + if(g_Pads[playerIndex].CurrentButtons.usDigitalButtons & XPAD_DPAD_LEFT) + g_State.DPad.Left = ButtonState::Pressed; + else + g_State.DPad.Left = ButtonState::Released; + if(g_Pads[playerIndex].CurrentButtons.usDigitalButtons & XPAD_DPAD_RIGHT) + g_State.DPad.Right = ButtonState::Pressed; + else + g_State.DPad.Right = ButtonState::Released; + if(g_Pads[playerIndex].CurrentButtons.usDigitalButtons & XPAD_DPAD_UP) + g_State.DPad.Up = ButtonState::Pressed; + else + g_State.DPad.Up = ButtonState::Released; + + //Update ThumbStick values + g_State.ThumbSticks.Left.X = g_Pads[playerIndex].sLThumbX; + g_State.ThumbSticks.Left.Y = -g_Pads[playerIndex].sLThumbY; + g_State.ThumbSticks.Right.X = g_Pads[playerIndex].sRThumbX; + g_State.ThumbSticks.Right.Y = -g_Pads[playerIndex].sRThumbY; + + return g_State; + } + + int GamePad::SetVibration(PlayerIndex_t playerIndex, float leftMotor, float rightMotor) + { + //If the controller is Disconnected, why bother? + if(GetState(playerIndex).IsConnected == false) + { + return -1; + } + else + { + int iWhichPad = 0; + + byte leftSpeed = (byte)(MathHelper::Clamp(leftMotor, 0.0f, 1.0f) * 255); + byte rightSpeed = (byte)(MathHelper::Clamp(rightMotor, 0.0f, 1.0f) * 255); + + switch(playerIndex) + { + case PlayerIndex::One: + iWhichPad = 3; + break; + case PlayerIndex::Two: + iWhichPad = 4; + break; + case PlayerIndex::Three: + iWhichPad = 1; + break; + case PlayerIndex::Four: + iWhichPad = 2; + break; + default: + throw InvalidOperationException(); + return false; + } + + usbd_device dev; + dev.p_ohci = &(xin->my_ohci); + dev.address = iWhichPad; // This will choose the first gamepad it finds, only for debug + + byte data1[6] = { 0, 6, 0, leftSpeed, 0, rightSpeed }; // rumble data + usb_bulk_msg(&dev, 6, (void*)data1); // simple bulk send function (in pad.c/.h) + } + } + + bool GamePadState::operator ==(GamePadState other) + { + return ((IsConnected == other.IsConnected) && (ThumbSticks == other.ThumbSticks) && + (Triggers == other.Triggers) && (DPad == other.DPad) && (Buttons == other.Buttons)); + } + + bool GamePadState::operator !=(GamePadState other) + { + return !(*this == other); + } + } +} diff --git a/src/libXFX/GraphicsAdapter.cpp b/src/libXFX/GraphicsAdapter.cpp new file mode 100644 index 0000000..a93e97a --- /dev/null +++ b/src/libXFX/GraphicsAdapter.cpp @@ -0,0 +1,150 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include "PBKit/pbKit.h" +#include + +#if ENABLE_XBOX +#include +#endif + +namespace XFX +{ + namespace Graphics + { + char* GraphicsAdapter::Description() + { +#if ENABLE_XBOX + //TODO: Come up with a device description +#else + //TODO: Get Device Description +#endif + } + + int GraphicsAdapter::DeviceId() + { +#if ENABLE_XBOX + return 0x2a0; +#else + //TODO: Get Device ID +#endif + } + + char* GraphicsAdapter::DeviceName() + { +#if ENABLE_XBOX + return "NV2A"; +#else + //TODO: Get Device Name +#endif + } + + char* GraphicsAdapter::DriverDLL() + { +#if ENABLE_XBOX + return "pbKit"; +#else + //TODO: Get Driver DLL +#endif + } + + float GraphicsAdapter::DriverVersion() + { +#if ENABLE_XBOX + return 1.0; +#else + //TODO: Get Driver Version +#endif + } + + bool GraphicsAdapter::IsDefaultAdapter() + { +#if ENABLE_XBOX + return true; +#else + //TODO: Find out whther this device is the Default Adapter +#endif + } + + int GraphicsAdapter::VendorId() + { +#if ENABLE_XBOX + return 0x10DE; +#else + //TODO: Get VendorId +#endif + } + + bool GraphicsAdapter::IsWideScreen() + { +#if ENABLE_XBOX + return false; +#else + //TODO: Get IsWideScreen +#endif + } + + DisplayMode GraphicsAdapter::CurrentDisplayMode() + { + DisplayMode disp; + +#if ENABLE_XBOX + VIDEO_MODE mode = XVideoGetMode(); + disp.Height = mode.height; + disp.RefreshRate = mode.refresh; + disp.Width = mode.width; + + //FIXME: get the proper SurfaceFormat for 16-bit + switch(mode.bpp) + { + case 32: disp.Format = SurfaceFormat::Color; + case 24: disp.Format = SurfaceFormat::Rgb32; + case 8: disp.Format = SurfaceFormat::Palette8; + default: disp.Format = SurfaceFormat::Unknown; + } +#else + //TODO: Get the screen surface format, dimensions, and refreshRate, and store them in the 'disp' variable +#endif + return disp; + } + + bool GraphicsAdapter::IsDeviceTypeAvailable(DeviceType_t deviceType) + { +#if ENABLE_XBOX + switch(deviceType) + { + case DeviceType::Hardware: return true; + case DeviceType::NullReference: return false; + case DeviceType::Reference: return false; + default: return false; + } +#else + //TODO: Add code to check this on Linux +#endif + } + } +} diff --git a/src/libXFX/GraphicsDevice.cpp b/src/libXFX/GraphicsDevice.cpp new file mode 100644 index 0000000..4476fbe --- /dev/null +++ b/src/libXFX/GraphicsDevice.cpp @@ -0,0 +1,170 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include + +#ifdef ENABLE_XBOX +#include "pbKit.h" +#else +#include "gl.h" +#endif + +using namespace System; +using namespace XFX; + +namespace XFX +{ + namespace Graphics + { + TextureCollection GraphicsDevice::Textures() + { + return textures; + } + +#if ENABLE_XBOX + GraphicsDevice::GraphicsDevice(GraphicsAdapter adapter, DeviceType_t deviceType, CreateOptions_t creationOptions, PresentationParameters presentationParameters) + { + _adapter = adapter; + if(_deviceType != DeviceType::Hardware) + throw DeviceNotSupportedException("Only DeviceType::Hardware is supported."); + + _deviceType = devicetype; + clearColor = Color::Black; + } +#else + GraphicsDevice::GraphicsDevice(GraphicsAdapter adapter, DeviceType_t deviceType, IntPtr renderWindowHandle, PresentationParameters presentationParameters) + { + _adapter = adapter; + _deviceType = devicetype; + clearColor = Color::Black; + } +#endif + + GraphicsDevice::GraphicsDevice() + { + + } + + GraphicsDevice::~GraphicsDevice() + { + Dispose(false); + } + + void GraphicsDevice::Clear(Color color) + { +#ifdef ENABLE_XBOX + DWORD *p; + DWORD format; + DWORD depth; + + int x1,y1,x2,y2; + + //Set the coordinates for the rectangle to be cleared + x1 = 0; + y1 = 0; + x2 = x1 + _depthStencilBuffer.Width(); + y2 = y1 + _depthStencilBuffer.Height(); + + switch(_depthStencilBuffer.Format()) + { + case DepthFormat::Depth24Stencil4: {format = 0x03; depth = 0xffffff0;} + case DepthFormat::Depth24Stencil8: {format = 0x03; depth = 0xffffff00;} + case DepthFormat::Depth32: {format = 0x03; depth = 0xffffffff;} + case DepthFormat::Unknown: + default: return; + } + + p=pb_begin(); + pb_push(p++,NV20_TCL_PRIMITIVE_3D_CLEAR_VALUE_HORIZ,2); //sets rectangle coordinates + *(p++)=((x2-1)<<16)|x1; + *(p++)=((y2-1)<<16)|y1; + pb_push(p++,NV20_TCL_PRIMITIVE_3D_CLEAR_VALUE_DEPTH,3); //sets data used to fill in rectangle + *(p++)=depth; //depth to clear + *(p++)=color.PackedValue(); //color + *(p++)=format; //triggers the HW rectangle fill (only on D&S) + pb_end(p); + + if(color != clearColor) + clearColor = color; +#else + if(color != clearColor) + { + glClearColor((float)color.R/255f, (float)color.G/255f, (float)color.B/255f, (float)color.A/255f); + clearColor = color; + } + glClear(GL_COLOR_BUFFER_BIT); + glLoadIdentity(); +#endif + } + + void GraphicsDevice::Clear(ClearOptions_t options, Color color, float depth, int stencil) + { + if(isDisposed) + throw ObjectDisposedException(); + + switch(options) + { + case ClearOptions::Depth: + { +#if ENABLE_XBOX +#else +#endif + } + case ClearOptions::Stencil: + { +#if ENABLE_XBOX +#else +#endif + } + case ClearOptions::Target: + { +#if ENABLE_XBOX +#else +#endif + } + + } + } + + void GraphicsDevice::Dispose() + { + Dispose(true); + } + + void GraphicsDevice::Dispose(bool disposing) + { + if(disposing) + { + + } + } + } +} diff --git a/src/libXFX/GraphicsDeviceCapabilities.cpp b/src/libXFX/GraphicsDeviceCapabilities.cpp new file mode 100644 index 0000000..57c1a38 --- /dev/null +++ b/src/libXFX/GraphicsDeviceCapabilities.cpp @@ -0,0 +1,96 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace XFX +{ + namespace Graphics + { + DeviceType_t GraphicsDeviceCapabilities::DeviceType_() + { +#if ENABLE_XBOX + return DeviceType::Hardware; +#else + +#endif + } + + /*** BLENDCAPS STRUCTURE DEFINITION ***/ + int SupportsBlendFactor() + { + return true; + } + + int SupportsBothInverseSourceAlpha() + { + return true; + } + + int SupportsBothSourceAlpha() + { + return true; + } + + int SupportsDestinationAlpha() + { + return true; + } + + bool GraphicsDeviceCapabilities::BlendCaps::operator!=(BlendCaps &other) + { + } + + bool GraphicsDeviceCapabilities::BlendCaps::operator==(BlendCaps &other) + { + } + + bool GraphicsDeviceCapabilities::CursorCaps::SupportsColor() + { +#if ENABLE_XBOX + return false; +#else +#endif + } + + bool GraphicsDeviceCapabilities::CursorCaps::SupportsLowResolution() + { +#if ENABLE_XBOX + return false; +#else +#endif + } + + bool GraphicsDeviceCapabilities::DeviceCaps::IsDirect3D9Driver() + { +#if ENABLE_XBOX + return false; +#else +#endif + } + } +} diff --git a/src/libXFX/GraphicsResource.cpp b/src/libXFX/GraphicsResource.cpp new file mode 100644 index 0000000..1d5a19f --- /dev/null +++ b/src/libXFX/GraphicsResource.cpp @@ -0,0 +1,85 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace XFX +{ + namespace Graphics + { + GraphicsDevice GraphicsResource::GraphicsDevice_() + { + return graphicsDevice; + } + + int GraphicsResource::IsDisposed() + { + return isDisposed(); + } + + char* GraphicsResource::Name() + { + return name; + } + + void GraphicsResource::Name(char* value) + { + name = value; + } + + ResourceType_t GraphicsResource::ResourceType_() + { + return resourceType; + } + + GraphicsResource::~GraphicsResource() + { + Dispose(false); + } + + GraphicsResource::GraphicsResource() + { + isDisposed = false; + } + + GraphicsResource::Dispose() + { + Dispose(true); + } + + GraphicsResource::Dispose(bool disposing) + { + if(isDisposed) + return; + + isDisposed = true; + + if (Disposing != null) + Disposing(*this, EventArgs::Empty); + } + } +} diff --git a/src/libXFX/Keyboard.cpp b/src/libXFX/Keyboard.cpp new file mode 100644 index 0000000..16c78ca --- /dev/null +++ b/src/libXFX/Keyboard.cpp @@ -0,0 +1,100 @@ +// Copyright (C) 2010-2012, Halofreak_1990 +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +extern "C" { +#ifdef ENABLE_XBOX +#include +#else +#endif +} + +#include + +namespace XFX +{ + namespace Input + { + int GetArrLength(unsigned char arr[]) + { + return sizeof(arr) / sizeof(unsigned char); + } + + XKEYBOARD_STROKE Stroke; + + //It's a waste of memory to create a new KeyboardState each time the input states are updated. + //Therefore, we create a static one and update it each time an update is requested. + static KeyboardState result; + + //Initializes the KeyboardState class + KeyboardState::KeyboardState() + { + } + + //Initializes the KeyboardState class with the specified keys pressed + KeyboardState::KeyboardState(unsigned char keys[]) + { + + } + + unsigned char *KeyboardState::GetPressedKeys() + { + + } + + //Returns whether the specified key is currently pressed + bool KeyboardState::IsKeyDown(unsigned char key) + { + if(XInputGetKeystroke(&Stroke) == 0){ + if((Stroke.ucFlags & key) == 0){ + return true; + } + return false; + } + //We should never get here unless the input system doesn't work + return -1; + } + + //Returns whether the specified key is NOT pressed + bool KeyboardState::IsKeyUp(unsigned char key) + { + if(XInputGetKeystroke(&Stroke) == 0){ + if((Stroke.ucFlags & key) != 0){ + return true; + } + return false; + } + //We should never get here unless the input system doesn't work + return -1; + } + + //Gets the state of the keyboard + KeyboardState Keyboard::GetState() + { + return result; + } + } +} diff --git a/src/libXFX/MathHelper.cpp b/src/libXFX/MathHelper.cpp new file mode 100644 index 0000000..8785290 --- /dev/null +++ b/src/libXFX/MathHelper.cpp @@ -0,0 +1,111 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include "MathHelper.h" + +namespace XFX +{ + const float MathHelper::E = 2.718282f; + const float MathHelper::Log10E = 0.4342945f; + const float MathHelper::Log2E = 1.442695f; + const float MathHelper::Pi = 3.141593f; + const float MathHelper::PiOver2 = 1.570796f; + const float MathHelper::PiOver4 = 0.7853982f; + const float MathHelper::TwoPi = 6.283185f; + + float MathHelper::Baricentric(float value1, float value2, float value3, float amount1, float amount2) + { + return (value1 + (amount1 * (value2 - value1))) + (amount2 * (value3 - value1)); + } + + float MathHelper::CatmullRom(float value1, float value2, float value3, float value4, float amount) + { + float squared = amount * amount; + float cubed = amount * squared; + + return 0.5f * ((((2.0f * value2) + ((-value1 + value3) * amount)) + + (((((2.0f * value1) - (5.0f * value2)) + (4.0f * value3)) - value4) * squared)) + + ((((-value1 + (3.0f * value2)) - (3.0f * value3)) + value4) * cubed)); + } + + float MathHelper::Clamp(float value, float min, float max) + { + float x = value; + x = (x > max) ? max : x; + x = (x < min) ? min : x; + return x; + } + + float Distance(float value1, float value2) + { + return value1 - value2; + } + + float MathHelper::Hermite(float value1, float tangent1, float value2, float tangent2, float amount) + { + float squared = amount * amount; + float cubed = amount * squared; + float part1 = ((2.0f * cubed) - (3.0f * squared)) + 1.0f; + float part2 = (-2.0f * cubed) + (3.0f * squared); + float part3 = (cubed - (2.0f * squared)) + amount; + float part4 = cubed - squared; + + return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4); + } + + float MathHelper::Lerp(float value1, float value2, float amount) + { + return value1 + ((value2 - value1) * amount); + } + + float MathHelper::Max(float value1, float value2) + { + return (value1 > value2) ? value2 : value1; + } + + float MathHelper::Min(float value1, float value2) + { + return (value1 < value2) ? value1 : value2; + } + + float MathHelper::SmoothStep(float value1, float value2, float amount) + { + amount = (amount > 1.0f) ? 1.0f : ((amount < 0.0f) ? 0.0f : amount); + amount = (amount * amount) * (3.0f - (2.0f * amount)); + return value1 + ((value2 - value1) * amount); + } + + float MathHelper::ToDegrees(float radians) + { + return radians * 180 / Pi; + } + + float MathHelper::ToRadians(float degrees) + { + return degrees * Pi / 180; + } +} diff --git a/src/libXFX/Matrix.cpp b/src/libXFX/Matrix.cpp new file mode 100644 index 0000000..40924d0 --- /dev/null +++ b/src/libXFX/Matrix.cpp @@ -0,0 +1,1315 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include +#include +#include + +using namespace System; + +namespace XFX +{ + const Matrix Matrix::Identity = Matrix(1.0f, 0, 0, 0, 0, 1.0f, 0, 0, 0, 0, 1.0f, 0, 0, 0, 0, 1.0f); + + Matrix::Matrix(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44) + { + M11 = m11; + M12 = m12; + M13 = m13; + M14 = m14; + M21 = m21; + M22 = m22; + M23 = m23; + M24 = m24; + M31 = m31; + M32 = m32; + M33 = m33; + M34 = m34; + M41 = m41; + M42 = m42; + M43 = m43; + M44 = m44; + } + + Matrix::Matrix(const Matrix &obj) + { + M11 = obj.M11; + M12 = obj.M12; + M13 = obj.M13; + M14 = obj.M14; + M21 = obj.M21; + M22 = obj.M22; + M23 = obj.M23; + M24 = obj.M24; + M31 = obj.M31; + M32 = obj.M32; + M33 = obj.M33; + M34 = obj.M34; + M41 = obj.M41; + M42 = obj.M42; + M43 = obj.M43; + M44 = obj.M44; + } + + Matrix::Matrix() + { + M11 = 0; + M12 = 0; + M13 = 0; + M14 = 0; + M21 = 0; + M22 = 0; + M23 = 0; + M24 = 0; + M31 = 0; + M32 = 0; + M33 = 0; + M34 = 0; + M41 = 0; + M42 = 0; + M43 = 0; + M44 = 0; + } + + Vector3 Matrix::Backward() + { + return Vector3(M31, M32, M33); + } + + void Matrix::Backward(Vector3 vector) + { + M31 = vector.X; + M32 = vector.Y; + M33 = vector.Z; + } + + Vector3 Matrix::Down() + { + return Vector3(-M21, -M22, -M23); + } + + void Matrix::Down(Vector3 vector) + { + M21 = -vector.X; + M22 = -vector.Y; + M23 = -vector.Z; + } + + Vector3 Matrix::Forward() + { + return Vector3(-M31, -M32, -M33); + } + + void Matrix::Forward(Vector3 vector) + { + M31 = -vector.X; + M32 = -vector.Y; + M33 = -vector.Z; + } + + Vector3 Matrix::Left() + { + return Vector3(-M11, -M12, -M13); + } + + void Matrix::Left(Vector3 vector) + { + M11 = -vector.X; + M12 = -vector.Y; + M13 = -vector.Z; + } + + Vector3 Matrix::Right() + { + return Vector3(M11, M12, M13); + } + + void Matrix::Right(Vector3 vector) + { + M11 = vector.X; + M12 = vector.Y; + M13 = vector.Z; + } + + Vector3 Matrix::Translation() + { + return Vector3(M41, M42, M43); + } + + void Matrix::Translation(Vector3 vector) + { + M41 = vector.X; + M42 = vector.Y; + M43 = vector.Z; + } + + Vector3 Matrix::Up() + { + return Vector3(M21, M22, M23); + } + + void Matrix::Up(Vector3 vector) + { + M21 = vector.X; + M22 = vector.Y; + M23 = vector.Z; + } + + Matrix Matrix::Add(Matrix matrix1, Matrix matrix2) + { + Matrix result; + Add(matrix1, matrix2, result); + return result; + } + + void Matrix::Add(Matrix matrix1, Matrix matrix2, out Matrix result) + { + result.M11 = matrix1.M11 + matrix2.M11; + result.M12 = matrix1.M12 + matrix2.M12; + result.M13 = matrix1.M13 + matrix2.M13; + result.M14 = matrix1.M14 + matrix2.M14; + result.M21 = matrix1.M21 + matrix2.M21; + result.M22 = matrix1.M22 + matrix2.M22; + result.M23 = matrix1.M23 + matrix2.M23; + result.M24 = matrix1.M24 + matrix2.M24; + result.M31 = matrix1.M31 + matrix2.M31; + result.M32 = matrix1.M32 + matrix2.M32; + result.M33 = matrix1.M33 + matrix2.M33; + result.M34 = matrix1.M34 + matrix2.M34; + result.M41 = matrix1.M41 + matrix2.M41; + result.M42 = matrix1.M42 + matrix2.M42; + result.M43 = matrix1.M43 + matrix2.M43; + result.M44 = matrix1.M44 + matrix2.M44; + } + + Matrix Matrix::CreateBillboard(Vector3 objectPosition, Vector3 cameraPosition, Vector3 cameraUpVector, Vector3* cameraForwardVector) + { + Matrix result; + CreateBillboard(objectPosition, cameraPosition, cameraUpVector, cameraForwardVector, result); + return result; + } + + void Matrix::CreateBillboard(Vector3 objectPosition, Vector3 cameraPosition, Vector3 cameraUpVector, Vector3* cameraForwardVector, out Matrix result) + { + Vector3 vector; + Vector3 vector2; + Vector3 vector3; + vector.X = objectPosition.X - cameraPosition.X; + vector.Y = objectPosition.Y - cameraPosition.Y; + vector.Z = objectPosition.Z - cameraPosition.Z; + float num = vector.LengthSquared(); + if (num < 0.0001f) + { + vector = (cameraForwardVector != null) ? -Vector3(cameraForwardVector->X, cameraForwardVector->Y, cameraForwardVector->Z) : Vector3::Forward; + } + else + { + Vector3::Multiply(vector, (float) (1.0f / ((float) Math::Sqrt((double) num))), vector); + } + Vector3::Cross(cameraUpVector, vector, vector3); + vector3.Normalize(); + Vector3::Cross(vector, vector3, vector2); + result.M11 = vector3.X; + result.M12 = vector3.Y; + result.M13 = vector3.Z; + result.M14 = 0.0f; + result.M21 = vector2.X; + result.M22 = vector2.Y; + result.M23 = vector2.Z; + result.M24 = 0.0f; + result.M31 = vector.X; + result.M32 = vector.Y; + result.M33 = vector.Z; + result.M34 = 0.0f; + result.M41 = objectPosition.X; + result.M42 = objectPosition.Y; + result.M43 = objectPosition.Z; + result.M44 = 1.0f; + } + + Matrix Matrix::CreateConstrainedBillboard(Vector3 objectPosition, Vector3 cameraPosition, Vector3 rotateAxis, Vector3* cameraForwardVector, Vector3* objectForwardVector) + { + Matrix result; + CreateConstrainedBillboard(objectPosition, cameraPosition, rotateAxis, cameraForwardVector, objectForwardVector, result); + return result; + } + + void Matrix::CreateConstrainedBillboard(Vector3 objectPosition, Vector3 cameraPosition, Vector3 rotateAxis, Vector3* cameraForwardVector, Vector3* objectForwardVector, out Matrix result) + { + float num 0.0f; + Vector3 vector; + Vector3 vector2; + Vector3 vector3; + vector2.X = objectPosition.X - cameraPosition.X; + vector2.Y = objectPosition.Y - cameraPosition.Y; + vector2.Z = objectPosition.Z - cameraPosition.Z; + float num2 = vector2.LengthSquared(); + if (num2 < 0.0001f) + { + vector2 = (cameraForwardVector != null) ? -Vector3(cameraForwardVector->X, cameraForwardVector->Y, cameraForwardVector->Z) : Vector3::Forward; + } + else + { + Vector3::Multiply(vector2, (float) (1.0f / ((float) Math::Sqrt((double) num2))), vector2); + } + Vector3 vector4 = rotateAxis; + Vector3::Dot(rotateAxis, vector2, num); + if (Math::Abs(num) > 0.9982547f) + { + if (objectForwardVector != null) + { + vector = Vector3(objectForwardVector->X, objectForwardVector->Y, objectForwardVector->Z); + Vector3::Dot(rotateAxis, vector, num); + if (Math::Abs(num) > 0.9982547f) + { + num = ((rotateAxis.X * Vector3::Forward.X) + (rotateAxis.Y * Vector3::Forward.Y)) + (rotateAxis.Z * Vector3::Forward.Z); + vector = (Math::Abs(num) > 0.9982547f) ? Vector3::Right : Vector3::Forward; + } + } + else + { + num = ((rotateAxis.X * Vector3::Forward.X) + (rotateAxis.Y * Vector3::Forward.Y)) + (rotateAxis.Z * Vector3::Forward.Z); + vector = (Math::Abs(num) > 0.9982547f) ? Vector3::Right : Vector3::Forward; + } + Vector3::Cross(rotateAxis, vector, vector3); + vector3.Normalize(); + Vector3::Cross(vector3, rotateAxis, vector); + vector.Normalize(); + } + else + { + Vector3::Cross(rotateAxis, vector2, vector3); + vector3.Normalize(); + Vector3::Cross(vector3, vector4, vector); + vector.Normalize(); + } + result.M11 = vector3.X; + result.M12 = vector3.Y; + result.M13 = vector3.Z; + result.M14 = 0.0f; + result.M21 = vector4.X; + result.M22 = vector4.Y; + result.M23 = vector4.Z; + result.M24 = 0.0f; + result.M31 = vector.X; + result.M32 = vector.Y; + result.M33 = vector.Z; + result.M34 = 0.0f; + result.M41 = objectPosition.X; + result.M42 = objectPosition.Y; + result.M43 = objectPosition.Z; + result.M44 = 1.0f; + } + + Matrix Matrix::CreateFromAxisAngle(Vector3 axis,float angle) + { + Matrix result; + CreateFromAxisAngle(axis, angle, result); + return result; + } + + void Matrix::CreateFromAxisAngle(Vector3 axis, float angle, out Matrix result) + { + if(axis.LengthSquared() != 1.0f) + axis.Normalize(); + + float x = axis.X; + float y = axis.Y; + float z = axis.Z; + float cos = Math::Cos(angle); + float sin = Math::Sin(angle); + float xx = x * x; + float yy = y * y; + float zz = z * z; + float xy = x * y; + float xz = x * z; + float yz = y * z; + + result.M11 = xx + (cos * (1.0f - xx)); + result.M12 = (xy - (cos * xy)) + (sin * z); + result.M13 = (xz - (cos * xz)) - (sin * y); + result.M14 = 0.0f; + result.M21 = (xy - (cos * xy)) - (sin * z); + result.M22 = yy + (cos * (1.0f - yy)); + result.M23 = (yz - (cos * yz)) + (sin * x); + result.M24 = 0.0f; + result.M31 = (xz - (cos * xz)) + (sin * y); + result.M32 = (yz - (cos * yz)) - (sin * x); + result.M33 = zz + (cos * (1.0f - zz)); + result.M34 = 0.0f; + result.M41 = 0.0f; + result.M42 = 0.0f; + result.M43 = 0.0f; + result.M44 = 1.0f; + } + + Matrix Matrix::CreateFromQuaternion(Quaternion rotation) + { + Matrix result; + CreateFromQuaternion(rotation, result); + return result; + } + + void Matrix::CreateFromQuaternion(Quaternion rotation, out Matrix result) + { + float xx = rotation.X * rotation.X; + float yy = rotation.Y * rotation.Y; + float zz = rotation.Z * rotation.Z; + float xy = rotation.X * rotation.Y; + float zw = rotation.Z * rotation.W; + float zx = rotation.Z * rotation.X; + float yw = rotation.Y * rotation.W; + float yz = rotation.Y * rotation.Z; + float xw = rotation.X * rotation.W; + + result.M11 = 1.0f - (2.0f * (yy + zz)); + result.M12 = 2.0f * (xy + zw); + result.M13 = 2.0f * (zx - yw); + result.M14 = 0.0f; + result.M21 = 2.0f * (xy - zw); + result.M22 = 1.0f - (2.0f * (zz + xx)); + result.M23 = 2.0f * (yz + xw); + result.M24 = 0.0f; + result.M31 = 2.0f * (zx + yw); + result.M32 = 2.0f * (yz - xw); + result.M33 = 1.0f - (2.0f * (yy + xx)); + result.M34 = 0.0f; + result.M41 = 0.0f; + result.M42 = 0.0f; + result.M43 = 0.0f; + result.M44 = 1.0f; + } + + Matrix Matrix::CreateFromYawPitchRoll(float yaw, float pitch, float roll) + { + Matrix result; + CreateFromYawPitchRoll(yaw, pitch, roll, result); + return result; + } + + void Matrix::CreateFromYawPitchRoll(float yaw, float pitch, float roll, out Matrix result) + { + Quaternion quaternion; + Quaternion::CreateFromYawPitchRoll(yaw, pitch, roll, quaternion); + CreateFromQuaternion(quaternion, result); + } + + Matrix Matrix::CreateLookAt(Vector3 cameraPosition, Vector3 cameraTarget, Vector3 cameraUpVector) + { + Matrix result; + CreateLookAt(cameraPosition, cameraTarget, cameraUpVector, result); + return result; + } + + void Matrix::CreateLookAt(Vector3 cameraPosition, Vector3 cameraTarget, Vector3 cameraUpVector, out Matrix result) + { + Vector3 xaxis, yaxis, zaxis; + Vector3::Subtract(cameraPosition, cameraTarget, zaxis); + zaxis.Normalize(); + Vector3::Cross(cameraUpVector, zaxis, xaxis); + xaxis.Normalize(); + Vector3::Cross(zaxis, xaxis, yaxis); + result = Matrix::Identity; + result.M11 = xaxis.X; + result.M21 = xaxis.Y; + result.M31 = xaxis.Z; + result.M12 = yaxis.X; + result.M22 = yaxis.Y; + result.M32 = yaxis.Z; + result.M13 = zaxis.X; + result.M23 = zaxis.Y; + result.M33 = zaxis.Z; + Vector3::Dot(xaxis, cameraPosition, result.M41); + Vector3::Dot(yaxis, cameraPosition, result.M42); + Vector3::Dot(zaxis, cameraPosition, result.M43); + result.M41 = -result.M41; + result.M42 = -result.M42; + result.M43 = -result.M43; + } + + Matrix Matrix::CreateOrthographic(float width, float height, float zNearPlane, float zFarPlane) + { + Matrix result; + CreateOrthographic(width, height, zNearPlane, zFarPlane, result); + return result; + } + + void Matrix::CreateOrthographic(float width, float height, float zNearPlane, float zFarPlane, out Matrix result) + { + float halfWidth = width * 0.5f; + float halfHeight = height * 0.5f; + CreateOrthographicOffCenter(-halfWidth, halfWidth, -halfHeight, halfHeight, zNearPlane, zFarPlane, result); + } + + Matrix Matrix::CreateOrthographicOffCenter(float left, float right, float bottom, float top, float zNearPlane, float zFarPlane) + { + Matrix result; + CreateOrthographicOffCenter(left, right, bottom, top, zNearPlane, zFarPlane, result); + return result; + } + + void Matrix::CreateOrthographicOffCenter(float left, float right, float bottom, float top, float zNearPlane, float zFarPlane, out Matrix result) + { + float zRange = 1.0f / (zFarPlane - zNearPlane); + result = Matrix::Identity; + result.M11 = 2.0f / (right - left); + result.M22 = 2.0f / (top - bottom); + result.M33 = zRange; + result.M41 = (left + right) / (left - right); + result.M42 = (top + bottom) / (bottom - top); + result.M43 = -zNearPlane * zRange; + + result.M33 *= -1.0f; + } + + Matrix Matrix::CreatePerspective(float width, float height, float zNearPlane, float zFarPlane) + { + Matrix result; + CreatePerspective(width, height, zNearPlane, zFarPlane); + return result; + } + + void Matrix::CreatePerspective(float width, float height, float zNearPlane, float zFarPlane, out Matrix result) + { + float halfWidth = width * 0.5f; + float halfHeight = height * 0.5f; + CreatePerspectiveOffCenter(-halfWidth, halfWidth, -halfHeight, halfHeight, zNearPlane, zFarPlane, result); + } + + Matrix Matrix::CreatePerspectiveFieldOfView(float fieldOfView, float aspectRatio, float nearPlaneDistance, float farPlaneDistance) + { + Matrix result; + CreatePerspectiveFieldOfView(fieldOfView, aspectRatio, nearPlaneDistance, farPlaneDistance); + return result; + } + + void Matrix::CreatePerspectiveFieldOfView(float fieldOfView, float aspectRatio, float nearPlaneDistance, float farPlaneDistance, out Matrix result) + { + float yScale = (float)(1.0 / Math::Tan(fieldOfView * 0.5f)); + float xScale = yScale / aspectRatio; + float halfWidth = nearPlaneDistance / xScale; + float halfHeight = nearPlaneDistance / yScale; + CreatePerspectiveOffCenter(-halfWidth, halfWidth, -halfHeight, halfHeight, nearPlaneDistance, farPlaneDistance, result); + } + + Matrix Matrix::CreatePerspectiveOffCenter(float left, float right, float bottom, float top, float nearPlaneDistance, float farPlaneDistance) + { + Matrix result; + CreatePerspectiveOffCenter(left, right, bottom, top, nearPlaneDistance, farPlaneDistance, result); + return result; + } + + void Matrix::CreatePerspectiveOffCenter(float left, float right, float bottom, float top, float nearPlaneDistance, float farPlaneDistance, out Matrix result) + { + if (nearPlaneDistance <= 0.0f) + { + throw ArgumentOutOfRangeException("nearPlaneDistance", "You should specify a positive value for nearPlaneDistance."); + } + if (farPlaneDistance <= 0.0f) + { + throw ArgumentOutOfRangeException("farPlaneDistance", "You should specify a positive value for farPlaneDistance."); + } + if (nearPlaneDistance >= farPlaneDistance) + { + throw ArgumentOutOfRangeException("Near plane distance is larger than Far plane distance. Near plane distance must be smaller than Far plane distance."); + } + result.M11 = (2f * nearPlaneDistance) / (right - left); + result.M12 = result.M13 = result.M14 = 0f; + result.M22 = (2f * nearPlaneDistance) / (top - bottom); + result.M21 = result.M23 = result.M24 = 0f; + result.M31 = (left + right) / (right - left); + result.M32 = (top + bottom) / (top - bottom); + result.M33 = farPlaneDistance / (nearPlaneDistance - farPlaneDistance); + result.M34 = -1f; + result.M43 = (nearPlaneDistance * farPlaneDistance) / (nearPlaneDistance - farPlaneDistance); + result.M41 = result.M42 = result.M44 = 0f; + } + + void Matrix::CreateReflection(Plane value, out Matrix result) + { + value.Normalize(); + float x = value.Normal.X; + float y = value.Normal.Y; + float z = value.Normal.Z; + float x2 = -2.0f * x; + float y2 = -2.0f * y; + float z2 = -2.0f * z; + result.M11 = (x2 * x) + 1.0f; + result.M12 = y2 * x; + result.M13 = z2 * x; + result.M14 = 0.0f; + result.M21 = x2 * y; + result.M22 = (y2 * y) + 1.0f; + result.M23 = z2 * y; + result.M24 = 0.0f; + result.M31 = x2 * z; + result.M32 = y2 * z; + result.M33 = (z2 * z) + 1.0f; + result.M34 = 0.0f; + result.M41 = x2 * value.D; + result.M42 = y2 * value.D; + result.M43 = z2 * value.D; + result.M44 = 1.0f; + } + + Matrix Matrix::CreateReflection(Plane value) + { + Matrix result; + value.Normalize(); + float x = value.Normal.X; + float y = value.Normal.Y; + float z = value.Normal.Z; + float x2 = -2.0f * x; + float y2 = -2.0f * y; + float z2 = -2.0f * z; + result.M11 = (x2 * x) + 1.0f; + result.M12 = y2 * x; + result.M13 = z2 * x; + result.M14 = 0.0f; + result.M21 = x2 * y; + result.M22 = (y2 * y) + 1.0f; + result.M23 = z2 * y; + result.M24 = 0.0f; + result.M31 = x2 * z; + result.M32 = y2 * z; + result.M33 = (z2 * z) + 1.0f; + result.M34 = 0.0f; + result.M41 = x2 * value.D; + result.M42 = y2 * value.D; + result.M43 = z2 * value.D; + result.M44 = 1.0f; + return result; + } + + void Matrix::CreateRotationX(float radians, out Matrix result) + { + float num2 = (float) Math::Cos((double) radians); + float num = (float) Math::Sin((double) radians); + result.M11 = 1f; + result.M12 = 0f; + result.M13 = 0f; + result.M14 = 0f; + result.M21 = 0f; + result.M22 = num2; + result.M23 = num; + result.M24 = 0f; + result.M31 = 0f; + result.M32 = -num; + result.M33 = num2; + result.M34 = 0f; + result.M41 = 0f; + result.M42 = 0f; + result.M43 = 0f; + result.M44 = 1f; + } + + Matrix Matrix::CreateRotationX(float radians) + { + Matrix result; + CreateRotationX(radians, result); + return result; + } + + void Matrix::CreateRotationY(float radians, out Matrix result) + { + float num2 = (float) Math::Cos((double) radians); + float num = (float) Math::Sin((double) radians); + result.M11 = num2; + result.M12 = 0f; + result.M13 = -num; + result.M14 = 0f; + result.M21 = 0f; + result.M22 = 1f; + result.M23 = 0f; + result.M24 = 0f; + result.M31 = num; + result.M32 = 0f; + result.M33 = num2; + result.M34 = 0f; + result.M41 = 0f; + result.M42 = 0f; + result.M43 = 0f; + result.M44 = 1f; + } + + Matrix Matrix::CreateRotationY(float radians) + { + Matrix result; + CreateRotationY(radians, result); + return result; + } + + void Matrix::CreateRotationZ(float radians, out Matrix result) + { + float num2 = (float) Math::Cos((double) radians); + float num = (float) Math::Sin((double) radians); + result.M11 = num2; + result.M12 = num; + result.M13 = 0f; + result.M14 = 0f; + result.M21 = -num; + result.M22 = num2; + result.M23 = 0f; + result.M24 = 0f; + result.M31 = 0f; + result.M32 = 0f; + result.M33 = 1f; + result.M34 = 0f; + result.M41 = 0f; + result.M42 = 0f; + result.M43 = 0f; + result.M44 = 1f; + } + + Matrix CreateRotationZ(float radians) + { + Matrix result; + CreateRotationZ(radians, result); + return result; + } + + void Matrix::CreateScale(float scale, out Matrix result) + { + float num = scale; + result.M11 = num; + result.M12 = 0.0f; + result.M13 = 0.0f; + result.M14 = 0.0f; + result.M21 = 0.0f; + result.M22 = num; + result.M23 = 0.0f; + result.M24 = 0.0f; + result.M31 = 0.0f; + result.M32 = 0.0f; + result.M33 = num; + result.M34 = 0.0f; + result.M41 = 0.0f; + result.M42 = 0.0f; + result.M43 = 0.0f; + result.M44 = 1.0f; + } + + Matrix Matrix::CreateScale(float scale) + { + Matrix result; + CreateScale(scale, result); + return result; + } + + void Matrix::CreateScale(float xScale, float yScale, float zScale, out Matrix result) + { + float num3 = xScale; + float num2 = yScale; + float num = zScale; + result.M11 = num3; + result.M12 = 0.0f; + result.M13 = 0.0f; + result.M14 = 0.0f; + result.M21 = 0.0f; + result.M22 = num2; + result.M23 = 0.0f; + result.M24 = 0.0f; + result.M31 = 0.0f; + result.M32 = 0.0f; + result.M33 = num; + result.M34 = 0.0f; + result.M41 = 0.0f; + result.M42 = 0.0f; + result.M43 = 0.0f; + result.M44 = 1.0f; + } + + Matrix Matrix::CreateScale(float xScale, float yScale, float zScale) + { + Matrix result; + CreateScale(xScale, yScale, zScale, result); + return result; + } + + void Matrix::CreateScale(Vector3 scales, out Matrix result) + { + float x = scales.X; + float y = scales.Y; + float z = scales.Z; + result.M11 = x; + result.M12 = 0.0f; + result.M13 = 0.0f; + result.M14 = 0.0f; + result.M21 = 0.0f; + result.M22 = y; + result.M23 = 0.0f; + result.M24 = 0.0f; + result.M31 = 0.0f; + result.M32 = 0.0f; + result.M33 = z; + result.M34 = 0.0f; + result.M41 = 0.0f; + result.M42 = 0.0f; + result.M43 = 0.0f; + result.M44 = 1.0f; + } + + Matrix Matrix::CreateScale(Vector3 scales) + { + Matrix result; + CreateScale(scales, result); + return result; + } + + void Matrix::CreateShadow(Vector3 lightDirection, Plane plane, out Matrix result) + { + plane.Normalize(); + float dot = ((plane.Normal.X * lightDirection.X) + (plane.Normal.Y * lightDirection.Y)) + (plane.Normal.Z * lightDirection.Z); + float x = -plane.Normal.X; + float y = -plane.Normal.Y; + float z = -plane.Normal.Z; + float d = -plane.D; + result.M11 = (x * lightDirection.X) + dot; + result.M21 = y * lightDirection.X; + result.M31 = z * lightDirection.X; + result.M41 = d * lightDirection.X; + result.M12 = x * lightDirection.Y; + result.M22 = (y * lightDirection.Y) + dot; + result.M32 = z * lightDirection.Y; + result.M42 = d * lightDirection.Y; + result.M13 = x * lightDirection.Z; + result.M23 = y * lightDirection.Z; + result.M33 = (z * lightDirection.Z) + dot; + result.M43 = d * lightDirection.Z; + result.M14 = 0.0f; + result.M24 = 0.0f; + result.M34 = 0.0f; + result.M44 = dot; + } + + Matrix Matrix::CreateShadow(Vector3 lightDirection, Plane plane) + { + Matrix result; + CreateShadow(lightDirection, plane, result); + return result; + } + + void Matrix::CreateTranslation(float xPosition, float yPosition, float zPosition, out Matrix result) + { + result.M11 = 1.0f; + result.M12 = 0.0f; + result.M13 = 0.0f; + result.M14 = 0.0f; + result.M21 = 0.0f; + result.M22 = 1.0f; + result.M23 = 0.0f; + result.M24 = 0.0f; + result.M31 = 0.0f; + result.M32 = 0.0f; + result.M33 = 1.0f; + result.M34 = 0.0f; + result.M41 = xPosition; + result.M42 = yPosition; + result.M43 = zPosition; + result.M44 = 1.0f; + } + + Matrix Matrix::CreateTranslation(float xPosition, float yPosition, float zPosition) + { + Matrix result; + CreateTranslation(xPosition, yPosition, zPosition, result); + return result; + } + + void Matrix::CreateTranslation(Vector3 position, out Matrix result) + { + result.M11 = 1.0f; + result.M12 = 0.0f; + result.M13 = 0.0f; + result.M14 = 0.0f; + result.M21 = 0.0f; + result.M22 = 1.0f; + result.M23 = 0.0f; + result.M24 = 0.0f; + result.M31 = 0.0f; + result.M32 = 0.0f; + result.M33 = 1.0f; + result.M34 = 0.0f; + result.M41 = position.X; + result.M42 = position.Y; + result.M43 = position.Z; + result.M44 = 1.0f; + } + + Matrix Matrix::CreateTranslation(Vector3 position) + { + Matrix result; + CreateTranslation(position, result); + return result; + } + + Matrix Matrix::CreateWorld(Vector3 position, Vector3 forward, Vector3 up) + { + Matrix ret; + CreateWorld(position, forward, up, out ret); + return ret; + } + + void Matrix::CreateWorld(Vector3 position, Vector3 forward, Vector3 up, out Matrix result) + { + Vector3 vector = Vector3::Normalize(position - forward); + Vector3 vector2 = Vector3::Normalize(Vector3.Cross(up, vector)); + Vector3 vector3 = Vector3::Cross(vector, vector2); + result.M11 = vector2.X; + result.M12 = vector2.Y; + result.M13 = vector2.Z; + result.M21 = vector3.X; + result.M22 = vector3.Y; + result.M23 = vector3.Z; + result.M31 = vector.X; + result.M32 = vector.Y; + result.M33 = vector.Z; + result.M41 = 0f; + result.M42 = 0f; + result.M43 = 0f; + result.M44 = 1f; + result.M14 = -Vector3::Dot(vector2, position); + result.M24 = -Vector3::Dot(vector3, position); + result.M34 = -Vector3::Dot(vector, position); + } + + int Matrix::Decompose(Vector3 scale, Quaternion rotation, Vector3 translation) + { + //Get the translation. + translation.X = M41; + translation.Y = M42; + translation.Z = M43; + //Scaling is the length of the rows. + scale.X = (float)Math::Sqrt((M11 * M11) + (M12 * M12) + (M13 * M13)); + scale.Y = (float)Math::Sqrt((M21 * M21) + (M22 * M22) + (M23 * M23)); + scale.Z = (float)Math::Sqrt((M31 * M31) + (M32 * M32) + (M33 * M33)); + //If any of the scaling factors are zero, than the rotation matrix can not exist. + if (Math::Abs(scale.X) < 1e-6f || + Math::Abs(scale.Y) < 1e-6f || + Math::Abs(scale.Z) < 1e-6f) + { + rotation = Quaternion::Identity; + return false; + } //The rotation is the left over matrix after dividing out the scaling. + Matrix rotationmatrix = Matrix(); + rotationmatrix.M11 = M11 / scale.X; + rotationmatrix.M12 = M12 / scale.X; + rotationmatrix.M13 = M13 / scale.X; + rotationmatrix.M21 = M21 / scale.Y; + rotationmatrix.M22 = M22 / scale.Y; + rotationmatrix.M23 = M23 / scale.Y; + rotationmatrix.M31 = M31 / scale.Z; + rotationmatrix.M32 = M32 / scale.Z; + rotationmatrix.M33 = M33 / scale.Z; + rotationmatrix.M44 = 1.0f; + Quaternion::CreateFromRotationMatrix(rotationmatrix, rotation); + return true; + } + + float Matrix::Determinant() + { + float temp1 = (M33 * M44) - (M34 * M43); + float temp2 = (M32 * M44) - (M34 * M42); + float temp3 = (M32 * M43) - (M33 * M42); + float temp4 = (M31 * M44) - (M34 * M41); + float temp5 = (M31 * M43) - (M33 * M41); + float temp6 = (M31 * M42) - (M32 * M41); + + return ((((M11 * (((M22 * temp1) - (M23 * temp2)) + (M24 * temp3))) - (M12 * (((M21 * temp1) - + (M23 * temp4)) + (M24 * temp5)))) + (M13 * (((M21 * temp2) - (M22 * temp4)) + (M24 * temp6)))) - + (M14 * (((M21 * temp3) - (M22 * temp5)) + (M23 * temp6)))); + } + + Matrix Matrix::Divide(Matrix matrix1, Matrix matrix2) + { + Matrix result; + Divide(matrix1, matrix2, result); + return result; + } + + void Matrix::Divide(Matrix matrix1, Matrix matrix2, out Matrix result) + { + Matrix inverse = Matrix::Invert(matrix2); + Matrix::Multiply(matrix1, inverse, result); + } + + void Matrix::Divide(Matrix matrix1, float divider, out Matrix result) + { + float num = 1f / divider; + result.M11 = matrix1.M11 * num; + result.M12 = matrix1.M12 * num; + result.M13 = matrix1.M13 * num; + result.M14 = matrix1.M14 * num; + result.M21 = matrix1.M21 * num; + result.M22 = matrix1.M22 * num; + result.M23 = matrix1.M23 * num; + result.M24 = matrix1.M24 * num; + result.M31 = matrix1.M31 * num; + result.M32 = matrix1.M32 * num; + result.M33 = matrix1.M33 * num; + result.M34 = matrix1.M34 * num; + result.M41 = matrix1.M41 * num; + result.M42 = matrix1.M42 * num; + result.M43 = matrix1.M43 * num; + result.M44 = matrix1.M44 * num; + } + + Matrix Matrix::Divide(Matrix matrix1, float divider) + { + Matrix result; + Divide(matrix1, divider, result); + return result; + } + + bool Matrix::Equals(Matrix other) + { + return ((M11 == other.M11) & (M12 == other.M12) & (M13 == other.M13) & (M14 == other.M14) & + (M21 == other.M21) & (M22 == other.M22) & (M23 == other.M23) & (M24 == other.M24) & + (M31 == other.M31) & (M32 == other.M32) & (M33 == other.M33) & (M34 == other.M34) & + (M41 == other.M41) & (M42 == other.M42) & (M43 == other.M43) & (M44 == other.M44)); + } + + int Matrix::GetHashCode() + { + return ((int)M11 ^ (int)M12 ^ (int)M13 ^ (int)M14 ^ (int)M21 ^ (int)M22 ^ (int)M23 ^ (int)M24 ^ + (int)M31 ^ (int)M32 ^ (int)M33 ^ (int)M34 ^ (int)M41 ^ (int)M42 ^ (int)M43 ^ (int)M44); + } + + void Matrix::Invert(Matrix matrix, out Matrix result) + { + float num5 = matrix.M11; + float num4 = matrix.M12; + float num3 = matrix.M13; + float num2 = matrix.M14; + float num9 = matrix.M21; + float num8 = matrix.M22; + float num7 = matrix.M23; + float num6 = matrix.M24; + float num17 = matrix.M31; + float num16 = matrix.M32; + float num15 = matrix.M33; + float num14 = matrix.M34; + float num13 = matrix.M41; + float num12 = matrix.M42; + float num11 = matrix.M43; + float num10 = matrix.M44; + float num23 = (num15 * num10) - (num14 * num11); + float num22 = (num16 * num10) - (num14 * num12); + float num21 = (num16 * num11) - (num15 * num12); + float num20 = (num17 * num10) - (num14 * num13); + float num19 = (num17 * num11) - (num15 * num13); + float num18 = (num17 * num12) - (num16 * num13); + float num39 = ((num8 * num23) - (num7 * num22)) + (num6 * num21); + float num38 = -(((num9 * num23) - (num7 * num20)) + (num6 * num19)); + float num37 = ((num9 * num22) - (num8 * num20)) + (num6 * num18); + float num36 = -(((num9 * num21) - (num8 * num19)) + (num7 * num18)); + float num = 1f / ((((num5 * num39) + (num4 * num38)) + (num3 * num37)) + (num2 * num36)); + result.M11 = num39 * num; + result.M21 = num38 * num; + result.M31 = num37 * num; + result.M41 = num36 * num; + result.M12 = -(((num4 * num23) - (num3 * num22)) + (num2 * num21)) * num; + result.M22 = (((num5 * num23) - (num3 * num20)) + (num2 * num19)) * num; + result.M32 = -(((num5 * num22) - (num4 * num20)) + (num2 * num18)) * num; + result.M42 = (((num5 * num21) - (num4 * num19)) + (num3 * num18)) * num; + float num35 = (num7 * num10) - (num6 * num11); + float num34 = (num8 * num10) - (num6 * num12); + float num33 = (num8 * num11) - (num7 * num12); + float num32 = (num9 * num10) - (num6 * num13); + float num31 = (num9 * num11) - (num7 * num13); + float num30 = (num9 * num12) - (num8 * num13); + result.M13 = (((num4 * num35) - (num3 * num34)) + (num2 * num33)) * num; + result.M23 = -(((num5 * num35) - (num3 * num32)) + (num2 * num31)) * num; + result.M33 = (((num5 * num34) - (num4 * num32)) + (num2 * num30)) * num; + result.M43 = -(((num5 * num33) - (num4 * num31)) + (num3 * num30)) * num; + float num29 = (num7 * num14) - (num6 * num15); + float num28 = (num8 * num14) - (num6 * num16); + float num27 = (num8 * num15) - (num7 * num16); + float num26 = (num9 * num14) - (num6 * num17); + float num25 = (num9 * num15) - (num7 * num17); + float num24 = (num9 * num16) - (num8 * num17); + result.M14 = -(((num4 * num29) - (num3 * num28)) + (num2 * num27)) * num; + result.M24 = (((num5 * num29) - (num3 * num26)) + (num2 * num25)) * num; + result.M34 = -(((num5 * num28) - (num4 * num26)) + (num2 * num24)) * num; + result.M44 = (((num5 * num27) - (num4 * num25)) + (num3 * num24)) * num; + } + + Matrix Matrix::Invert(Matrix matrix) + { + Invert(matrix, matrix); + return matrix; + } + + void Matrix::Lerp(Matrix value1, Matrix value2, float amount, out Matrix result) + { + result.M11 = matrix1.M11 + ((matrix2.M11 - matrix1.M11) * amount); + result.M12 = matrix1.M12 + ((matrix2.M12 - matrix1.M12) * amount); + result.M13 = matrix1.M13 + ((matrix2.M13 - matrix1.M13) * amount); + result.M14 = matrix1.M14 + ((matrix2.M14 - matrix1.M14) * amount); + result.M21 = matrix1.M21 + ((matrix2.M21 - matrix1.M21) * amount); + result.M22 = matrix1.M22 + ((matrix2.M22 - matrix1.M22) * amount); + result.M23 = matrix1.M23 + ((matrix2.M23 - matrix1.M23) * amount); + result.M24 = matrix1.M24 + ((matrix2.M24 - matrix1.M24) * amount); + result.M31 = matrix1.M31 + ((matrix2.M31 - matrix1.M31) * amount); + result.M32 = matrix1.M32 + ((matrix2.M32 - matrix1.M32) * amount); + result.M33 = matrix1.M33 + ((matrix2.M33 - matrix1.M33) * amount); + result.M34 = matrix1.M34 + ((matrix2.M34 - matrix1.M34) * amount); + result.M41 = matrix1.M41 + ((matrix2.M41 - matrix1.M41) * amount); + result.M42 = matrix1.M42 + ((matrix2.M42 - matrix1.M42) * amount); + result.M43 = matrix1.M43 + ((matrix2.M43 - matrix1.M43) * amount); + result.M44 = matrix1.M44 + ((matrix2.M44 - matrix1.M44) * amount); + } + + Matrix Matrix::Lerp(Matrix value1, Matrix value2, float amount) + { + Matrix result; + Lerp(value1, value2, amount, result); + return result; + } + + Matrix Matrix::Multiply(Matrix matrix1, Matrix matrix2) + { + Matrix result; + Multiply(matrix1, matrix2, result); + return result; + } + + void Matrix::Multiply(Matrix matrix1, Matrix matrix2, out Matrix result) + { + float num16 = (((matrix1.M11 * matrix2.M11) + (matrix1.M12 * matrix2.M21)) + (matrix1.M13 * matrix2.M31)) + (matrix1.M14 * matrix2.M41); + float num15 = (((matrix1.M11 * matrix2.M12) + (matrix1.M12 * matrix2.M22)) + (matrix1.M13 * matrix2.M32)) + (matrix1.M14 * matrix2.M42); + float num14 = (((matrix1.M11 * matrix2.M13) + (matrix1.M12 * matrix2.M23)) + (matrix1.M13 * matrix2.M33)) + (matrix1.M14 * matrix2.M43); + float num13 = (((matrix1.M11 * matrix2.M14) + (matrix1.M12 * matrix2.M24)) + (matrix1.M13 * matrix2.M34)) + (matrix1.M14 * matrix2.M44); + float num12 = (((matrix1.M21 * matrix2.M11) + (matrix1.M22 * matrix2.M21)) + (matrix1.M23 * matrix2.M31)) + (matrix1.M24 * matrix2.M41); + float num11 = (((matrix1.M21 * matrix2.M12) + (matrix1.M22 * matrix2.M22)) + (matrix1.M23 * matrix2.M32)) + (matrix1.M24 * matrix2.M42); + float num10 = (((matrix1.M21 * matrix2.M13) + (matrix1.M22 * matrix2.M23)) + (matrix1.M23 * matrix2.M33)) + (matrix1.M24 * matrix2.M43); + float num9 = (((matrix1.M21 * matrix2.M14) + (matrix1.M22 * matrix2.M24)) + (matrix1.M23 * matrix2.M34)) + (matrix1.M24 * matrix2.M44); + float num8 = (((matrix1.M31 * matrix2.M11) + (matrix1.M32 * matrix2.M21)) + (matrix1.M33 * matrix2.M31)) + (matrix1.M34 * matrix2.M41); + float num7 = (((matrix1.M31 * matrix2.M12) + (matrix1.M32 * matrix2.M22)) + (matrix1.M33 * matrix2.M32)) + (matrix1.M34 * matrix2.M42); + float num6 = (((matrix1.M31 * matrix2.M13) + (matrix1.M32 * matrix2.M23)) + (matrix1.M33 * matrix2.M33)) + (matrix1.M34 * matrix2.M43); + float num5 = (((matrix1.M31 * matrix2.M14) + (matrix1.M32 * matrix2.M24)) + (matrix1.M33 * matrix2.M34)) + (matrix1.M34 * matrix2.M44); + float num4 = (((matrix1.M41 * matrix2.M11) + (matrix1.M42 * matrix2.M21)) + (matrix1.M43 * matrix2.M31)) + (matrix1.M44 * matrix2.M41); + float num3 = (((matrix1.M41 * matrix2.M12) + (matrix1.M42 * matrix2.M22)) + (matrix1.M43 * matrix2.M32)) + (matrix1.M44 * matrix2.M42); + float num2 = (((matrix1.M41 * matrix2.M13) + (matrix1.M42 * matrix2.M23)) + (matrix1.M43 * matrix2.M33)) + (matrix1.M44 * matrix2.M43); + float num = (((matrix1.M41 * matrix2.M14) + (matrix1.M42 * matrix2.M24)) + (matrix1.M43 * matrix2.M34)) + (matrix1.M44 * matrix2.M44); + result.M11 = num16; + result.M12 = num15; + result.M13 = num14; + result.M14 = num13; + result.M21 = num12; + result.M22 = num11; + result.M23 = num10; + result.M24 = num9; + result.M31 = num8; + result.M32 = num7; + result.M33 = num6; + result.M34 = num5; + result.M41 = num4; + result.M42 = num3; + result.M43 = num2; + result.M44 = num; + } + + Matrix Matrix::Multiply(Matrix matrix1, float scaleFactor) + { + Matrix result; + Multiply(matrix1, scaleFactor, result); + return result; + } + + void Matrix::Multiply(Matrix matrix1, float scaleFactor, out Matrix result) + { + float num = scaleFactor; + result.M11 = matrix1.M11 * num; + result.M12 = matrix1.M12 * num; + result.M13 = matrix1.M13 * num; + result.M14 = matrix1.M14 * num; + result.M21 = matrix1.M21 * num; + result.M22 = matrix1.M22 * num; + result.M23 = matrix1.M23 * num; + result.M24 = matrix1.M24 * num; + result.M31 = matrix1.M31 * num; + result.M32 = matrix1.M32 * num; + result.M33 = matrix1.M33 * num; + result.M34 = matrix1.M34 * num; + result.M41 = matrix1.M41 * num; + result.M42 = matrix1.M42 * num; + result.M43 = matrix1.M43 * num; + result.M44 = matrix1.M44 * num; + } + + Matrix Matrix::Negate(Matrix matrix) + { + Matrix result; + Negate(matrix, result); + return result; + } + + void Matrix::Negate(Matrix matrix, out Matrix result) + { + result.M11 = -matrix.M11; + result.M12 = -matrix.M12; + result.M13 = -matrix.M13; + result.M14 = -matrix.M14; + result.M21 = -matrix.M21; + result.M22 = -matrix.M22; + result.M23 = -matrix.M23; + result.M24 = -matrix.M24; + result.M31 = -matrix.M31; + result.M32 = -matrix.M32; + result.M33 = -matrix.M33; + result.M34 = -matrix.M34; + result.M41 = -matrix.M41; + result.M42 = -matrix.M42; + result.M43 = -matrix.M43; + result.M44 = -matrix.M44; + } + + Matrix Matrix::Subtract(Matrix matrix1, Matrix matrix2) + { + Matrix result; + Subtract(matrix1, matrix2, result); + return result; + } + + void Matrix::Subtract(Matrix matrix1, Matrix matrix2, out Matrix result) + { + result.M11 = matrix1.M11 - matrix2.M11; + result.M12 = matrix1.M12 - matrix2.M12; + result.M13 = matrix1.M13 - matrix2.M13; + result.M14 = matrix1.M14 - matrix2.M14; + result.M21 = matrix1.M21 - matrix2.M21; + result.M22 = matrix1.M22 - matrix2.M22; + result.M23 = matrix1.M23 - matrix2.M23; + result.M24 = matrix1.M24 - matrix2.M24; + result.M31 = matrix1.M31 - matrix2.M31; + result.M32 = matrix1.M32 - matrix2.M32; + result.M33 = matrix1.M33 - matrix2.M33; + result.M34 = matrix1.M34 - matrix2.M34; + result.M41 = matrix1.M41 - matrix2.M41; + result.M42 = matrix1.M42 - matrix2.M42; + result.M43 = matrix1.M43 - matrix2.M43; + result.M44 = matrix1.M44 - matrix2.M44; + } + + Matrix Matrix::Transpose(Matrix matrix) + { + Matrix ret; + Transpose(matrix, ret); + return ret; + } + + void Matrix::Transpose(Matrix matrix, Matrix result) + { + result.M11 = matrix.M11; + result.M12 = matrix.M21; + result.M13 = matrix.M31; + result.M14 = matrix.M41; + result.M21 = matrix.M12; + result.M22 = matrix.M22; + result.M23 = matrix.M32; + result.M24 = matrix.M42; + result.M31 = matrix.M13; + result.M32 = matrix.M23; + result.M33 = matrix.M33; + result.M34 = matrix.M43; + result.M41 = matrix.M14; + result.M42 = matrix.M24; + result.M43 = matrix.M34; + result.M44 = matrix.M44; + } + + Matrix Matrix::operator+(const Matrix other) + { + return Add(*this, other); + } + + Matrix Matrix::operator /(const Matrix other) + { + return Divide(*this, other); + } + + Matrix Matrix::operator /(const float divider) + { + return Divide(*this, divider); + } + + bool Matrix::operator==(const Matrix other) + { + return Equals(other); + } + + bool Matrix::operator!=(const Matrix other) + { + return !Equals(other); + } + + Matrix Matrix::operator *(const Matrix other) + { + return Multiply(*this, other); + } + + Matrix Matrix::operator *(const float scaleFactor) + { + return Multiply(*this, scaleFactor); + } + + Matrix Matrix::operator -(const Matrix other) + { + return Subtract(*this, other); + } + + Matrix Matrix::operator -() + { + return Negate(*this); + } + + Matrix Matrix::operator=(const Matrix other) + { + M11 = other.M11; + M12 = other.M12; + M13 = other.M13; + M14 = other.M14; + M21 = other.M21; + M22 = other.M22; + M23 = other.M23; + M24 = other.M24; + M31 = other.M31; + M32 = other.M32; + M33 = other.M33; + M34 = other.M34; + M41 = other.M41; + M42 = other.M42; + M43 = other.M43; + M44 = other.M44; + return *this; + } +} diff --git a/src/libXFX/Mouse.cpp b/src/libXFX/Mouse.cpp new file mode 100644 index 0000000..c667e2a --- /dev/null +++ b/src/libXFX/Mouse.cpp @@ -0,0 +1,99 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +extern "C" { +#include +} + +#include + +namespace XFX +{ + namespace Input + { + extern "C"{ + extern struct xmouse_data XMOUSE_current; + } + + //It's a waste of memory to create a new MouseState each time the input states are updated. + //Therefore, we create a static one and update it each time an update is requested. + static MouseState result; + + /* MouseState Operators */ + bool MouseState::operator!=(const MouseState &other) + { + return !((LeftButton == other.LeftButton) && (MiddleButton == other.MiddleButton) && + (RightButton == other.RightButton) && (X == other.X) && (XButton1 == other.XButton1) && + (XButton2 == other.XButton2) && (Y == other.Y)); + } + + bool MouseState::operator==(const MouseState &other) + { + return ((LeftButton == other.LeftButton) && (MiddleButton == other.MiddleButton) && + (RightButton == other.RightButton) && (X == other.X) && (XButton1 == other.XButton1) && + (XButton2 == other.XButton2) && (Y == other.Y)); + } + /* END Mousestate Operators */ + + MouseState Mouse::GetState() + { + result.X +=XMOUSE_current.x; + result.Y +=XMOUSE_current.y; + XMOUSE_current.x=0; + XMOUSE_current.y=0; + + if((XMOUSE_current.buttons & XMOUSE_BUTTON_1)) + result.LeftButton = ButtonState::Pressed; + else + result.LeftButton = ButtonState::Released; + if((XMOUSE_current.buttons & XMOUSE_BUTTON_3)) + result.MiddleButton = ButtonState::Pressed; + else + result.MiddleButton = ButtonState::Released; + if((XMOUSE_current.buttons & XMOUSE_BUTTON_2)) + result.RightButton = ButtonState::Pressed; + else + result.RightButton = ButtonState::Released; + if((XMOUSE_current.buttons & XMOUSE_BUTTON_4)) + result.XButton1 = ButtonState::Pressed; + else + result.XButton1 = ButtonState::Released; + if((XMOUSE_current.buttons & XMOUSE_BUTTON_5)) + result.XButton2 = ButtonState::Pressed; + else + result.XButton2 = ButtonState::Released; + + return result; + } + + void Mouse::SetPosition(int x, int y) + { + result.X = x; + result.Y = y; + } + } +} diff --git a/src/libXFX/PBKit/nv20_shader.h b/src/libXFX/PBKit/nv20_shader.h new file mode 100644 index 0000000..619cc04 --- /dev/null +++ b/src/libXFX/PBKit/nv20_shader.h @@ -0,0 +1,132 @@ + +/* NV20_TCL_PRIMITIVE_3D_0x0B00 */ +#define NV20_VP_INST_0B00 0x00000000 /* always 0 */ +#define NV20_VP_INST0_KNOWN 0 + +/* NV20_TCL_PRIMITIVE_3D_0x0B04 */ +#define NV20_VP_INST_SCA_OPCODE_SHIFT 25 +#define NV20_VP_INST_SCA_OPCODE_MASK (0x0F << 25) +#define NV20_VP_INST_OPCODE_RCP 0x2 +#define NV20_VP_INST_OPCODE_RCC 0x3 +#define NV20_VP_INST_OPCODE_RSQ 0x4 +#define NV20_VP_INST_OPCODE_EXP 0x5 +#define NV20_VP_INST_OPCODE_LOG 0x6 +#define NV20_VP_INST_OPCODE_LIT 0x7 +#define NV20_VP_INST_VEC_OPCODE_SHIFT 21 +#define NV20_VP_INST_VEC_OPCODE_MASK (0x0F << 21) +#define NV20_VP_INST_OPCODE_NOP 0x0 +#define NV20_VP_INST_OPCODE_MOV 0x1 +#define NV20_VP_INST_OPCODE_MUL 0x2 +#define NV20_VP_INST_OPCODE_ADD 0x3 +#define NV20_VP_INST_OPCODE_MAD 0x4 +#define NV20_VP_INST_OPCODE_DP3 0x5 +#define NV20_VP_INST_OPCODE_DPH 0x6 +#define NV20_VP_INST_OPCODE_DP4 0x7 +#define NV20_VP_INST_OPCODE_DST 0x8 +#define NV20_VP_INST_OPCODE_MIN 0x9 +#define NV20_VP_INST_OPCODE_MAX 0xA +#define NV20_VP_INST_OPCODE_SLT 0xB +#define NV20_VP_INST_OPCODE_SGE 0xC +#define NV20_VP_INST_OPCODE_ARL 0xD +#define NV20_VP_INST_CONST_SRC_SHIFT 13 +#define NV20_VP_INST_CONST_SRC_MASK (0xFF << 13) +#define NV20_VP_INST_INPUT_SRC_SHIFT 9 +#define NV20_VP_INST_INPUT_SRC_MASK (0xF << 9) +#define NV20_VP_INST_INPUT_SRC_POS 0 +#define NV20_VP_INST_INPUT_SRC_COL0 3 +#define NV20_VP_INST_INPUT_SRC_COL1 4 +#define NV20_VP_INST_INPUT_SRC_TC(n) (9+n) +#define NV20_VP_INST_SRC0H_SHIFT 0 +#define NV20_VP_INST_SRC0H_MASK (0x1FF << 0) +#define NV20_VP_INST1_KNOWN ( \ + NV20_VP_INST_OPCODE_MASK | \ + NV20_VP_INST_CONST_SRC_MASK | \ + NV20_VP_INST_INPUT_SRC_MASK | \ + NV20_VP_INST_SRC0H_MASK \ + ) + +/* NV20_TCL_PRIMITIVE_3D_0x0B08 */ +#define NV20_VP_INST_SRC0L_SHIFT 26 +#define NV20_VP_INST_SRC0L_MASK (0x3F <<26) +#define NV20_VP_INST_SRC1_SHIFT 11 +#define NV20_VP_INST_SRC1_MASK (0x7FFF<<11) +#define NV20_VP_INST_SRC2H_SHIFT 0 +#define NV20_VP_INST_SRC2H_MASK (0x7FF << 0) + +/* NV20_TCL_PRIMITIVE_3D_0x0B0C */ +#define NV20_VP_INST_SRC2L_SHIFT 28 +#define NV20_VP_INST_SRC2L_MASK (0x0F <<28) +#define NV20_VP_INST_VTEMP_WRITEMASK_SHIFT 24 +#define NV20_VP_INST_VTEMP_WRITEMASK_MASK (0x0F <<24) +# define NV20_VP_INST_TEMP_WRITEMASK_X (1<<27) +# define NV20_VP_INST_TEMP_WRITEMASK_Y (1<<26) +# define NV20_VP_INST_TEMP_WRITEMASK_Z (1<<25) +# define NV20_VP_INST_TEMP_WRITEMASK_W (1<<24) +#define NV20_VP_INST_DEST_TEMP_ID_SHIFT 20 +#define NV20_VP_INST_DEST_TEMP_ID_MASK (0x0F <<20) +#define NV20_VP_INST_STEMP_WRITEMASK_SHIFT 16 +#define NV20_VP_INST_STEMP_WRITEMASK_MASK (0x0F <<16) +# define NV20_VP_INST_STEMP_WRITEMASK_X (1<<19) +# define NV20_VP_INST_STEMP_WRITEMASK_Y (1<<18) +# define NV20_VP_INST_STEMP_WRITEMASK_Z (1<<17) +# define NV20_VP_INST_STEMP_WRITEMASK_W (1<<16) +#define NV20_VP_INST_DEST_WRITEMASK_SHIFT 12 +#define NV20_VP_INST_DEST_WRITEMASK_MASK (0x0F <<12) +# define NV20_VP_INST_DEST_WRITEMASK_X (1<<15) +# define NV20_VP_INST_DEST_WRITEMASK_Y (1<<14) +# define NV20_VP_INST_DEST_WRITEMASK_Z (1<<13) +# define NV20_VP_INST_DEST_WRITEMASK_W (1<<12) +#define NV20_VP_INST_CONST_DEST_FLAG (1<<11) +#define NV20_VP_INST_CONST_DEST_SHIFT 3 +#define NV20_VP_INST_CONST_DEST_MASK (0xFF<< 3) +#define NV20_VP_INST_DEST_SHIFT 3 +#define NV20_VP_INST_DEST_MASK (0xF << 3) +#define NV20_VP_INST_DEST_POS 0 +#define NV20_VP_INST_DEST_COL0 3 +#define NV20_VP_INST_DEST_COL1 4 +#define NV20_VP_INST_DEST_FOG 5 +#define NV20_VP_INST_DEST_PTS 6 +#define NV20_VP_INST_DEST_TC(n) (9+n) +#define NV20_VP_INST_DEST_SCA (1<<2) +#define NV20_VP_INST_INDEX_CONST (1<<1) +#define NV20_VP_INST_LAST_INST (1<<0) +#define NV20_VP_INST3_KNOWN ( \ + NV20_VP_INST_SRC2L_MASK | \ + NV20_VP_INST_VTEMP_WRITEMASK_MASK | \ + NV20_VP_INST_DEST_TEMP_ID_MASK | \ + NV20_VP_INST_STEMP_WRITEMASK_MASK | \ + NV20_VP_INST_DEST_WRITEMASK_MASK | \ + NV20_VP_INST_CONST_DEST_MASK | \ + NV20_VP_INST_DEST_MASK | \ + NV20_VP_INST_DEST_SCA | \ + NV20_VP_INST_INDEX_CONST | \ + NV20_VP_INST_LAST_INST \ + ) + +/* Useful to split the source selection regs into their pieces */ +#define NV20_VP_SRC0_HIGH_SHIFT 6 +#define NV20_VP_SRC0_HIGH_MASK 0x00007FC0 +#define NV20_VP_SRC0_LOW_MASK 0x0000003F +#define NV20_VP_SRC2_HIGH_SHIFT 4 +#define NV20_VP_SRC2_HIGH_MASK 0x00007FF0 +#define NV20_VP_SRC2_LOW_MASK 0x0000000F + +#define NV20_VP_SRC_REG_NEGATE (1<<14) +#define NV20_VP_SRC_REG_SWZ_X_SHIFT 12 +#define NV20_VP_SRC_REG_SWZ_X_MASK (0x03 <<12) +#define NV20_VP_SRC_REG_SWZ_Y_SHIFT 10 +#define NV20_VP_SRC_REG_SWZ_Y_MASK (0x03 <<10) +#define NV20_VP_SRC_REG_SWZ_Z_SHIFT 8 +#define NV20_VP_SRC_REG_SWZ_Z_MASK (0x03 << 8) +#define NV20_VP_SRC_REG_SWZ_W_SHIFT 6 +#define NV20_VP_SRC_REG_SWZ_W_MASK (0x03 << 6) +#define NV20_VP_SRC_REG_SWZ_ALL_SHIFT 6 +#define NV20_VP_SRC_REG_SWZ_ALL_MASK (0xFF << 6) +#define NV20_VP_SRC_REG_TEMP_ID_SHIFT 2 +#define NV20_VP_SRC_REG_TEMP_ID_MASK (0x0F << 0) +#define NV20_VP_SRC_REG_TYPE_SHIFT 0 +#define NV20_VP_SRC_REG_TYPE_MASK (0x03 << 0) +#define NV20_VP_SRC_REG_TYPE_TEMP 1 +#define NV20_VP_SRC_REG_TYPE_INPUT 2 +#define NV20_VP_SRC_REG_TYPE_CONST 3 + diff --git a/src/libXFX/PBKit/nv_objects.h b/src/libXFX/PBKit/nv_objects.h new file mode 100644 index 0000000..c80308e --- /dev/null +++ b/src/libXFX/PBKit/nv_objects.h @@ -0,0 +1,1782 @@ +/* Data */ +#define STOP 0x00000000 +#define POINTS 0x00000001 +#define LINES 0x00000002 +#define LINE_LOOP 0x00000003 +#define LINE_STRIP 0x00000004 +#define TRIANGLES 0x00000005 +#define TRIANGLE_STRIP 0x00000006 +#define TRIANGLE_FAN 0x00000007 +#define QUADS 0x00000008 +#define QUAD_STRIP 0x00000009 +#define POLYGON 0x0000000A + +/* Boolean */ +#define FALSE 0 +#define TRUE 1 + +/* Objects */ +#define NV_MEMORY_TO_MEMORY_FORMAT 0x00000039 +#define NV_MEMORY_TO_MEMORY_FORMAT_NOP 0x00000100 +#define NV_MEMORY_TO_MEMORY_FORMAT_NOTIFY 0x00000104 +#define NV_MEMORY_TO_MEMORY_FORMAT_DMA_NOTIFY 0x00000180 +#define NV_MEMORY_TO_MEMORY_FORMAT_OBJECT_IN 0x00000184 +#define NV_MEMORY_TO_MEMORY_FORMAT_OBJECT_OUT 0x00000188 +#define NV_MEMORY_TO_MEMORY_FORMAT_UNK0 0x00000200 +#define NV_MEMORY_TO_MEMORY_FORMAT_UNK1 0x0000021c +#define NV_MEMORY_TO_MEMORY_FORMAT_UNK2 0x00000220 +#define NV_MEMORY_TO_MEMORY_FORMAT_UNK3 0x00000224 +#define NV_MEMORY_TO_MEMORY_FORMAT_UNK4 0x00000228 +#define NV_MEMORY_TO_MEMORY_FORMAT_UNK5 0x0000022c +#define NV_MEMORY_TO_MEMORY_FORMAT_UNK6 0x00000230 +#define NV_MEMORY_TO_MEMORY_FORMAT_UNK7 0x00000234 +#define NV_MEMORY_TO_MEMORY_FORMAT_UNK8 0x00000238 +#define NV_MEMORY_TO_MEMORY_FORMAT_UNK9 0x0000023c +#define NV_MEMORY_TO_MEMORY_FORMAT_OFFSET_IN 0x0000030C +#define NV_MEMORY_TO_MEMORY_FORMAT_OFFSET_OUT 0x00000310 +#define NV_MEMORY_TO_MEMORY_FORMAT_PITCH_IN 0x00000314 +#define NV_MEMORY_TO_MEMORY_FORMAT_PITCH_OUT 0x00000318 +#define NV_MEMORY_TO_MEMORY_FORMAT_LINE_LENGTH_IN 0x0000031C +#define NV_MEMORY_TO_MEMORY_FORMAT_LINE_COUNT 0x00000320 +#define NV_MEMORY_TO_MEMORY_FORMAT_FORMAT 0x00000324 +#define NV_MEMORY_TO_MEMORY_FORMAT_BUF_NOTIFY 0x00000328 + + +#define NV04_GDI_RECTANGLE_TEXT 0x0000004a + +#define NV04_GDI_RECTANGLE_TEXT_SET_DMA_NOTIFY 0x00000180 +#define NV04_GDI_RECTANGLE_TEXT_PATTERN 0x00000188 +#define NV04_GDI_RECTANGLE_TEXT_ROP5 0x0000018c +#define NV04_GDI_RECTANGLE_TEXT_SURFACE 0x00000198 + +#define NV04_GDI_RECTANGLE_TEXT_OPERATION 0x000002fc +#define NV04_GDI_RECTANGLE_TEXT_FORMAT 0x00000300 + +#define NV04_GDI_RECTANGLE_TEXT_SOLID_COLOR 0x000003fc +#define NV04_GDI_RECTANGLE_TEXT_SOLID_RECTS(i) (0x00000400+(i)*8) +#define NV04_GDI_RECTANGLE_TEXT_SOLID_RECTS__SIZE 32 +#define NV04_GDI_RECTANGLE_TEXT_SOLID_RECTS_Y 15:0 +#define NV04_GDI_RECTANGLE_TEXT_SOLID_RECTS_X 31:16 +#define NV04_GDI_RECTANGLE_TEXT_SOLID_RECTS_HEIGHT 47:32 +#define NV04_GDI_RECTANGLE_TEXT_SOLID_RECTS_WIDTH 63:48 + +#define NV04_GDI_RECTANGLE_TEXT_BLOCK_LEVEL1_TL 0x000005f4 +#define NV04_GDI_RECTANGLE_TEXT_BLOCK_LEVEL1_BR 0x000005f8 +#define NV04_GDI_RECTANGLE_TEXT_FILL_VALUE 0x000005fc +#define NV04_GDI_RECTANGLE_TEXT_BLOCK_LEVEL2_TL 0x00000600 +#define NV04_GDI_RECTANGLE_TEXT_BLOCK_LEVEL2_BR 0x00000604 + +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_ONE_COLOR_CLIP 0x000007ec +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_ONE_COLOR_CLIP_POINT0_X 15:0 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_ONE_COLOR_CLIP_POINT0_Y 31:16 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_ONE_COLOR_CLIP_POINT1_X 47:32 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_ONE_COLOR_CLIP_POINT1_Y 63:48 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_ONE_COLOR_COLOR 0x000007f4 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_ONE_COLOR_SIZE 0x000007f8 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_ONE_COLOR_SIZE_WIDTH 15:0 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_ONE_COLOR_SIZE_HEIGHT 31:16 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_ONE_COLOR_POINT 0x000007fc +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_ONE_COLOR_POINT_X 15:0 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_ONE_COLOR_POINT_Y 31:16 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_ONE_COLOR_DATA(i) (0x00000800+(i)*4) +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_ONE_COLOR_DATA__SIZE 128 + +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_CLIP 0x00000be4 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_CLIP_POINT0_X 15:0 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_CLIP_POINT0_Y 31:16 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_CLIP_POINT1_X 47:32 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_CLIP_POINT1_Y 63:48 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_COLOR_0 0x00000bec +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_COLOR_1 0x00000bfc +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_SIZE_IN 0x00000bf4 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_SIZE_IN_WIDTH 15:0 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_SIZE_IN_HEIGHT 31:16 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_SIZE_OUT 0x00000bf8 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_SIZE_OUT_WIDTH 15:0 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_SIZE_OUT_HEIGH 31:16 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_POINT 0x00000bfc +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_POINT_X 15:0 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_POINT_Y 31:16 +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_DATA(i) (0x00000c00+(i)*4) +#define NV04_GDI_RECTANGLE_TEXT_EXPAND_TWO_COLOR_DATA__SIZE 128 + + +#define NV04_CONTEXT_SURFACES_3D 0x00000053 +#define NV04_CONTEXT_SURFACES_3D_DMA_NOTIFY 0x00000180 +#define NV04_CONTEXT_SURFACES_3D_DMA_COLOR 0x00000184 +#define NV04_CONTEXT_SURFACES_3D_DMA_ZETA 0x00000188 +#define NV04_CONTEXT_SURFACES_3D_CLIP_HORIZONTAL 0x000002F8 +#define NV04_CONTEXT_SURFACES_3D_CLIP_HORIZONTAL_X 15:0 +#define NV04_CONTEXT_SURFACES_3D_CLIP_HORIZONTAL_WIDTH 31:16 +#define NV04_CONTEXT_SURFACES_3D_CLIP_VERTICAL 0x000002FC +#define NV04_CONTEXT_SURFACES_3D_CLIP_VERTICAL_Y 15:0 +#define NV04_CONTEXT_SURFACES_3D_CLIP_VERTICAL_HEIGHT 31:16 +#define NV04_CONTEXT_SURFACES_3D_FORMAT 0x00000300 +#define NV04_CONTEXT_SURFACES_3D_FORMAT_COLOR 7:0 +#define NV04_CONTEXT_SURFACES_3D_FORMAT_TYPE 15:8 +#define NV04_CONTEXT_SURFACES_3D_FORMAT_WIDTH 23:16 // also I get zeroes here +#define NV04_CONTEXT_SURFACES_3D_FORMAT_HEIGHT 31:24 // see above +#define NV04_CONTEXT_SURFACES_3D_CLIP_SIZE 0x00000304 +#define NV04_CONTEXT_SURFACES_3D_CLIP_SIZE_WIDTH 15:0 +#define NV04_CONTEXT_SURFACES_3D_CLIP_SIZE_HEIGHT 31:15 +#define NV04_CONTEXT_SURFACES_3D_PITCH 0x00000308 +#define NV04_CONTEXT_SURFACES_3D_PITCH_COLOR 15:0 +#define NV04_CONTEXT_SURFACES_3D_PITCH_ZETA 31:16 +#define NV04_CONTEXT_SURFACES_3D_OFFSET_COLOR 0x0000030c +#define NV04_CONTEXT_SURFACES_3D_OFFSET_ZETA 0x00000310 + + +#define NV04_DX5_TEXTURED_TRIANGLE 0x00000054 + +#define NV04_DX5_TEXTURED_TRIANGLE_NOP 0x00000100 +#define NV04_DX5_TEXTURED_TRIANGLE_NOTIFY 0x00000104 + +#define NV04_DX5_TEXTURED_TRIANGLE_DMA_NOTIFY 0x00000180 +#define NV04_DX5_TEXTURED_TRIANGLE_DMA_1 0x00000184 +#define NV04_DX5_TEXTURED_TRIANGLE_DMA_2 0x00000188 +#define NV04_DX5_TEXTURED_TRIANGLE_SURFACE 0x0000018c + +#define NV04_DX5_TEXTURED_TRIANGLE_COLOR_KEY 0x00000300 +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_OFFSET 0x00000304 +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_FORMAT 0x00000308 +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_FORMAT_WRAP_T 30:28 +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_FORMAT_WRAP_S 26:24 +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_FORMAT_SIZE_V 23:20 +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_FORMAT_SIZE_U 19:16 +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_FORMAT_MIPMAPS 15:12 +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_FORMAT_COLOR 11:8 +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_FILTER 0x0000030C +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_FILTER_MAG 30:28 +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_FILTER_MIN 26:24 +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_FILTER_LODBIAS 23:16 +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_FILTER_DITHER 15:15 +#define NV04_DX5_TEXTURED_TRIANGLE_BLEND 0x00000310 +#define NV04_DX5_TEXTURED_TRIANGLE_BLEND_DST 31:28 +#define NV04_DX5_TEXTURED_TRIANGLE_BLEND_SRC 27:24 +#define NV04_DX5_TEXTURED_TRIANGLE_BLEND_ENABLE 20:20 +#define NV04_DX5_TEXTURED_TRIANGLE_BLEND_FOG 16:16 +#define NV04_DX5_TEXTURED_TRIANGLE_BLEND_SPECULAR 12:12 +#define NV04_DX5_TEXTURED_TRIANGLE_BLEND_TEXTUREPERSPECTIVE 8:8 +#define NV04_DX5_TEXTURED_TRIANGLE_BLEND_SHADEMODE 7:6 +#define NV04_DX5_TEXTURED_TRIANGLE_BLEND_TEXTURE 3:0 +#define NV04_DX5_TEXTURED_TRIANGLE_CONTROL 0x00000314 +#define NV04_DX5_TEXTURED_TRIANGLE_CONTROL_ALPHAREF 7:0 +#define NV04_DX5_TEXTURED_TRIANGLE_CONTROL_ALPHAFUNC 11:8 +#define NV04_DX5_TEXTURED_TRIANGLE_CONTROL_ALPHATEST 12:12 +#define NV04_DX5_TEXTURED_TRIANGLE_CONTROL_ZENABLE 14:14 +#define NV04_DX5_TEXTURED_TRIANGLE_CONTROL_ZFUNC 19:16 +#define NV04_DX5_TEXTURED_TRIANGLE_CONTROL_CULLMODE 21:20 +#define NV04_DX5_TEXTURED_TRIANGLE_CONTROL_DITHER 22:22 +#define NV04_DX5_TEXTURED_TRIANGLE_CONTROL_ZPERSPECTIVE 23:23 +#define NV04_DX5_TEXTURED_TRIANGLE_CONTROL_ZWRITE 24:24 +#define NV04_DX5_TEXTURED_TRIANGLE_CONTROL_ZFORMAT 31:30 +#define NV04_DX5_TEXTURED_TRIANGLE_FOG_COLOR 0x00000318 + + +#define NV04_DX5_TEXTURED_TRIANGLE_TLVERTEX_SX(i) (0x00000400 + 0x20 * i) +#define NV04_DX5_TEXTURED_TRIANGLE_TLVERTEX_SX__SIZE 16 +#define NV04_DX5_TEXTURED_TRIANGLE_TLVERTEX_SY(i) (0x00000404 + 0x20 * i) +#define NV04_DX5_TEXTURED_TRIANGLE_TLVERTEX_SY__SIZE 16 +#define NV04_DX5_TEXTURED_TRIANGLE_TLVERTEX_SZ(i) (0x00000408 + 0x20 * i) +#define NV04_DX5_TEXTURED_TRIANGLE_TLVERTEX_SZ__SIZE 16 +#define NV04_DX5_TEXTURED_TRIANGLE_INV_W(i) (0x0000040C + 0x20 * i) +#define NV04_DX5_TEXTURED_TRIANGLE_INV_W__SIZE 16 +#define NV04_DX5_TEXTURED_TRIANGLE_COLOR(i) (0x00000410 + 0x20 * i) +#define NV04_DX5_TEXTURED_TRIANGLE_COLOR__SIZE 16 +#define NV04_DX5_TEXTURED_TRIANGLE_SPECULAR(i) (0x00000414 + 0x20 * i) +#define NV04_DX5_TEXTURED_TRIANGLE_SPECULAR__SIZE 16 +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_S(i) (0x00000418 + 0x20 * i) +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_S__SIZE 16 +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_T(i) (0x0000041C + 0x20 * i) +#define NV04_DX5_TEXTURED_TRIANGLE_TEXTURE_T__SIZE 16 + +#define NV04_DX5_TEXTURED_TRIANGLE_DRAW 0x00000600 +#define NV04_DX5_TEXTURED_TRIANGLE_DRAW_V0 3:0 +#define NV04_DX5_TEXTURED_TRIANGLE_DRAW_V1 7:4 +#define NV04_DX5_TEXTURED_TRIANGLE_DRAW_V2 11:8 +#define NV04_DX5_TEXTURED_TRIANGLE_DRAW_V3 15:12 +#define NV04_DX5_TEXTURED_TRIANGLE_DRAW_V4 19:16 +#define NV04_DX5_TEXTURED_TRIANGLE_DRAW_V5 23:20 + +#define NV04_DX6_MULTITEX_TRIANGLE 0x00000055 + +#define NV04_DX6_MULTITEX_TRIANGLE_NOP 0x00000100 +#define NV04_DX6_MULTITEX_TRIANGLE_NOTIFY 0x00000104 + +#define NV04_DX6_MULTITEX_TRIANGLE_DMA_NOTIFY 0x00000180 +#define NV04_DX6_MULTITEX_TRIANGLE_DMA_1 0x00000184 +#define NV04_DX6_MULTITEX_TRIANGLE_DMA_2 0x00000188 +#define NV04_DX6_MULTITEX_TRIANGLE_SURFACE 0x0000018c + +#define NV04_DX6_MULTITEX_TRIANGLE_OFFSET0 0x00000308 +#define NV04_DX6_MULTITEX_TRIANGLE_OFFSET1 0x0000030c +#define NV04_DX6_MULTITEX_TRIANGLE_FORMAT0 0x00000310 +#define NV04_DX6_MULTITEX_TRIANGLE_FORMAT1 0x00000314 +#define NV04_DX6_MULTITEX_TRIANGLE_FILTER0 0x00000318 +#define NV04_DX6_MULTITEX_TRIANGLE_FILTER1 0x0000031c +#define NV04_DX6_MULTITEX_TRIANGLE_COMBINE_0_ALPHA 0x00000320 +#define NV04_DX6_MULTITEX_TRIANGLE_COMBINE_0_COLOR 0x00000324 +#define NV04_DX6_MULTITEX_TRIANGLE_COMBINE_1_ALPHA 0x0000032c +#define NV04_DX6_MULTITEX_TRIANGLE_COMBINE_1_COLOR 0x00000330 +#define NV04_DX6_MULTITEX_TRIANGLE_COMBINE_FACTOR 0x00000334 + +#define NV04_DX6_MULTITEX_TRIANGLE_BLEND 0x00000338 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL0 0x0000033c +// control0 is more or less the same as 0x54 (dx5_tri)_control +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL0_R_WRITE 27:27 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL0_G_WRITE 28:28 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL0_B_WRITE 29:29 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL0_A_WRITE 26:26 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL0_S_WRITE 25:25 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL1 0x00000340 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL1_STENCILENABLE 0:0 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL1_STENCILFUNC 7:4 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL1_STENCILREF 15:8 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL1_STENCIL_MASK_READ 23:16 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL1_STENCIL_MASK_WRITE 31:24 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL2 0x00000344 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL2_STENCIL_FAIL 3:0 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL2_STENCIL_ZFAIL 7:4 +#define NV04_DX6_MULTITEX_TRIANGLE_CONTROL2_STENCIL_ZPASS 11:8 +#define NV04_DX6_MULTITEX_TRIANGLE_FOG_COLOR 0x00000348 + +#define NV04_DX6_MULTITEX_TRIANGLE_TLVERTEX_SX(i) (0x00000400 + 0x28 * i) +#define NV04_DX6_MULTITEX_TRIANGLE_TLVERTEX_SX__SIZE 8 +#define NV04_DX6_MULTITEX_TRIANGLE_TLVERTEX_SY(i) (0x00000404 + 0x28 * i) +#define NV04_DX6_MULTITEX_TRIANGLE_TLVERTEX_SY__SIZE 8 +#define NV04_DX6_MULTITEX_TRIANGLE_TLVERTEX_SZ(i) (0x00000408 + 0x28 * i) +#define NV04_DX6_MULTITEX_TRIANGLE_TLVERTEX_SZ__SIZE 8 +#define NV04_DX6_MULTITEX_TRIANGLE_INV_W(i) (0x0000040C + 0x28 * i) +#define NV04_DX6_MULTITEX_TRIANGLE_INV_W__SIZE 8 +#define NV04_DX6_MULTITEX_TRIANGLE_COLOR(i) (0x00000410 + 0x28 * i) +#define NV04_DX6_MULTITEX_TRIANGLE_COLOR__SIZE 8 +#define NV04_DX6_MULTITEX_TRIANGLE_SPECULAR(i) (0x00000414 + 0x28 * i) +#define NV04_DX6_MULTITEX_TRIANGLE_SPECULAR__SIZE 8 +#define NV04_DX6_MULTITEX_TRIANGLE_TEXTURE0_S(i) (0x00000418 + 0x28 * i) +#define NV04_DX6_MULTITEX_TRIANGLE_TEXTURE0_S__SIZE 8 +#define NV04_DX6_MULTITEX_TRIANGLE_TEXTURE0_T(i) (0x0000041C + 0x28 * i) +#define NV04_DX6_MULTITEX_TRIANGLE_TEXTURE0_T__SIZE 8 +#define NV04_DX6_MULTITEX_TRIANGLE_TEXTURE1_S(i) (0x00000420 + 0x28 * i) +#define NV04_DX6_MULTITEX_TRIANGLE_TEXTURE1_S__SIZE 8 +#define NV04_DX6_MULTITEX_TRIANGLE_TEXTURE1_T(i) (0x00000424 + 0x28 * i) +#define NV04_DX6_MULTITEX_TRIANGLE_TEXTURE1_T__SIZE 8 + +#define NV04_DX6_MULTITEX_TRIANGLE_DRAW 0x00000540 +#define NV04_DX6_MULTITEX_TRIANGLE_DRAW_V0 3:0 +#define NV04_DX6_MULTITEX_TRIANGLE_DRAW_V1 7:4 +#define NV04_DX6_MULTITEX_TRIANGLE_DRAW_V2 11:8 +#define NV04_DX6_MULTITEX_TRIANGLE_DRAW_V3 15:12 +#define NV04_DX6_MULTITEX_TRIANGLE_DRAW_V4 19:16 +#define NV04_DX6_MULTITEX_TRIANGLE_DRAW_V5 23:20 + +#define NV04_COLOR_KEY 0x00000057 +#define NV04_COLOR_KEY_SET_DMA_NOTIFY 0x00000180 +#define NV04_COLOR_KEY_FORMAT 0x00000300 +#define NV04_COLOR_KEY_VALUE 0x00000304 + +#define NV04_SOLID_LINE 0x0000005c +#define NV04_SOLID_LINE_CLIP_RECTANGLE 0x00000184 +#define NV04_SOLID_LINE_PATTERN 0x00000188 +#define NV04_SOLID_LINE_ROP 0x0000018c +#define NV04_SOLID_LINE_SURFACE 0x00000198 +#define NV04_SOLID_LINE_OPERATION 0x000002FC +#define NV04_SOLID_LINE_COLOR_FORMAT 0x00000300 +#define NV04_SOLID_LINE_COLOR_VALUE 0x00000304 +#define NV04_SOLID_LINE_START 0x00000400 +#define NV04_SOLID_LINE_START_X 15:0 +#define NV04_SOLID_LINE_START_Y 31:16 +#define NV04_SOLID_LINE_END 0x00000400 +#define NV04_SOLID_LINE_END_X 15:0 +#define NV04_SOLID_LINE_END_Y 31:16 + +#define NV04_UNK005E 0x0000005e +#define NV04_UNK005E_SET_SURFACE 0x00000198 +#define NV04_UNK005E_UNK02fc 0x000002fc +#define NV04_UNK005E_UNK0300 0x00000300 +#define NV04_UNK005E_COUNTER 0x00000304 + +#define NV_IMAGE_FROM_CPU 0x00000061 +#define NV_IMAGE_FROM_CPU_DMA_NOTIFY 0x00000180 +#define NV_IMAGE_FROM_CPU_CLIP_RECTANGLE 0x00000188 +#define NV_IMAGE_FROM_CPU_PATTERN 0x0000018C +#define NV_IMAGE_FROM_CPU_ROP 0x00000190 +#define NV_IMAGE_FROM_CPU_SURFACE 0x0000019C +#define NV_IMAGE_FROM_CPU_OPERATION 0x000002FC +#define NV_IMAGE_FROM_CPU_FORMAT 0x00000300 + +// XXX: the hw context holds type = 061 ! +#define NV05_IMAGE_FROM_CPU 0x00000065 + +#define NV05_IMAGE_FROM_CPU_DMA_NOTIFY 0x00000180 +#define NV05_IMAGE_FROM_CPU_CLIP_RECTANGLE 0x00000188 +#define NV05_IMAGE_FROM_CPU_PATTERN 0x0000018C +#define NV05_IMAGE_FROM_CPU_ROP 0x00000190 +#define NV05_IMAGE_FROM_CPU_SURFACE 0x0000019C +#define NV05_IMAGE_FROM_CPU_OPERATION 0x000002FC +#define NV05_IMAGE_FROM_CPU_FORMAT 0x00000300 +#define NV05_IMAGE_FROM_CPU_POINT 0x00000304 +#define NV05_IMAGE_FROM_CPU_POINT_X 15:0 +#define NV05_IMAGE_FROM_CPU_POINT_Y 31:16 +#define NV05_IMAGE_FROM_CPU_SIZE_OUT 0x00000308 +#define NV05_IMAGE_FROM_CPU_SIZE_OUT_WIDTH 15:0 +#define NV05_IMAGE_FROM_CPU_SIZE_OUT_HEIGHT 31:16 +#define NV05_IMAGE_FROM_CPU_SIZE_IN 0x0000030c +#define NV05_IMAGE_FROM_CPU_SIZE_IN_WIDTH 15:0 +#define NV05_IMAGE_FROM_CPU_SIZE_IN_HEIGHT 31:16 +#define NV05_IMAGE_FROM_CPU_COLOR(i) (0x000000400 + 4 * i) +#define NV05_IMAGE_FROM_CPU_COLOR__SIZE 1792 + +/* +NV10_TCL_PRIMITIVE_3D unknown commands + values +0120 1 (nv11+) set to 0 on init context, correspond to nv10_image_blit[0x120] +0124 1 (nv11+) set to 1 on init context, correspond to nv10_image_blit[0x124] +0128 1 (nv11+) set to 2 on init context, correspond to nv10_image_blit[0x128] +0258-025c 2 (nv17+) set to 1 on init context +0290 1 set to 0x00100001 on init context +02b4 1 set to 0 before setting the clip_horiz,vert values +03f0 1 (nv15+) set to 3 when fsaa is enabled, renders then set to 2 for swap buffers +03f4 1 set to 0 on init context +03f8 1 (nv17+) set to 0 on init context +03fc 1 (nv17+) set to 0xff on init context if double buffer, 0 otherwise +0d74 1 (nv17+) set to 0 on init context +0d84 1 (nv17+) set to 3 on init context +*/ + +#define NV10_TCL_PRIMITIVE_3D 0x00000056 +#define NV11_TCL_PRIMITIVE_3D 0x00000096 +#define NV17_TCL_PRIMITIVE_3D 0x00000099 + +#define NV10_TCL_PRIMITIVE_3D_NOP 0x00000100 +#define NV10_TCL_PRIMITIVE_3D_NOTIFY 0x00000104 +// 0x00000120 +// 0x00000124 +// 0x00000128 +#define NV10_TCL_PRIMITIVE_3D_SET_DMA_NOTIFY 0x00000180 +#define NV10_TCL_PRIMITIVE_3D_SET_DMA_IN_MEMORY0 0x00000184 +#define NV10_TCL_PRIMITIVE_3D_SET_DMA_IN_MEMORY1 0x00000188 +#define NV10_TCL_PRIMITIVE_3D_SET_DISPLAY_LIST 0x0000018c +#define NV10_TCL_PRIMITIVE_3D_SET_DMA_IN_MEMORY2 0x00000194 +#define NV10_TCL_PRIMITIVE_3D_SET_DMA_IN_MEMORY3 0x00000198 +#define NV17_TCL_PRIMITIVE_3D_SET_DMA_IN_MEMORY4 0x000001ac +#define NV17_TCL_PRIMITIVE_3D_SET_DMA_IN_MEMORY5 0x000001b0 +#define NV10_TCL_PRIMITIVE_3D_VIEWPORT_HORIZ 0x00000200 +#define NV10_TCL_PRIMITIVE_3D_VIEWPORT_VERT 0x00000204 +#define NV10_TCL_PRIMITIVE_3D_BUFFER_FORMAT 0x00000208 +#define NV10_TCL_PRIMITIVE_3D_BUFFER_PITCH 0x0000020c +#define NV10_TCL_PRIMITIVE_3D_COLOR_OFFSET 0x00000210 +#define NV10_TCL_PRIMITIVE_3D_DEPTH_OFFSET 0x00000214 +#define NV10_TCL_PRIMITIVE_3D_TX_OFFSET(n) (0x00000218+(n<<2)) +#define NV10_TCL_PRIMITIVE_3D_TX_FORMAT(n) (0x00000220+(n<<2)) +#define NV10_TCL_PRIMITIVE_3D_TX_ENABLE(n) (0x00000228+(n<<2)) +#define NV10_TCL_PRIMITIVE_3D_TX_NPOT_PITCH(n) (0x00000230+(n<<2)) +#define NV10_TCL_PRIMITIVE_3D_TX_NPOT_SIZE(n) (0x00000240+(n<<2)) +#define NV10_TCL_PRIMITIVE_3D_TX_FILTER(n) (0x00000248+(n<<2)) +#define NV10_TCL_PRIMITIVE_3D_TX_PALETTE_OFFSET(n) (0x00000250+(n<<2)) +// 0x00000258 +// 0x0000025c +#define NV10_TCL_PRIMITIVE_3D_RC_IN_ALPHA(n) (0x00000260+(n<<2)) /* input combiners, portion alpha */ +#define NV10_TCL_PRIMITIVE_3D_RC_IN_RGB(n) (0x00000268+(n<<2)) /* input combiners, portion rgb */ +#define NV10_TCL_PRIMITIVE_3D_RC_COLOR0 0x00000270 /* combiners, constant colors */ +#define NV10_TCL_PRIMITIVE_3D_RC_COLOR1 0x00000274 +#define NV10_TCL_PRIMITIVE_3D_RC_OUT_ALPHA(n) (0x00000278+(n<<2)) /* output combiners, portion alpha */ +#define NV10_TCL_PRIMITIVE_3D_RC_OUT_RGB(n) (0x00000280+(n<<2)) /* output combiners, portion rgb */ +#define NV10_TCL_PRIMITIVE_3D_RC_FINAL0 0x00000288 /* final combiner, variables A-D */ +#define NV10_TCL_PRIMITIVE_3D_RC_FINAL1 0x0000028c /* final combiner, variables E-G */ +// 0x00000290 +#define NV10_TCL_PRIMITIVE_3D_LIGHT_MODEL 0x00000294 +#define NV10_TCL_PRIMITIVE_3D_COLOR_MATERIAL_ENABLE 0x00000298 +#define NV10_TCL_PRIMITIVE_3D_FOG_MODE 0x0000029c +#define NV10_TCL_PRIMITIVE_3D_FOG_COORD_DIST 0x000002a0 +#define NV10_TCL_PRIMITIVE_3D_FOG_ENABLE 0x000002a4 +#define NV10_TCL_PRIMITIVE_3D_FOG_COLOR 0x000002a8 +// 0x000002b4 +#define NV17_TCL_PRIMITIVE_3D_COLOR_MASK_ENABLE 0x000002bc +#define NV10_TCL_PRIMITIVE_3D_VIEWPORT_CLIP_HORIZ(n) (0x000002c0+(n<<2)) +#define NV10_TCL_PRIMITIVE_3D_VIEWPORT_CLIP_VERT(n) (0x000002e0+(n<<2)) +#define NV10_TCL_PRIMITIVE_3D_ALPHA_FUNC_ENABLE 0x00000300 +#define NV10_TCL_PRIMITIVE_3D_BLEND_FUNC_ENABLE 0x00000304 +#define NV10_TCL_PRIMITIVE_3D_CULL_FACE_ENABLE 0x00000308 +#define NV10_TCL_PRIMITIVE_3D_DEPTH_TEST_ENABLE 0x0000030c +#define NV10_TCL_PRIMITIVE_3D_DITHER_ENABLE 0x00000310 +#define NV10_TCL_PRIMITIVE_3D_LIGHTING_ENABLE 0x00000314 +#define NV10_TCL_PRIMITIVE_3D_POINT_PARAMETERS_ENABLE 0x00000318 +#define NV10_TCL_PRIMITIVE_3D_POINT_SMOOTH_ENABLE 0x0000031c +#define NV10_TCL_PRIMITIVE_3D_LINE_SMOOTH_ENABLE 0x00000320 +#define NV10_TCL_PRIMITIVE_3D_POLYGON_SMOOTH_ENABLE 0x00000324 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_WEIGHT_ENABLE 0x00000328 +#define NV10_TCL_PRIMITIVE_3D_STENCIL_ENABLE 0x0000032c +#define NV10_TCL_PRIMITIVE_3D_POLYGON_OFFSET_POINT_ENABLE 0x00000330 +#define NV10_TCL_PRIMITIVE_3D_POLYGON_OFFSET_LINE_ENABLE 0x00000334 +#define NV10_TCL_PRIMITIVE_3D_POLYGON_OFFSET_FILL_ENABLE 0x00000338 +#define NV10_TCL_PRIMITIVE_3D_ALPHA_FUNC_FUNC 0x0000033c +#define NV10_TCL_PRIMITIVE_3D_ALPHA_FUNC_REF 0x00000340 +#define NV10_TCL_PRIMITIVE_3D_BLEND_FUNC_SRC 0x00000344 +#define NV10_TCL_PRIMITIVE_3D_BLEND_FUNC_DST 0x00000348 +#define NV10_TCL_PRIMITIVE_3D_BLEND_COLOR 0x0000034c +#define NV10_TCL_PRIMITIVE_3D_BLEND_EQUATION 0x00000350 +#define NV10_TCL_PRIMITIVE_3D_DEPTH_FUNC 0x00000354 +#define NV10_TCL_PRIMITIVE_3D_COLOR_MASK 0x00000358 +#define NV10_TCL_PRIMITIVE_3D_DEPTH_WRITE_ENABLE 0x0000035c +#define NV10_TCL_PRIMITIVE_3D_STENCIL_MASK 0x00000360 +#define NV10_TCL_PRIMITIVE_3D_STENCIL_FUNC_FUNC 0x00000364 +#define NV10_TCL_PRIMITIVE_3D_STENCIL_FUNC_REF 0x00000368 +#define NV10_TCL_PRIMITIVE_3D_STENCIL_FUNC_MASK 0x0000036c +#define NV10_TCL_PRIMITIVE_3D_STENCIL_OP_FAIL 0x00000370 +#define NV10_TCL_PRIMITIVE_3D_STENCIL_OP_ZFAIL 0x00000374 +#define NV10_TCL_PRIMITIVE_3D_STENCIL_OP_ZPASS 0x00000378 +#define NV10_TCL_PRIMITIVE_3D_SHADE_MODEL 0x0000037c +#define NV10_TCL_PRIMITIVE_3D_LINE_WIDTH 0x00000380 /* 8.0 * line_width */ +#define NV10_TCL_PRIMITIVE_3D_POLYGON_OFFSET_FACTOR 0x00000384 +#define NV10_TCL_PRIMITIVE_3D_POLYGON_OFFSET_UNITS 0x00000388 +#define NV10_TCL_PRIMITIVE_3D_POLYGON_MODE_FRONT 0x0000038c +#define NV10_TCL_PRIMITIVE_3D_POLYGON_MODE_BACK 0x00000390 +#define NV10_TCL_PRIMITIVE_3D_DEPTH_RANGE_NEAR 0x00000394 /* near * 16777216.0 */ +#define NV10_TCL_PRIMITIVE_3D_DEPTH_RANGE_FAR 0x00000398 /* far * 16777216.0 */ +#define NV10_TCL_PRIMITIVE_3D_CULL_FACE 0x0000039c +#define NV10_TCL_PRIMITIVE_3D_FRONT_FACE 0x000003a0 +#define NV10_TCL_PRIMITIVE_3D_NORMALIZE_ENABLE 0x000003a4 +#define NV10_TCL_PRIMITIVE_3D_COLOR_MATERIAL_R 0x000003a8 +#define NV10_TCL_PRIMITIVE_3D_COLOR_MATERIAL_G 0x000003ac +#define NV10_TCL_PRIMITIVE_3D_COLOR_MATERIAL_B 0x000003b0 +#define NV10_TCL_PRIMITIVE_3D_COLOR_MATERIAL_A 0x000003b4 +#define NV10_TCL_PRIMITIVE_3D_COLOR_CONTROL 0x000003b8 +#define NV10_TCL_PRIMITIVE_3D_ENABLED_LIGHTS 0x000003bc +#define NV10_TCL_PRIMITIVE_3D_CLIP_PLANE_ENABLE(n) (0x000003c0+(n<<2)) +#define NV10_TCL_PRIMITIVE_3D_CLIP_PLANE_ENABLE__SIZE 8 +#define NV10_TCL_PRIMITIVE_3D_TX_MATRIX_ENABLE(n) (0x000003e0+(n<<2)) +#define NV10_TCL_PRIMITIVE_3D_VIEW_MATRIX_ENABLE 0x000003e8 +#define NV10_TCL_PRIMITIVE_3D_POINT_SIZE 0x000003ec /* 8.0 * point_size */ +// 0x000003f0 +// 0x000003f4 +// 0x000003f8 +// 0x000003fc +#define NV10_TCL_PRIMITIVE_3D_MODELVIEW0_MATRIX 0x00000400 +#define NV10_TCL_PRIMITIVE_3D_MODELVIEW1_MATRIX 0x00000440 +#define NV10_TCL_PRIMITIVE_3D_INVERSE_MODELVIEW0_MATRIX 0x00000480 +#define NV10_TCL_PRIMITIVE_3D_INVERSE_MODELVIEW1_MATRIX 0x000004c0 +#define NV10_TCL_PRIMITIVE_3D_PROJECTION_MATRIX 0x00000500 +#define NV10_TCL_PRIMITIVE_3D_TX_MATRIX(n) (0x00000540+(n<<6)) +#define NV10_TCL_PRIMITIVE_3D_CLIP_PLANE_A(n) (0x00000600+(n<<4)) +#define NV10_TCL_PRIMITIVE_3D_CLIP_PLANE_B(n) (0x00000604+(n<<4)) +#define NV10_TCL_PRIMITIVE_3D_CLIP_PLANE_C(n) (0x00000608+(n<<4)) +#define NV10_TCL_PRIMITIVE_3D_CLIP_PLANE_D(n) (0x0000060c+(n<<4)) +#define NV10_TCL_PRIMITIVE_3D_FOG_EQUATION_CONSTANT 0x00000680 /* 1.0+(end/(end-start)) */ +#define NV10_TCL_PRIMITIVE_3D_FOG_EQUATION_LINEAR 0x00000684 /* -1.0/(end-start) */ +#define NV10_TCL_PRIMITIVE_3D_FOG_EQUATION_QUADRATIC 0x00000688 /* 0.0 */ +#define NV10_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_A 0x000006a0 +#define NV10_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_B 0x000006a4 +#define NV10_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_C 0x000006a8 +#define NV10_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_D 0x000006ac +#define NV10_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_E 0x000006b0 +#define NV10_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_F 0x000006b4 +#define NV10_TCL_PRIMITIVE_3D_LIGHT_MODEL_FRONT_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_R 0x000006c4 +#define NV10_TCL_PRIMITIVE_3D_LIGHT_MODEL_FRONT_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_G 0x000006c8 +#define NV10_TCL_PRIMITIVE_3D_LIGHT_MODEL_FRONT_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_B 0x000006cc +#define NV10_TCL_PRIMITIVE_3D_VIEWPORT_SCALE_X 0x000006e8 /* unsure */ +#define NV10_TCL_PRIMITIVE_3D_VIEWPORT_SCALE_Y 0x000006ec +#define NV10_TCL_PRIMITIVE_3D_VIEWPORT_SCALE_Z 0x000006f0 +#define NV10_TCL_PRIMITIVE_3D_VIEWPORT_SCALE_W 0x000006f4 +#define NV10_TCL_PRIMITIVE_3D_POINT_PARAMETER_A 0x000006f8 +#define NV10_TCL_PRIMITIVE_3D_POINT_PARAMETER_B 0x000006fc +#define NV10_TCL_PRIMITIVE_3D_POINT_PARAMETER_C 0x00000700 +#define NV10_TCL_PRIMITIVE_3D_POINT_PARAMETER_D 0x00000704 +#define NV10_TCL_PRIMITIVE_3D_POINT_PARAMETER_E 0x00000708 +#define NV10_TCL_PRIMITIVE_3D_POINT_PARAMETER_F 0x0000070c +#define NV10_TCL_PRIMITIVE_3D_POINT_PARAMETER_G 0x00000710 +#define NV10_TCL_PRIMITIVE_3D_POINT_PARAMETER_H 0x00000714 +#define NV10_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_AMBIENT_R(n) (0x00000800+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_AMBIENT_G(n) (0x00000804+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_AMBIENT_B(n) (0x00000808+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_DIFFUSE_R(n) (0x0000080c+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_DIFFUSE_G(n) (0x00000810+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_DIFFUSE_B(n) (0x00000814+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_SPECULAR_R(n) (0x00000818+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_SPECULAR_G(n) (0x0000081c+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_SPECULAR_B(n) (0x00000820+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_HALF_VECTOR_X(n) (0x00000828+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_HALF_VECTOR_Y(n) (0x0000082c+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_HALF_VECTOR_Z(n) (0x00000830+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_DIRECTION_X(n) (0x00000834+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_DIRECTION_Y(n) (0x00000838+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_DIRECTION_Z(n) (0x0000083c+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_SPOT_CUTOFF_A(n) (0x00000840+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_SPOT_EXPONENT(n) (0x00000844+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_SPOT_CUTOFF_B(n) (0x00000848+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_SPOT_DIR_X(n) (0x0000084c+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_SPOT_DIR_Y(n) (0x00000850+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_SPOT_DIR_Z(n) (0x00000854+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_SPOT_CUTOFF_C(n) (0x00000858+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_POSITION_X(n) (0x0000085c+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_POSITION_Y(n) (0x00000860+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_POSITION_Z(n) (0x00000864+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_CONSTANT_ATTENUATION(n) (0x00000868+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_LINEAR_ATTENUATION(n) (0x0000086c+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_LIGHT_QUADRATIC_ATTENUATION(n) (0x00000870+(n<<7)) +#define NV10_TCL_PRIMITIVE_3D_VERTEX_POS_3F_X 0x00000c00 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_POS_3F_Y 0x00000c04 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_POS_3F_Z 0x00000c08 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_POS_4F_X 0x00000c18 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_POS_4F_Y 0x00000c1c +#define NV10_TCL_PRIMITIVE_3D_VERTEX_POS_4F_Z 0x00000c20 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_POS_4F_W 0x00000c24 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_NOR_3F_X 0x00000c30 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_NOR_3F_Y 0x00000c34 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_NOR_3F_Z 0x00000c38 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_NOR_3I_XY 0x00000c40 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_NOR_3I_Z 0x00000c44 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_COL_4F_R 0x00000c50 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_COL_4F_G 0x00000c54 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_COL_4F_B 0x00000c58 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_COL_4F_A 0x00000c5c +#define NV10_TCL_PRIMITIVE_3D_VERTEX_COL_3F_R 0x00000c60 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_COL_3F_G 0x00000c64 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_COL_3F_B 0x00000c68 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_COL_4I 0x00000c6c +#define NV10_TCL_PRIMITIVE_3D_VERTEX_COL2_3F_R 0x00000c80 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_COL2_3F_G 0x00000c84 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_COL2_3F_B 0x00000c88 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_COL2_3I 0x00000c8c +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX0_2F_S 0x00000c90 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX0_2F_T 0x00000c94 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX0_2I 0x00000c98 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX0_4F_S 0x00000ca0 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX0_4F_T 0x00000ca4 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX0_4F_R 0x00000ca8 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX0_4F_Q 0x00000cac +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX0_4I_ST 0x00000cb0 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX0_4I_RQ 0x00000cb4 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX1_2F_S 0x00000cb8 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX1_2F_T 0x00000cbc +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX1_2I 0x00000cc0 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX1_4F_S 0x00000cc8 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX1_4F_T 0x00000ccc +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX1_4F_R 0x00000cd0 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX1_4F_Q 0x00000cd4 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX1_4I_ST 0x00000cd8 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_TX1_4I_RQ 0x00000cdc +#define NV10_TCL_PRIMITIVE_3D_VERTEX_FOG_1F 0x00000ce0 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_WGH_1F 0x00000ce4 +#define NV10_TCL_PRIMITIVE_3D_EDGEFLAG_ENABLE 0x00000cec +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_VALIDATE 0x00000cf0 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ATTR(i) (0x00000d04+(i)*0x08) +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ATTR__SIZE 8 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_OFFSET_POS 0x00000d00 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_FORMAT_POS 0x00000d04 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_OFFSET_COL 0x00000d08 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_FORMAT_COL 0x00000d0c +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_OFFSET_COL2 0x00000d10 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_FORMAT_COL2 0x00000d14 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_OFFSET_TX0 0x00000d18 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_FORMAT_TX0 0x00000d1c +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_OFFSET_TX1 0x00000d20 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_FORMAT_TX1 0x00000d24 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_OFFSET_NOR 0x00000d28 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_FORMAT_NOR 0x00000d2c +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_OFFSET_WGH 0x00000d30 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_FORMAT_WGH 0x00000d34 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_OFFSET_FOG 0x00000d38 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_FORMAT_FOG 0x00000d3c +#define NV10_TCL_PRIMITIVE_3D_COLOR_LOGIC_OP_ENABLE 0x00000d40 +#define NV10_TCL_PRIMITIVE_3D_COLOR_LOGIC_OP_OP 0x00000d44 +#define NV17_TCL_PRIMITIVE_3D_LMA_DEPTH_BUFFER_PITCH 0x00000d5c /* LMA_DEPTH is nv17 only */ +#define NV17_TCL_PRIMITIVE_3D_LMA_DEPTH_BUFFER_OFFSET 0x00000d60 +#define NV17_TCL_PRIMITIVE_3D_LMA_DEPTH_FILL_VALUE 0x00000d68 +#define NV17_TCL_PRIMITIVE_3D_LMA_DEPTH_CLEAR_ENABLE 0x00000d6c +// 0x00000d74 +// 0x00000d84 +#define NV10_TCL_PRIMITIVE_3D_BEGIN_END 0x00000dfc +#define NV10_TCL_PRIMITIVE_3D_INDEX_DATA 0x00000e00 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_BUFFER_BEGIN_END 0x000013fc +#define NV10_TCL_PRIMITIVE_3D_VERTEX_BUFFER_DRAW_ARRAYS 0x00001400 +#define NV10_TCL_PRIMITIVE_3D_VIEWPORT_ORIGIN_X 0x00001638 +#define NV10_TCL_PRIMITIVE_3D_VIEWPORT_ORIGIN_Y 0x0000163c +#define NV10_TCL_PRIMITIVE_3D_VIEWPORT_ORIGIN_Z 0x00001640 +#define NV10_TCL_PRIMITIVE_3D_VIEWPORT_ORIGIN_W 0x00001644 +#define NV17_TCL_PRIMITIVE_3D_LMA_DEPTH_ENABLE 0x00001658 +#define NV10_TCL_PRIMITIVE_3D_VERTEX_ARRAY_DATA 0x00001800 + + +#define NV10_IMAGE_FROM_CPU 0x0000008a +#define NV10_IMAGE_FROM_CPU_SET_DMA_NOTIFY 0x00000180 +#define NV10_IMAGE_FROM_CPU_SET_CONTEXT_CLIP_RECTANGLE 0x00000188 +#define NV10_IMAGE_FROM_CPU_SET_IMAGE_PATTERN 0x0000018c +#define NV10_IMAGE_FROM_CPU_SET_RASTER_OP 0x00000190 +#define NV10_IMAGE_FROM_CPU_SET_CONTEXT_SURFACES_2D 0x0000019c +#define NV10_IMAGE_FROM_CPU_OPERATION 0x000002fc +#define NV10_IMAGE_FROM_CPU_FORMAT 0x00000300 +#define NV10_IMAGE_FROM_CPU_POINT 0x00000304 +#define NV10_IMAGE_FROM_CPU_POINT_X 15:0 +#define NV10_IMAGE_FROM_CPU_POINT_Y 31:16 +#define NV10_IMAGE_FROM_CPU_SIZE_OUT 0x00000308 +#define NV10_IMAGE_FROM_CPU_SIZE_OUT_WIDTH 15:0 +#define NV10_IMAGE_FROM_CPU_SIZE_OUT_HEIGHT 31:16 +#define NV10_IMAGE_FROM_CPU_SIZE_IN 0x0000030c +#define NV10_IMAGE_FROM_CPU_SIZE_IN_WIDTH 15:0 +#define NV10_IMAGE_FROM_CPU_SIZE_IN_HEIGHT 31:16 +#define NV10_IMAGE_FROM_CPU_HLINE 0x00000400 + + +#define NV10_UNK0072 0x00000072 +#define NV10_UNK0072_COUNTER 0x00000050 +#define NV40_UNK0072_SET_OBJECT 0x00000060 +#define NV40_UNK0072_UNK0 0x00000064 +#define NV40_UNK0072_UNK1 0x0000006c +#define NV10_UNK0072_SET_DMA_NOTIFY 0x00000180 + + +#define NV10_PRIMITIVE_2D 0x0000007b +#define NV10_PRIMITIVE_2D_SET_DMA_NOTIFY 0x00000180 +#define NV10_PRIMITIVE_2D_SET_SURFACE 0x00000184 +#define NV10_PRIMITIVE_2D_SET_FORMAT 0x00000300 +#define NV10_PRIMITIVE_2D_SET_POINT 0x00000304 +#define NV10_PRIMITIVE_2D_SET_POINT_X 15:0 +#define NV10_PRIMITIVE_2D_SET_POINT_Y 31:16 +#define NV10_PRIMITIVE_2D_SET_SIZE 0x00000308 +#define NV10_PRIMITIVE_2D_SET_SIZE_WIDTH 15:0 +#define NV10_PRIMITIVE_2D_SET_SIZE_HEIGHT 31:16 +#define NV10_PRIMITIVE_2D_SET_CLIP_HORIZ 0x0000030c +#define NV10_PRIMITIVE_2D_SET_CLIP_HORIZ_WIDTH 31:16 +#define NV10_PRIMITIVE_2D_SET_CLIP_HORIZ_X 15:0 +#define NV10_PRIMITIVE_2D_SET_CLIP_VERT 0x00000310 +#define NV10_PRIMITIVE_2D_SET_CLIP_VERT_HEIGHT 31:16 +#define NV10_PRIMITIVE_2D_SET_CLIP_VERT_Y 15:0 +#define NV10_PRIMITIVE_2D_SET_DATA(i) (0x00000400 + (i)*4) +#define NV10_PRIMITIVE_2D_SET_DATA__SIZE 1792 + +#define NV01_CONTEXT_CLIP_RECTANGLE 0x00000019 +#define NV01_CONTEXT_CLIP_RECTANGLE_SET_POINT 0x00000300 +#define NV01_CONTEXT_CLIP_RECTANGLE_SET_POINT_X 15:0 +#define NV01_CONTEXT_CLIP_RECTANGLE_SET_POINT_Y 31:16 +#define NV01_CONTEXT_CLIP_RECTANGLE_SET_SIZE 0x00000304 +#define NV01_CONTEXT_CLIP_RECTANGLE_SET_SIZE_WIDTH 15:0 +#define NV01_CONTEXT_CLIP_RECTANGLE_SET_SIZE_HEIGHT 31:16 + +#define NV03_PRIMITIVE_RASTER_OP 0x00000043 +#define NV03_PRIMITIVE_RASTER_OP_NOTIFY 0x00000100 +#define NV03_PRIMITIVE_RASTER_OP_DMA_NOTIFY 0x00000180 +#define NV03_PRIMITIVE_RASTER_OP_LOGIC_OP 0x00000300 +#define NV03_PRIMITIVE_RASTER_OP_LOGIC_OP_CMD 7:4 + +#define NV04_CONTEXT_SURFACES_2D 0x00000042 +#define NV04_CONTEXT_SURFACES_2D_NOTIFY 0x00000104 +#define NV04_CONTEXT_SURFACES_2D_SET_DMA_NOTIFY 0x00000180 +#define NV04_CONTEXT_SURFACES_2D_SET_DMA_IMAGE_SRC 0x00000184 +#define NV04_CONTEXT_SURFACES_2D_SET_DMA_IMAGE_DST 0x00000188 +#define NV04_CONTEXT_SURFACES_2D_FORMAT 0x00000300 +#define NV04_CONTEXT_SURFACES_2D_FORMAT_COLOR 7:0 +#define NV04_CONTEXT_SURFACES_2D_PITCH 0x00000304 +#define NV04_CONTEXT_SURFACES_2D_PITCH_SRC 15:0 +#define NV04_CONTEXT_SURFACES_2D_PITCH_DST 31:16 +#define NV04_CONTEXT_SURFACES_2D_OFFSET_SRC 0x00000308 +#define NV04_CONTEXT_SURFACES_2D_OFFSET_DST 0x0000030c + +#define NV04_IMAGE_PATTERN 0x00000044 +#define NV04_IMAGE_PATTERN_COLOR_FORMAT 0x00000300 +#define NV04_IMAGE_PATTERN_MONO_FORMAT 0x00000304 +#define NV04_IMAGE_PATTERN_SELECT 0x0000030c +#define NV04_IMAGE_PATTERN_MONOCHROME_SHAPE 0x00000308 +#define NV04_IMAGE_PATTERN_MONOCHROME_COLOR0 0x00000310 +#define NV04_IMAGE_PATTERN_MONOCHROME_COLOR1 0x00000314 +#define NV04_IMAGE_PATTERN_MONOCHROME_PATTERN0 0x00000318 +#define NV04_IMAGE_PATTERN_MONOCHROME_PATTERN1 0x0000031c + +#define NV04_SWIZZLED_SURFACE 0x00000052 +#define NV04_SWIZZLED_SURFACE_DMA_NOTIFY 0x00000180 +#define NV04_SWIZZLED_SURFACE_DMA_IMAGE 0x00000184 +#define NV04_SWIZZLED_SURFACE_FORMAT 0x00000300 +#define NV04_SWIZZLED_SURFACE_FORMAT_HEIGHT 31:24 +#define NV04_SWIZZLED_SURFACE_FORMAT_WIDTH 23:16 +#define NV04_SWIZZLED_SURFACE_FORMAT_COLOR 15:0 +#define NV04_SWIZZLED_SURFACE_OFFSET 0x00000304 + +#define NV_IMAGE_BLIT 0x0000005f + +#define NV_IMAGE_BLIT_NOP 0x00000100 +#define NV_IMAGE_BLIT_NOTIFY 0x00000104 +#define NV_IMAGE_BLIT_DMA_NOTIFY 0x00000180 +#define NV_IMAGE_BLIT_COLOR_KEY 0x00000184 +#define NV_IMAGE_BLIT_CLIP_RECTANGLE 0x00000188 +#define NV_IMAGE_BLIT_PATTERN 0x0000018c +#define NV_IMAGE_BLIT_ROP5 0x00000190 +#define NV_IMAGE_BLIT_SURFACE 0x0000019c +#define NV_IMAGE_BLIT_OPERATION 0x000002FC +#define NV_IMAGE_BLIT_POINT_IN 0x00000300 +#define NV_IMAGE_BLIT_POINT_IN_X 15:0 +#define NV_IMAGE_BLIT_POINT_IN_Y 31:16 +#define NV_IMAGE_BLIT_POINT_OUT 0x00000304 +#define NV_IMAGE_BLIT_POINT_OUT_X 15:0 +#define NV_IMAGE_BLIT_POINT_OUT_Y 31:16 +#define NV_IMAGE_BLIT_SIZE 0x00000308 +#define NV_IMAGE_BLIT_SIZE_WIDTH 15:0 +#define NV_IMAGE_BLIT_SIZE_HEIGHT 31:16 + +#define NV10_CONTEXT_SURFACES_2D 0x00000062 +#define NV10_CONTEXT_SURFACES_2D_SET_DMA_NOTIFY 0x00000180 +#define NV10_CONTEXT_SURFACES_2D_SET_DMA_IN_MEMORY0 0x00000184 +#define NV10_CONTEXT_SURFACES_2D_SET_DMA_IN_MEMORY1 0x00000188 +#define NV10_CONTEXT_SURFACES_2D_FORMAT 0x00000300 +#define NV10_CONTEXT_SURFACES_2D_FORMAT_COLOR 7:0 +#define NV10_CONTEXT_SURFACES_2D_FORMAT_TYPE 15:7 +#define NV10_CONTEXT_SURFACES_2D_FORMAT_WIDTH 23:16 +#define NV10_CONTEXT_SURFACES_2D_FORMAT_HEIGHT 31:24 +#define NV10_CONTEXT_SURFACES_2D_PITCH 0x00000304 +#define NV10_CONTEXT_SURFACES_2D_PITCH_SRC 15:0 +#define NV10_CONTEXT_SURFACES_2D_PITCH_DST 31:16 +#define NV10_CONTEXT_SURFACES_2D_OFFSET_SRC 0x00000308 +#define NV10_CONTEXT_SURFACES_2D_OFFSET_DST 0x0000030c + +#define NV05_SCALED_IMAGE_FROM_MEMORY 0x00000063 + +#define NV05_SCALED_IMAGE_FROM_MEMORY_SURFACE 0x00000198 +#define NV05_SCALED_IMAGE_FROM_MEMORY_COLOR_CONVERSION 0x000002fc +#define NV05_SCALED_IMAGE_FROM_MEMORY_OPERATION 0x00000304 + +#define NV05_SCALED_IMAGE_FROM_MEMORY_CLIP_POS 0x00000308 +#define NV05_SCALED_IMAGE_FROM_MEMORY_CLIP_SIZE 0x0000030C +#define NV05_SCALED_IMAGE_FROM_MEMORY_OUT_POS 0x00000310 +#define NV05_SCALED_IMAGE_FROM_MEMORY_OUT_SIZE 0x00000314 +#define NV05_SCALED_IMAGE_FROM_MEMORY_DU_DX 0x00000318 +#define NV05_SCALED_IMAGE_FROM_MEMORY_DV_DY 0x0000031C +#define NV05_SCALED_IMAGE_FROM_MEMORY_SIZE 0x00000400 +#define NV05_SCALED_IMAGE_FROM_MEMORY_FORMAT 0x00000404 +#define NV05_SCALED_IMAGE_FROM_MEMORY_OFFSET 0x00000408 +#define NV05_SCALED_IMAGE_FROM_MEMORY_POINT 0x0000040C + +#define NV04_SCALED_IMAGE_FROM_MEMORY 0x00000077 +#define NV04_SCALED_IMAGE_FROM_MEMORY_DMA_NOTIFY 0x00000180 +#define NV04_SCALED_IMAGE_FROM_MEMORY_DMA_IMAGE 0x00000184 +#define NV04_SCALED_IMAGE_FROM_MEMORY_SURFACE 0x00000198 + +#define NV04_SCALED_IMAGE_FROM_MEMORY_COLOR_FORMAT 0x00000300 +#define NV04_SCALED_IMAGE_FROM_MEMORY_OPERATION 0x00000304 +#define NV04_SCALED_IMAGE_FROM_MEMORY_CLIP_POS 0x00000308 +#define NV04_SCALED_IMAGE_FROM_MEMORY_CLIP_SIZE 0x0000030C +#define NV04_SCALED_IMAGE_FROM_MEMORY_OUT_POS 0x00000310 +#define NV04_SCALED_IMAGE_FROM_MEMORY_OUT_SIZE 0x00000314 +#define NV04_SCALED_IMAGE_FROM_MEMORY_DU_DX 0x00000318 +#define NV04_SCALED_IMAGE_FROM_MEMORY_DV_DY 0x0000031C +#define NV04_SCALED_IMAGE_FROM_MEMORY_SIZE 0x00000400 +#define NV04_SCALED_IMAGE_FROM_MEMORY_FORMAT 0x00000404 +#define NV04_SCALED_IMAGE_FROM_MEMORY_OFFSET 0x00000408 +#define NV04_SCALED_IMAGE_FROM_MEMORY_POINT 0x0000040C + + +#define NV10_VIDEO_DISPLAY 0x0000007c +#define NV10_VIDEO_DISPLAY_COUNTER 0x00000050 +#define NV10_VIDEO_DISPLAY_SET_DMA_FROM_MEMORY 0x00000180 +#define NV10_VIDEO_DISPLAY_SET_DMA_IN_MEMORY0 0x00000184 +#define NV10_VIDEO_DISPLAY_SET_DMA_IN_MEMORY1 0x00000188 +#define NV10_VIDEO_DISPLAY_SET_OBJECT3 0x0000019c +#define NV10_VIDEO_DISPLAY_UNK0250 0x00000250 +#define NV10_VIDEO_DISPLAY_SIZE 0x000002f8 +#define NV10_VIDEO_DISPLAY_OFFSET 0x00000300 +#define NV10_VIDEO_DISPLAY_UNK0304 0x00000304 + + +#define NV10_SCALED_IMAGE_FROM_MEMORY 0x00000089 +#define NV10_SCALED_IMAGE_FROM_MEMORY_COUNTER 0x00000050 +#define NV10_SCALED_IMAGE_FROM_MEMORY_SET_DMA_IN_MEMORY 0x00000184 +#define NV10_SCALED_IMAGE_FROM_MEMORY_SET_IMAGE_PATTERN 0x00000188 +#define NV10_SCALED_IMAGE_FROM_MEMORY_SET_RASTER_OP 0x0000018c +#define NV10_SCALED_IMAGE_FROM_MEMORY_SET_SURFACE 0x00000198 /* context_surfaces_2d or swizzled_surface */ +#define NV10_SCALED_IMAGE_FROM_MEMORY_UNK02fc 0x000002fc +#define NV10_SCALED_IMAGE_FROM_MEMORY_UNK0300 0x00000300 +#define NV10_SCALED_IMAGE_FROM_MEMORY_OPERATION 0x00000304 +#define NV10_SCALED_IMAGE_FROM_MEMORY_CLIP_POS 0x00000308 +#define NV10_SCALED_IMAGE_FROM_MEMORY_CLIP_SIZE 0x0000030C +#define NV10_SCALED_IMAGE_FROM_MEMORY_OUT_POS 0x00000310 +#define NV10_SCALED_IMAGE_FROM_MEMORY_OUT_SIZE 0x00000314 +#define NV10_SCALED_IMAGE_FROM_MEMORY_SIZE 0x00000400 +#define NV10_SCALED_IMAGE_FROM_MEMORY_FORMAT 0x00000404 +#define NV10_SCALED_IMAGE_FROM_MEMORY_OFFSET 0x00000408 +#define NV10_SCALED_IMAGE_FROM_MEMORY_POINT 0x0000040C + + +#define NV10_IMAGE_BLIT 0x0000009f +#define NV10_IMAGE_BLIT_NOP 0x00000100 +#define NV10_IMAGE_BLIT_NOTIFY 0x00000104 +// 0x00000120 /* quadro, set to 0,1,2 */ +// 0x00000124 +// 0x00000128 +#define NV10_IMAGE_BLIT_SET_DMA_NOTIFY 0x00000180 +#define NV10_IMAGE_BLIT_SET_CONTEXT_CLIP_RECTANGLE 0x00000188 +#define NV10_IMAGE_BLIT_SET_IMAGE_PATTERN 0x0000018c +#define NV10_IMAGE_BLIT_SET_RASTER_OP 0x00000190 +#define NV10_IMAGE_BLIT_SET_CONTEXT_SURFACES_2D 0x0000019c +#define NV10_IMAGE_BLIT_SET_OPERATION 0x000002fc +#define NV10_IMAGE_BLIT_SET_POINT 0x00000300 +#define NV10_IMAGE_BLIT_SET_POINT_X 15:0 +#define NV10_IMAGE_BLIT_SET_POINT_Y 31:16 +#define NV10_IMAGE_BLIT_SET_PITCH 0x00000304 +#define NV10_IMAGE_BLIT_SET_PITCH_NEXT_LINE 31:16 +#define NV10_IMAGE_BLIT_SET_SIZE 0x00000308 +#define NV10_IMAGE_BLIT_SET_SIZE_WIDTH 15:0 +#define NV10_IMAGE_BLIT_SET_SIZE_HEIGHT 31:16 + + +/* +Unknown NV20 commands: + +NV20_TCL_PRIMITIVE_3D [0x1d78/4] = 0x00000001 | UNKNOWN = 00000001 + Appears always just after NV20_TCL_PRIMITIVE_3D_POLYGON_OFFSET_FACTOR and + _UNITS, and nowhere else. The parameter is always 0x1. + FACTOR and UNITS are always followed by 0x1d78 in dumps nv20 nv25 nv25gl nv28pq, + but there are exceptions in dumps nv28 and nv28sgl offset tests. +*/ + +#define NV20_SWIZZLED_SURFACE 0x0000009e +#define NV20_SWIZZLED_SURFACE_SET_OBJECT0 0x00000180 +#define NV20_SWIZZLED_SURFACE_SET_OBJECT1 0x00000184 +#define NV20_SWIZZLED_SURFACE_FORMAT 0x00000300 +#define NV20_SWIZZLED_SURFACE_FORMAT_HEIGHT 31:24 +#define NV20_SWIZZLED_SURFACE_FORMAT_WIDTH 23:16 +#define NV20_SWIZZLED_SURFACE_FORMAT_COLOR 15:0 +#define NV20_SWIZZLED_SURFACE_OFFSET 0x00000304 + +#define NV20_TCL_PRIMITIVE_SET_MAIN_OBJECT 0x00000000 + +#define NV20_TCL_PRIMITIVE_3D 0x00000097 + +#define NV20_TCL_PRIMITIVE_3D_NOP 0x00000100 //data=0 +#define NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT 0x00000100 //data=interrupt routine ID +#define NV20_TCL_PRIMITIVE_3D_NOTIFY 0x00000104 +#define NV20_TCL_PRIMITIVE_3D_WAIT_MAKESPACE 0x00000110 +#define NV20_TCL_PRIMITIVE_3D_MAIN_TILES_INDICES 0x00000120 +#define NV20_TCL_PRIMITIVE_3D_ASK_FOR_IDLE 0x0000012C +#define NV20_TCL_PRIMITIVE_3D_STALL_PIPELINE 0x00000130 +#define NV20_TCL_PRIMITIVE_3D_SET_OBJECT0 0x00000180 +#define NV20_TCL_PRIMITIVE_3D_SET_OBJECT1 0x00000184 +#define NV20_TCL_PRIMITIVE_3D_SET_OBJECT2 0x00000188 +#define NV20_TCL_PRIMITIVE_3D_SET_OBJECT2A 0x00000190 +#define NV20_TCL_PRIMITIVE_3D_SET_OBJECT3 0x00000194 +#define NV20_TCL_PRIMITIVE_3D_SET_OBJECT4 0x00000198 +#define NV20_TCL_PRIMITIVE_3D_SET_OBJECT5 0x0000019c +#define NV20_TCL_PRIMITIVE_3D_SET_OBJECT6 0x000001a0 +#define NV20_TCL_PRIMITIVE_3D_SET_OBJECT7 0x000001a4 +#define NV20_TCL_PRIMITIVE_3D_SET_OBJECT8 0x000001a8 +#define NV20_TCL_PRIMITIVE_3D_SET_OBJECT9 0x000001ac +#define NV20_TCL_PRIMITIVE_3D_SET_OBJECT10 0x000001b0 +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_HORIZ 0x00000200 +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_VERT 0x00000204 +#define NV20_TCL_PRIMITIVE_3D_BUFFER_FORMAT 0x00000208 +#define NV20_TCL_PRIMITIVE_3D_BUFFER_PITCH 0x0000020c +#define NV20_TCL_PRIMITIVE_3D_COLOR_OFFSET 0x00000210 +#define NV20_TCL_PRIMITIVE_3D_DEPTH_OFFSET 0x00000214 +#define NV20_TCL_PRIMITIVE_3D_LMA_DEPTH_BUFFER_PITCH 0x0000022c +#define NV20_TCL_PRIMITIVE_3D_LMA_DEPTH_BUFFER_OFFSET 0x00000230 +#define NV20_TCL_PRIMITIVE_3D_W_YUV_FPZ_FLAGS 0x00000290 +#define NV20_TCL_PRIMITIVE_3D_LIGHT_CONTROL 0x00000294 +#define NV20_TCL_PRIMITIVE_3D_COLOR_MATERIAL_CONTROL 0x00000298 +#define NV20_TCL_PRIMITIVE_3D_FOG_MODE 0x0000029c +#define NV20_TCL_PRIMITIVE_3D_FOG_COORD_DIST 0x000002a0 +#define NV20_TCL_PRIMITIVE_3D_FOG_ENABLE 0x000002a4 +#define NV20_TCL_PRIMITIVE_3D_FOG_COLOR 0x000002a8 +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_CLIP_MODE 0x000002b4 //0/1=accept/reject pixels inside scissors union +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_CLIP_HORIZ(n) (0x000002c0+(n<<2)) +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_CLIP_VERT(n) (0x000002e0+(n<<2)) +#define NV20_TCL_PRIMITIVE_3D_SET_OBJECT_UNKNOWN 0x000002fc +#define NV20_TCL_PRIMITIVE_3D_ALPHA_FUNC_ENABLE 0x00000300 +#define NV20_TCL_PRIMITIVE_3D_BLEND_FUNC_ENABLE 0x00000304 +#define NV20_TCL_PRIMITIVE_3D_CULL_FACE_ENABLE 0x00000308 +#define NV20_TCL_PRIMITIVE_3D_DEPTH_TEST_ENABLE 0x0000030c +#define NV20_TCL_PRIMITIVE_3D_DITHER_ENABLE 0x00000310 +#define NV20_TCL_PRIMITIVE_3D_LIGHTING_ENABLE 0x00000314 +#define NV20_TCL_PRIMITIVE_3D_POINT_PARAMETERS_ENABLE 0x00000318 +#define NV20_TCL_PRIMITIVE_3D_POINT_SMOOTH_ENABLE 0x0000031c +#define NV20_TCL_PRIMITIVE_3D_LINE_SMOOTH_ENABLE 0x00000320 +#define NV20_TCL_PRIMITIVE_3D_POLYGON_SMOOTH_ENABLE 0x00000324 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_BLEND_ENABLE 0x00000328 +#define NV20_TCL_PRIMITIVE_3D_STENCIL_TEST_ENABLE 0x0000032c +#define NV20_TCL_PRIMITIVE_3D_POLYGON_OFFSET_POINT_ENABLE 0x00000330 +#define NV20_TCL_PRIMITIVE_3D_POLYGON_OFFSET_LINE_ENABLE 0x00000334 +#define NV20_TCL_PRIMITIVE_3D_POLYGON_OFFSET_FILL_ENABLE 0x00000338 +#define NV20_TCL_PRIMITIVE_3D_ALPHA_FUNC_FUNC 0x0000033c +#define NV20_TCL_PRIMITIVE_3D_ALPHA_FUNC_REF 0x00000340 +#define NV20_TCL_PRIMITIVE_3D_BLEND_FUNC_SRC 0x00000344 +#define NV20_TCL_PRIMITIVE_3D_BLEND_FUNC_DST 0x00000348 +#define NV20_TCL_PRIMITIVE_3D_BLEND_COLOR 0x0000034c +#define NV20_TCL_PRIMITIVE_3D_BLEND_EQUATION 0x00000350 +#define NV20_TCL_PRIMITIVE_3D_DEPTH_FUNC 0x00000354 +#define NV20_TCL_PRIMITIVE_3D_COLOR_MASK 0x00000358 +#define NV20_TCL_PRIMITIVE_3D_DEPTH_WRITE_ENABLE 0x0000035c +#define NV20_TCL_PRIMITIVE_3D_STENCIL_MASK 0x00000360 +#define NV20_TCL_PRIMITIVE_3D_STENCIL_FUNC_FUNC 0x00000364 +#define NV20_TCL_PRIMITIVE_3D_STENCIL_FUNC_REF 0x00000368 +#define NV20_TCL_PRIMITIVE_3D_STENCIL_FUNC_MASK 0x0000036c +#define NV20_TCL_PRIMITIVE_3D_STENCIL_OP_FAIL 0x00000370 +#define NV20_TCL_PRIMITIVE_3D_STENCIL_OP_ZFAIL 0x00000374 +#define NV20_TCL_PRIMITIVE_3D_STENCIL_OP_ZPASS 0x00000378 +#define NV20_TCL_PRIMITIVE_3D_SHADE_MODEL 0x0000037c +#define NV20_TCL_PRIMITIVE_3D_LINE_WIDTH 0x00000380 +#define NV20_TCL_PRIMITIVE_3D_POLYGON_OFFSET_FACTOR 0x00000384 +#define NV20_TCL_PRIMITIVE_3D_POLYGON_OFFSET_UNITS 0x00000388 +#define NV20_TCL_PRIMITIVE_3D_POLYGON_MODE_FRONT 0x0000038c +#define NV20_TCL_PRIMITIVE_3D_POLYGON_MODE_BACK 0x00000390 +#define NV20_TCL_PRIMITIVE_3D_DEPTH_RANGE_NEAR 0x00000394 +#define NV20_TCL_PRIMITIVE_3D_DEPTH_RANGE_FAR 0x00000398 +#define NV20_TCL_PRIMITIVE_3D_CULL_FACE 0x0000039c +#define NV20_TCL_PRIMITIVE_3D_FRONT_FACE 0x000003a0 +#define NV20_TCL_PRIMITIVE_3D_NORMALIZE_ENABLE 0x000003a4 +#define NV20_TCL_PRIMITIVE_3D_COLOR_MATERIAL_FRONT_R 0x000003a8 +#define NV20_TCL_PRIMITIVE_3D_COLOR_MATERIAL_FRONT_G 0x000003ac +#define NV20_TCL_PRIMITIVE_3D_COLOR_MATERIAL_FRONT_B 0x000003b0 +#define NV20_TCL_PRIMITIVE_3D_COLOR_MATERIAL_FRONT_A 0x000003b4 +#define NV20_TCL_PRIMITIVE_3D_SEPARATE_SPECULAR_ENABLE 0x000003b8 +#define NV20_TCL_PRIMITIVE_3D_ENABLED_LIGHTS 0x000003bc +#define NV20_TCL_PRIMITIVE_3D_CLIP_PLANE_ENABLE(n) (0x000003c0+(n<<2)) +#define NV20_TCL_PRIMITIVE_3D_TX_MATRIX_ENABLE(n) (0x00000420+(n<<2)) +#define NV20_TCL_PRIMITIVE_3D_POINT_SIZE 0x0000043c +#define NV20_TCL_PRIMITIVE_3D_MODELVIEW_MATRIX 0x00000480 +#define NV20_TCL_PRIMITIVE_3D_INVERSE_MODELVIEW_MATRIX 0x00000580 +#define NV20_TCL_PRIMITIVE_3D_PROJECTION_MATRIX 0x00000680 +#define NV20_TCL_PRIMITIVE_3D_TX_MATRIX(n) (0x000006c0+(n<<6)) +#define NV20_TCL_PRIMITIVE_3D_CLIP_PLANE_A(n) (0x00000840+(n<<4)) +#define NV20_TCL_PRIMITIVE_3D_CLIP_PLANE_B(n) (0x00000844+(n<<4)) +#define NV20_TCL_PRIMITIVE_3D_CLIP_PLANE_C(n) (0x00000848+(n<<4)) +#define NV20_TCL_PRIMITIVE_3D_CLIP_PLANE_D(n) (0x0000084c+(n<<4)) +#define NV20_TCL_PRIMITIVE_3D_FOG_EQUATION_CONSTANT 0x000009c0 +#define NV20_TCL_PRIMITIVE_3D_FOG_EQUATION_LINEAR 0x000009c4 +#define NV20_TCL_PRIMITIVE_3D_FOG_EQUATION_QUADRATIC 0x000009c8 +#define NV20_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_A 0x000009e0 +#define NV20_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_B 0x000009e4 +#define NV20_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_C 0x000009e8 +#define NV20_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_D 0x000009ec +#define NV20_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_E 0x000009f0 +#define NV20_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_F 0x000009f4 +#define NV20_TCL_PRIMITIVE_3D_SWATHWIDTH 0x000009f8 + +#define NV20_TCL_PRIMITIVE_3D_POINT_SPRITE 0x00000a1c + +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_OX 0x00000a20 /* x offset */ +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_OY 0x00000a24 /* y offset */ +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_DEPTH_AVG_S 0x00000a28 /* (depth range near + far)/2 * 16777214 */ +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_UNKNOWN_A 0x00000a2c /* 0.0 if DEPTH_AVG_S == 0.0, otherwise 16777215.0 */ +/* see tests draw_pixels, line_stipple and logic_op for where DEPTH_AVG_S=0.0 */ + +#define NV20_TCL_PRIMITIVE_3D_POINT_PARAMETER_A 0x00000a30 +#define NV20_TCL_PRIMITIVE_3D_POINT_PARAMETER_B 0x00000a34 +#define NV20_TCL_PRIMITIVE_3D_POINT_PARAMETER_C 0x00000a38 +#define NV20_TCL_PRIMITIVE_3D_POINT_PARAMETER_D 0x00000a3c +#define NV20_TCL_PRIMITIVE_3D_POINT_PARAMETER_E 0x00000a40 +#define NV20_TCL_PRIMITIVE_3D_POINT_PARAMETER_F 0x00000a44 +#define NV20_TCL_PRIMITIVE_3D_POINT_PARAMETER_G 0x00000a48 +#define NV20_TCL_PRIMITIVE_3D_POINT_PARAMETER_H 0x00000a4c + +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_PX_DIV2 0x00000af0 /* width/2 */ +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_PY_DIV2 0x00000af4 /* -height/2 */ +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_DEPTH_HALF_S 0x00000af8 /* (depth range far - near)/2 * 16777214 */ +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_UNKNOWN_B 0x00000afc /* always 65535.0 */ + +#define NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST0 0x00000b00 +#define NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST1 0x00000b04 +#define NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST2 0x00000b08 +#define NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST3 0x00000b0c +#define NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_X 0x00000b80 +#define NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_Y 0x00000b84 +#define NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_Z 0x00000b88 +#define NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_W 0x00000b8c + +#define NV20_TCL_PRIMITIVE_3D_LIGHT_MODEL_FRONT_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_R 0x00000a10 +#define NV20_TCL_PRIMITIVE_3D_LIGHT_MODEL_FRONT_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_G 0x00000a14 +#define NV20_TCL_PRIMITIVE_3D_LIGHT_MODEL_FRONT_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_B 0x00000a18 + +#define NV20_TCL_PRIMITIVE_3D_TX_OFFSET(n) (0x00001b00+(n<<6)) +#define NV20_TCL_PRIMITIVE_3D_TX_FORMAT(n) (0x00001b04+(n<<6)) +#define NV20_TCL_PRIMITIVE_3D_TX_WRAP(n) (0x00001b08+(n<<6)) +#define NV20_TCL_PRIMITIVE_3D_TX_ENABLE(n) (0x00001b0c+(n<<6)) +#define NV20_TCL_PRIMITIVE_3D_TX_NPOT_PITCH(n) (0x00001b10+(n<<6)) +#define NV20_TCL_PRIMITIVE_3D_TX_FILTER(n) (0x00001b14+(n<<6)) +/*#define NV20_TCL_PRIMITIVE_3D_TX_UNK_B(n) (0x00001b18+(n<<6))*/ +#define NV20_TCL_PRIMITIVE_3D_TX_NPOT_SIZE(n) (0x00001b1c+(n<<6)) +#define NV20_TCL_PRIMITIVE_3D_TX_PALETTE_OFFSET(n) (0x00001b20+(n<<6)) + +// 0x00001d78 +// 0x00001d7c +// 0x00001d84 +#define NV20_TCL_PRIMITIVE_3D_RC_ENABLE 0x00001e60 + +#define NV20_TCL_PRIMITIVE_3D_TX_SHADER_OP 0x000001e70 +#define NV20_TCL_PRIMITIVE_3D_TX_SHADER_CULL_MODE 0x0000017f8 +#define NV20_TCL_PRIMITIVE_3D_TX_SHADER_PREVIOUS 0x000001e78 + +#define NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_ID 0x00001ea4 + +#define NV20_TCL_PRIMITIVE_3D_RC_IN_ALPHA(n) (0x00000260+(n<<2)) /* input combiners, portion alpha */ +#define NV20_TCL_PRIMITIVE_3D_RC_IN_RGB(n) (0x00000ac0+(n<<2)) /* input combiners, portion rgb */ +#define NV20_TCL_PRIMITIVE_3D_RC_CONSTANT_COLOR0(n) (0x00000a60+(n<<2)) /* constant color 0 */ +#define NV20_TCL_PRIMITIVE_3D_RC_CONSTANT_COLOR1(n) (0x00000a80+(n<<2)) /* constant color 1 */ +#define NV20_TCL_PRIMITIVE_3D_RC_OUT_ALPHA(n) (0x00000aa0+(n<<2)) /* output combiners, portion alpha */ +#define NV20_TCL_PRIMITIVE_3D_RC_OUT_RGB(n) (0x00001e40+(n<<2)) /* output combiners, portion rgb */ +#define NV20_TCL_PRIMITIVE_3D_RC_COLOR0 0x00001e20 /* combiners, constant colors */ +#define NV20_TCL_PRIMITIVE_3D_RC_COLOR1 0x00001e24 +#define NV20_TCL_PRIMITIVE_3D_RC_FINAL0 0x00000288 /* final combiner, variables A-D */ +#define NV20_TCL_PRIMITIVE_3D_RC_FINAL1 0x0000028c /* final combiner, variables E-G */ + +#define NV20_TCL_PRIMITIVE_3D_LIGHT_POSITION_X(n) (0x0000105c+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_POSITION_Y(n) (0x00001060+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_POSITION_Z(n) (0x00001064+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_HALF_VECTOR_X(n) (0x00001028+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_HALF_VECTOR_Y(n) (0x0000102c+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_HALF_VECTOR_Z(n) (0x00001030+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_DIRECTION_X(n) (0x00001034+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_DIRECTION_Y(n) (0x00001038+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_DIRECTION_Z(n) (0x0000103c+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_AMBIENT_R(n) (0x00001000+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_AMBIENT_G(n) (0x00001004+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_AMBIENT_B(n) (0x00001008+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_DIFFUSE_R(n) (0x0000100c+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_DIFFUSE_G(n) (0x00001010+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_DIFFUSE_B(n) (0x00001014+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_SPECULAR_R(n) (0x00001018+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_SPECULAR_G(n) (0x0000101c+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_SPECULAR_B(n) (0x00001020+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_BACK_SIDE_PRODUCT_AMBIENT(n) (0x00000c00+(n<<6)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_BACK_SIDE_PRODUCT_DIFFUSE(n) (0x00000c0c+(n<<6)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_BACK_SIDE_PRODUCT_SPECULAR(n) (0x00000c18+(n<<6)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_CONSTANT_ATTENUATION(n) (0x00001068+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_LINEAR_ATTENUATION(n) (0x0000106c+(n<<7)) +#define NV20_TCL_PRIMITIVE_3D_LIGHT_QUADRATIC_ATTENUATION(n) (0x00001070+(n<<7)) + +/* These commands seem right on NV28, calculations by pq. Note: d = sqrt(dirX^2 + dirY^2 + dirZ^2) */ +#define NV20_TCL_PRIMITIVE_3D_LIGHT_SPOT_CUTOFF_A(n) (0x00001040+(n<<7)) /* unknown */ +#define NV20_TCL_PRIMITIVE_3D_LIGHT_SPOT_EXPONENT(n) (0x00001044+(n<<7)) /* unknown */ +#define NV20_TCL_PRIMITIVE_3D_LIGHT_SPOT_CUTOFF_B(n) (0x00001048+(n<<7)) /* unknown */ +#define NV20_TCL_PRIMITIVE_3D_LIGHT_SPOT_DIR_X(n) (0x0000104c+(n<<7)) /* 1/( cos(cutoff)-1 ) * dirX/d */ +#define NV20_TCL_PRIMITIVE_3D_LIGHT_SPOT_DIR_Y(n) (0x00001050+(n<<7)) /* 1/( cos(cutoff)-1 ) * dirY/d */ +#define NV20_TCL_PRIMITIVE_3D_LIGHT_SPOT_DIR_Z(n) (0x00001054+(n<<7)) /* 1/( cos(cutoff)-1 ) * dirZ/d */ +#define NV20_TCL_PRIMITIVE_3D_LIGHT_SPOT_CUTOFF_C(n) (0x00001058+(n<<7)) /* 1 + 1/( cos(cutoff)-1 ) */ + +#define NV20_TCL_PRIMITIVE_3D_BACK_MATERIAL_SHININESS_A 0x00001e28 +#define NV20_TCL_PRIMITIVE_3D_BACK_MATERIAL_SHININESS_B 0x00001e2c +#define NV20_TCL_PRIMITIVE_3D_BACK_MATERIAL_SHININESS_C 0x00001e30 +#define NV20_TCL_PRIMITIVE_3D_BACK_MATERIAL_SHININESS_D 0x00001e34 +#define NV20_TCL_PRIMITIVE_3D_BACK_MATERIAL_SHININESS_E 0x00001e38 +#define NV20_TCL_PRIMITIVE_3D_BACK_MATERIAL_SHININESS_F 0x00001e3c + +#define NV20_TCL_PRIMITIVE_3D_POLYGON_STIPPLE_ENABLE 0x0000147c +#define NV20_TCL_PRIMITIVE_3D_POLYGON_STIPPLE_PATTERN(n) (0x00001480+(n<<2)) +#define NV20_TCL_PRIMITIVE_3D_POLYGON_STIPPLE_PATTERN__SIZE 32 + +#define NV20_TCL_PRIMITIVE_3D_VERTEX_POS_3F_X 0x00001500 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_POS_3F_Y 0x00001504 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_POS_3F_Z 0x00001508 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_POS_4F_X 0x00001518 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_POS_4F_Y 0x0000151c +#define NV20_TCL_PRIMITIVE_3D_VERTEX_POS_4F_Z 0x00001520 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_POS_4F_W 0x00001524 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_POS_4I_XY 0x00001528 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_POS_4I_ZW 0x0000152c +#define NV20_TCL_PRIMITIVE_3D_VERTEX_NOR_3F_X 0x00001530 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_NOR_3F_Y 0x00001534 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_NOR_3F_Z 0x00001538 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_NOR_3I_XY 0x00001540 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_NOR_3I_Z 0x00001544 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_COL_4F_R 0x00001550 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_COL_4F_G 0x00001554 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_COL_4F_B 0x00001558 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_COL_4F_A 0x0000155c +#define NV20_TCL_PRIMITIVE_3D_VERTEX_COL_3F_R 0x00001560 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_COL_3F_G 0x00001564 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_COL_3F_B 0x00001568 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_COL_4I 0x0000156c +#define NV20_TCL_PRIMITIVE_3D_VERTEX_COL2_3F_R 0x00001580 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_COL2_3F_G 0x00001584 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_COL2_3F_B 0x00001588 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_COL2_3I 0x0000158c +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX0_2F_S 0x00001590 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX0_2F_T 0x00001594 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX0_2I 0x00001598 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX0_4F_S 0x000015a0 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX0_4F_T 0x000015a4 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX0_4F_R 0x000015a8 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX0_4F_Q 0x000015ac +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX0_4I_ST 0x000015b0 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX0_4I_RQ 0x000015b4 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX1_2F_S 0x000015b8 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX1_2F_T 0x000015bc +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX1_2I 0x000015c0 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX1_4F_S 0x000015c8 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX1_4F_T 0x000015cc +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX1_4F_R 0x000015d0 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX1_4F_Q 0x000015d4 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX1_4I_ST 0x000015d8 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX1_4I_RQ 0x000015dc +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX2_2F_S 0x000015e0 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX2_2F_T 0x000015e4 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX2_2I 0x000015e8 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX2_4F_S 0x000015f0 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX2_4F_T 0x000015f4 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX2_4F_R 0x000015f8 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX2_4F_Q 0x000015fc +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX2_4I_ST 0x00001600 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX2_4I_RQ 0x00001604 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX3_2F_S 0x00001608 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX3_2F_T 0x0000160c +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX3_2I 0x00001610 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX3_4F_S 0x00001620 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX3_4F_T 0x00001624 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX3_4F_R 0x00001628 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX3_4F_Q 0x0000162c +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX3_4I_ST 0x00001630 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_TX3_4I_RQ 0x00001634 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_FOG_1F 0x00001698 +#define NV20_TCL_PRIMITIVE_3D_EDGE_FLAG 0x000016bc + +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR0_POS 0x00001720 +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR1_WGH 0x00001724 +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR2_NOR 0x00001728 +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR3_COL 0x0000172c +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR4_COL2 0x00001730 +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR5_FOG 0x00001734 +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR6 0x00001738 +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR7 0x0000173c +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR8_TX0 0x00001740 +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR9_TX1 0x00001744 +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR10_TX2 0x00001748 +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR11_TX3 0x0000174c +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR12_TX4 0x00001750 +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR13_TX5 0x00001754 +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR14_TX6 0x00001758 +#define NV20_TCL_PRIMITIVE_3D_VB_POINTER_ATTR15_TX7 0x0000175c +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR(i) (0x00001760 + (i * 0x04)) +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR__SIZE 16 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR0_POS 0x00001760 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR1_WGH 0x00001764 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR2_NOR 0x00001768 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR3_COL 0x0000176c +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR4_COL2 0x00001770 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR5_FOG 0x00001774 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR6 0x00001778 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR7 0x0000177c +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR8_TX0 0x00001780 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR9_TX1 0x00001784 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR10_TX2 0x00001788 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR11_TX3 0x0000178c +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR12_TX4 0x00001790 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR13_TX5 0x00001794 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR14_TX6 0x00001798 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_ATTR15_TX7 0x0000179c + +#define NV20_TCL_PRIMITIVE_3D_LIGHT_MODEL_BACK_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_R 0x000017a0 +#define NV20_TCL_PRIMITIVE_3D_LIGHT_MODEL_BACK_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_G 0x000017a4 +#define NV20_TCL_PRIMITIVE_3D_LIGHT_MODEL_BACK_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_B 0x000017a8 +#define NV20_TCL_PRIMITIVE_3D_COLOR_MATERIAL_BACK_A 0x000017ac +#define NV20_TCL_PRIMITIVE_3D_COLOR_MATERIAL_BACK_R 0x000017b0 +#define NV20_TCL_PRIMITIVE_3D_COLOR_MATERIAL_BACK_G 0x000017b4 +#define NV20_TCL_PRIMITIVE_3D_COLOR_MATERIAL_BACK_B 0x000017b8 +#define NV20_TCL_PRIMITIVE_3D_COLOR_LOGIC_OP_ENABLE 0x000017bc +#define NV20_TCL_PRIMITIVE_3D_COLOR_LOGIC_OP_OP 0x000017c0 +#define NV20_TCL_PRIMITIVE_3D_LIGHT_MODEL_TWO_SIDE_ENABLE 0x000017c4 +// 0x000017cc +#define NV20_TCL_PRIMITIVE_3D_BEGIN_END 0x000017fc + +#define NV20_TCL_PRIMITIVE_3D_TX_DEPTH_UNIT(n) (0x00001840 + (n*4)) +#define NV20_TCL_PRIMITIVE_3D_TX_ADDRESS_UNIT(n) (0x00001A00 + (n * 32)) +#define NV20_TCL_PRIMITIVE_3D_TX_FORMAT_UNIT(n) (0x00001A04 + (n * 32)) +#define NV20_TCL_PRIMITIVE_3D_TX_FORMAT_MIPMAP_COUNT 23:20 +#define NV20_TCL_PRIMITIVE_3D_TX_FORMAT_TYPE 14:13 +#define NV20_TCL_PRIMITIVE_3D_TX_FORMAT_FORMAT 12:8 +#define NV20_TCL_PRIMITIVE_3D_TX_FORMAT_NCOMP 7:4 /* 2=2D, 3=3D, high bit may be wrong */ +#define NV20_TCL_PRIMITIVE_3D_TX_FORMAT_CUBIC 2:2 +#define NV20_TCL_PRIMITIVE_3D_TX_WRAP_UNIT(n) (0x00001A08 + (n * 32)) +#define NV20_TCL_PRIMITIVE_3D_TX_WRAP_S 7:0 +#define NV20_TCL_PRIMITIVE_3D_TX_WRAP_T 15:8 +#define NV20_TCL_PRIMITIVE_3D_TX_WRAP_R 23:16 +#define NV20_TCL_PRIMITIVE_3D_TX_UNK03_UNIT(n) (0x00001A0C + (n * 32)) +#define NV20_TCL_PRIMITIVE_3D_TX_SWIZZLE_UNIT(n) (0x00001A10 + (n * 32)) +#define NV20_TCL_PRIMITIVE_3D_TX_SWIZZLE_S0_ZERO 0 +#define NV20_TCL_PRIMITIVE_3D_TX_SWIZZLE_S0_ONE 1 +#define NV20_TCL_PRIMITIVE_3D_TX_SWIZZLE_S0_S1 2 +#define NV20_TCL_PRIMITIVE_3D_TX_SWIZZLE_S1_X 3 +#define NV20_TCL_PRIMITIVE_3D_TX_SWIZZLE_S1_Y 2 +#define NV20_TCL_PRIMITIVE_3D_TX_SWIZZLE_S1_Z 1 +#define NV20_TCL_PRIMITIVE_3D_TX_SWIZZLE_S1_W 0 +#define NV20_TCL_PRIMITIVE_3D_TX_FILTER_UNIT(n) (0x00001A14 + (n * 32)) +#define NV20_TCL_PRIMITIVE_3D_TX_FILTER_MIN 19:16 +#define NV20_TCL_PRIMITIVE_3D_TX_FILTER_MAG 27:24 +#define NV20_TCL_PRIMITIVE_3D_TX_XY_DIM_UNIT(n) (0x00001A18 + (n * 32)) +#define NV20_TCL_PRIMITIVE_3D_TX_UNK07_UNIT(n) (0x00001A1C + (n * 32)) + +#define NV20_TCL_PRIMITIVE_3D_INDEX_DATA 0x00001800 +#define NV20_TCL_PRIMITIVE_3D_VB_VERTEX_BATCH 0x00001810 +#define NV20_TCL_PRIMITIVE_3D_VERTEX_DATA 0x00001818 +// 0x00001c18 +#define NV20_TCL_PRIMITIVE_3D_SCISSOR_X2_X1 0x00001c30 +#define NV20_TCL_PRIMITIVE_3D_SCISSOR_Y2_Y1 0x00001c50 +#define NV20_TCL_PRIMITIVE_3D_ACTIVATE_COLORS 0x00001d6c +#define NV20_TCL_PRIMITIVE_3D_MULTISAMPLE 0x00001d7c //bit0:MultiSampleAntiAliasing bits31-16:MultiSampleMask +#define NV20_TCL_PRIMITIVE_3D_CULL_ENABLE 0x00001d84 //bit0:OcclusionCullEnable bit1:StencilCullEnable +#define NV20_TCL_PRIMITIVE_3D_PARAMETER_A 0x00001d8c //connects with MMIO 0x00401A88 (useful to pass parameters to interrupt routines) +#define NV20_TCL_PRIMITIVE_3D_PARAMETER_B 0x00001d90 //connects with MMIO 0x0040186C (useful to pass parameters to interrupt routines) +#define NV20_TCL_PRIMITIVE_3D_CLEAR_VALUE_DEPTH 0x00001d8c +#define NV20_TCL_PRIMITIVE_3D_CLEAR_VALUE_ARGB 0x00001d90 +#define NV20_TCL_PRIMITIVE_3D_CLEAR_WHICH_BUFFERS 0x00001d94 //used to trigger clear operation (Parameters A & B are then considered depth & color values) +#define NV20_TCL_PRIMITIVE_3D_CLEAR_VALUE_HORIZ 0x00001d98 +#define NV20_TCL_PRIMITIVE_3D_CLEAR_VALUE_VERT 0x00001d9c +#define NV20_TCL_PRIMITIVE_3D_SHADOW_FUNC_FUNC 0x00001e6c +#define NV20_TCL_PRIMITIVE_3D_TX_SHADER_DOTMAPPING 0x00001e74 //(0 means [0,255]argb from texture=>[0.0,1.0](r,g,b)) +#define NV20_TCL_PRIMITIVE_3D_SHADER_TYPE 0x00001e94 +#define SHADER_TYPE_INTERNAL 4 +#define SHADER_TYPE_EXTERNAL 6 +#define NV20_TCL_PRIMITIVE_3D_SHADER_SUBTYPE 0x00001e98 +#define SHADER_SUBTYPE_REGULAR 0 //not allowed to write into constants: faster +#define NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_FROM_ID 0x00001e9C +#define NV20_TCL_PRIMITIVE_3D_VP_PROGRAM_START_ID 0x00001ea0 +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_ORIGIN_X 0x00001f00 +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_ORIGIN_Y 0x00001f04 +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_ORIGIN_Z 0x00001f08 +#define NV20_TCL_PRIMITIVE_3D_VIEWPORT_ORIGIN_W 0x00001f0c + + +#define NV30_TCL_PRIMITIVE_3D 0x00000097 + +#define NV30_TCL_PRIMITIVE_3D_SET_OBJECT0 0x00000180 +#define NV30_TCL_PRIMITIVE_3D_SET_OBJECT1 0x00000184 +#define NV30_TCL_PRIMITIVE_3D_SET_OBJECT2 0x00000188 +#define NV30_TCL_PRIMITIVE_3D_SET_OBJECT3 0x0000018C +#define NV30_TCL_PRIMITIVE_3D_SET_OBJECT4 0x00000194 +#define NV30_TCL_PRIMITIVE_3D_SET_OBJECT5 0x00000198 +#define NV30_TCL_PRIMITIVE_3D_SET_VB_SRC0_OBJECT 0x0000019C +#define NV30_TCL_PRIMITIVE_3D_SET_VB_SRC1_OBJECT 0x000001A0 +#define NV30_TCL_PRIMITIVE_3D_SET_OBJECT6 0x000001A4 /* see NV30_TCL_PRIMITIVE_3D_UNK1D6C/1D70 */ +#define NV30_TCL_PRIMITIVE_3D_SET_OBJECT7 0x000001A8 +#define NV30_TCL_PRIMITIVE_3D_SET_OBJECT8 0x000001AC +#define NV30_TCL_PRIMITIVE_3D_SET_OBJECT8B 0x000001B0 +#define NV30_TCL_PRIMITIVE_3D_SET_OBJECT9 0x000001B4 +#define NV30_TCL_PRIMITIVE_3D_SET_OBJECT10 0x000001B8 +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_COLOR_BUFFER_DIM0 0x00000200 ///< X dims and offset. Please see doc/nv40_color_buff.txt +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_COLOR_BUFFER_DIM1 0x00000204 ///< Y dims and offset +#define NV30_TCL_PRIMITIVE_3D_BUFFER_FORMAT 0x00000208 +#define NV30_TCL_PRIMITIVE_3D_BUFFER0_PITCH 0x0000020c +#define NV30_TCL_PRIMITIVE_3D_COLOR0_OFFSET 0x00000210 +#define NV30_TCL_PRIMITIVE_3D_DEPTH_OFFSET 0x00000214 +#define NV30_TCL_PRIMITIVE_3D_COLOR1_OFFSET 0x00000218 +#define NV30_TCL_PRIMITIVE_3D_BUFFER1_PITCH 0x0000021c +#define NV30_TCL_PRIMITIVE_3D_ENABLED_BUFFERS 0x00000220 +#define NV30_TCL_PRIMITIVE_3D_LMA_DEPTH_BUFFER_PITCH 0x0000022c +#define NV30_TCL_PRIMITIVE_3D_LMA_DEPTH_BUFFER_OFFSET 0x00000230 +#define NV30_TCL_PRIMITIVE_3D_TX_MATRIX_ENABLE(n) (0x0000240+(n<<2)) +#define NV30_TCL_PRIMITIVE_3D_BUFFER2_PITCH 0x00000280 +#define NV30_TCL_PRIMITIVE_3D_BUFFER3_PITCH 0x00000284 +#define NV30_TCL_PRIMITIVE_3D_BUFFER2_OFFSET 0x00000288 +#define NV30_TCL_PRIMITIVE_3D_BUFFER3_OFFSET 0x0000028c +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_COLOR_BUFFER_OFS0 0x000002c0 ///< Offset and modulo for width +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_COLOR_BUFFER_OFS1 0x000002c4 ///< Offset and modulo for height +#define NV30_TCL_PRIMITIVE_3D_DITHER_ENABLE 0x00000300 +#define NV30_TCL_PRIMITIVE_3D_ALPHA_FUNC_ENABLE 0x00000304 +#define NV30_TCL_PRIMITIVE_3D_ALPHA_FUNC_FUNC 0x00000308 +#define NV30_TCL_PRIMITIVE_3D_ALPHA_FUNC_REF 0x0000030c +#define NV30_TCL_PRIMITIVE_3D_BLEND_FUNC_ENABLE 0x00000310 +#define NV30_TCL_PRIMITIVE_3D_BLEND_FUNC_SRC 0x00000314 +#define NV30_TCL_PRIMITIVE_3D_BLEND_FUNC_DST 0x00000318 +#define NV30_TCL_PRIMITIVE_3D_BLEND_COLOR 0x0000031c +#define NV30_TCL_PRIMITIVE_3D_BLEND_EQUATION 0x00000320 +#define NV30_TCL_PRIMITIVE_3D_COLOR_MASK 0x00000324 +#define NV30_TCL_PRIMITIVE_3D_STENCIL_BACK_ENABLE 0x00000328 +#define NV30_TCL_PRIMITIVE_3D_STENCIL_BACK_MASK 0x0000032c +#define NV30_TCL_PRIMITIVE_3D_STENCIL_BACK_FUNC_FUNC 0x00000330 +#define NV30_TCL_PRIMITIVE_3D_STENCIL_BACK_FUNC_REF 0x00000334 +#define NV30_TCL_PRIMITIVE_3D_STENCIL_BACK_FUNC_MASK 0x00000338 +#define NV30_TCL_PRIMITIVE_3D_STENCIL_BACK_OP_FAIL 0x0000033c +#define NV30_TCL_PRIMITIVE_3D_STENCIL_BACK_OP_ZFAIL 0x00000340 +#define NV30_TCL_PRIMITIVE_3D_STENCIL_BACK_OP_ZPASS 0x00000344 +#define NV30_TCL_PRIMITIVE_3D_STENCIL_FRONT_ENABLE 0x00000348 +#define NV30_TCL_PRIMITIVE_3D_STENCIL_FRONT_MASK 0x0000034c +#define NV30_TCL_PRIMITIVE_3D_STENCIL_FRONT_FUNC_FUNC 0x00000350 +#define NV30_TCL_PRIMITIVE_3D_STENCIL_FRONT_FUNC_REF 0x00000354 +#define NV30_TCL_PRIMITIVE_3D_STENCIL_FRONT_FUNC_MASK 0x00000358 +#define NV30_TCL_PRIMITIVE_3D_STENCIL_FRONT_OP_FAIL 0x0000035c +#define NV30_TCL_PRIMITIVE_3D_STENCIL_FRONT_OP_ZFAIL 0x00000360 +#define NV30_TCL_PRIMITIVE_3D_STENCIL_FRONT_OP_ZPASS 0x00000364 +#define NV30_TCL_PRIMITIVE_3D_SHADE_MODEL 0x00000368 +#define NV30_TCL_PRIMITIVE_3D_FOG_ENABLE 0x0000036c +#define NV30_TCL_PRIMITIVE_3D_FOG_COLOR 0x00000370 +#define NV30_TCL_PRIMITIVE_3D_COLOR_LOGIC_OP_ENABLE 0x00000374 +#define NV30_TCL_PRIMITIVE_3D_COLOR_LOGIC_OP_OP 0x00000378 +#define NV30_TCL_PRIMITIVE_3D_NORMALIZE_ENABLE 0x0000037c +#define NV30_TCL_PRIMITIVE_3D_DEPTH_RANGE_NEAR 0x00000394 +#define NV30_TCL_PRIMITIVE_3D_DEPTH_RANGE_FAR 0x00000398 +#define NV30_TCL_PRIMITIVE_3D_COLOR_MATERIAL_FRONT_R 0x000003a0 +#define NV30_TCL_PRIMITIVE_3D_COLOR_MATERIAL_FRONT_G 0x000003a4 +#define NV30_TCL_PRIMITIVE_3D_COLOR_MATERIAL_FRONT_B 0x000003a8 +#define NV30_TCL_PRIMITIVE_3D_COLOR_MATERIAL_FRONT_A 0x000003b4 +#define NV30_TCL_PRIMITIVE_3D_LINE_WIDTH_SMOOTH 0x000003b8 +#define NV30_TCL_PRIMITIVE_3D_LINE_SMOOTH_ENABLE 0x000003bc +#define NV30_TCL_PRIMITIVE_3D_CLIP_PLANE_ENABLE(n) (0x00000400+(n<<2)) +#define NV30_TCL_PRIMITIVE_3D_MODELVIEW_MATRIX 0x00000480 +#define NV30_TCL_PRIMITIVE_3D_INVERSE_MODELVIEW_MATRIX 0x00000580 +#define NV30_TCL_PRIMITIVE_3D_PROJECTION_MATRIX 0x00000680 +#define NV30_TCL_PRIMITIVE_3D_TX_MATRIX(n) (0x000006c0+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_SCISSOR_WIDTH_XPOS 0x000008c0 ///< Set the width and xpos of glScissor() +#define NV30_TCL_PRIMITIVE_3D_SCISSOR_HEIGHT_YPOS 0x000008c4 ///< Set the height and ypos of glScissor() +#define NV30_TCL_PRIMITIVE_3D_FP_ACTIVE_PROGRAM 0x000008e4 +#define NV30_TCL_PRIMITIVE_3D_FOG_COORD_DIST 0x000008c8 +#define NV30_TCL_PRIMITIVE_3D_FOG_MODE 0x000008cc +#define NV30_TCL_PRIMITIVE_3D_FOG_EQUATION_CONSTANT 0x000008d0 +#define NV30_TCL_PRIMITIVE_3D_FOG_EQUATION_LINEAR 0x000008d4 +#define NV30_TCL_PRIMITIVE_3D_FOG_EQUATION_QUADRATIC 0x000008d8 +#define NV30_TCL_PRIMITIVE_3D_RC_COLOR0 0x000008ec +#define NV30_TCL_PRIMITIVE_3D_RC_COLOR1 0x000008f0 +#define NV30_TCL_PRIMITIVE_3D_RC_FINAL0 0x000008f4 +#define NV30_TCL_PRIMITIVE_3D_RC_FINAL1 0x000008f8 +#define NV30_TCL_PRIMITIVE_3D_RC_ENABLE 0x000008fc +#define NV30_TCL_PRIMITIVE_3D_RC_IN_ALPHA(n) (0x00000900+(n<<5)) +#define NV30_TCL_PRIMITIVE_3D_RC_IN_RGB(n) (0x00000904+(n<<5)) +#define NV30_TCL_PRIMITIVE_3D_RC_CONSTANT_COLOR0(n) (0x00000908+(n<<5)) +#define NV30_TCL_PRIMITIVE_3D_RC_CONSTANT_COLOR1(n) (0x0000090c+(n<<5)) +#define NV30_TCL_PRIMITIVE_3D_RC_OUT_ALPHA(n) (0x00000910+(n<<5)) +#define NV30_TCL_PRIMITIVE_3D_RC_OUT_RGB(n) (0x00000914+(n<<5)) +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_DIMS_0 0x00000a00 +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_DIMS_0_WIDTH 31:16 +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_DIMS_0_XOFFS 15:0 +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_DIMS_1 0x00000a04 +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_DIMS_0_HEIGHT 31:16 +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_DIMS_0_YOFFS 15:0 +#define NV30_TCL_PRIMITIVE_3D_LIGHT_MODEL_FRONT_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_R 0x00000a10 +#define NV30_TCL_PRIMITIVE_3D_LIGHT_MODEL_FRONT_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_G 0x00000a14 +#define NV30_TCL_PRIMITIVE_3D_LIGHT_MODEL_FRONT_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_B 0x00000a18 +/* VIEWPORT_XFRM_* are FP32 values */ +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_XFRM_OX 0x00000a20 /* center X? */ +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_XFRM_OY 0x00000a24 /* center Y? */ +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_XFRM_NPF_DIV2 0x00000a28 /* (near+far)/2 */ +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_XFRM_UNK0_0x0 0x00000a2c /* always 0? */ +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_XFRM_PX_DIV2 0x00000a30 /* width/2 */ +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_XFRM_PY_DIV2 0x00000a34 /* -(height/2) */ +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_XFRM_FMN_DIV2 0x00000a38 /* (far-near)/2 */ +#define NV30_TCL_PRIMITIVE_3D_VIEWPORT_XFRM_UNK1_0x0 0x00000a3c /* always 0? */ +#define NV30_TCL_PRIMITIVE_3D_POLYGON_OFFSET_FILL_ENABLE 0x00000a60 +#define NV30_TCL_PRIMITIVE_3D_POLYGON_OFFSET_LINE_ENABLE 0x00000a64 +#define NV30_TCL_PRIMITIVE_3D_POLYGON_OFFSET_POINT_ENABLE 0x00000a68 +#define NV30_TCL_PRIMITIVE_3D_DEPTH_FUNC 0x00000a6c +#define NV30_TCL_PRIMITIVE_3D_DEPTH_WRITE_ENABLE 0x00000a70 +#define NV30_TCL_PRIMITIVE_3D_DEPTH_TEST_ENABLE 0x00000a74 +#define NV30_TCL_PRIMITIVE_3D_POLYGON_OFFSET_FACTOR 0x00000a78 +#define NV30_TCL_PRIMITIVE_3D_POLYGON_OFFSET_UNITS 0x00000a7c /* units*2 ?? */ +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_INST0 0x00000b80 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_INST1 0x00000b84 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_INST2 0x00000b88 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_INST3 0x00000b8c +#define NV30_TCL_PRIMITIVE_3D_CLIP_PLANE_A(n) (0x00000e00+(n<<4)) +#define NV30_TCL_PRIMITIVE_3D_CLIP_PLANE_B(n) (0x00000e04+(n<<4)) +#define NV30_TCL_PRIMITIVE_3D_CLIP_PLANE_C(n) (0x00000e08+(n<<4)) +#define NV30_TCL_PRIMITIVE_3D_CLIP_PLANE_D(n) (0x00000e0c+(n<<4)) + +#define NV30_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_AMBIENT_R(n) (0x00001000+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_AMBIENT_G(n) (0x00001004+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_AMBIENT_B(n) (0x00001008+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_DIFFUSE_R(n) (0x0000100c+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_DIFFUSE_G(n) (0x00001010+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_DIFFUSE_B(n) (0x00001014+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_SPECULAR_R(n) (0x00001018+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_SPECULAR_G(n) (0x0000101c+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_FRONT_SIDE_PRODUCT_SPECULAR_B(n) (0x00001020+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_HALF_VECTOR_X(n) (0x00001028+(n<<7)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_HALF_VECTOR_Y(n) (0x0000102c+(n<<7)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_HALF_VECTOR_Z(n) (0x00001030+(n<<7)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_DIRECTION_X(n) (0x00001034+(n<<7)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_DIRECTION_Y(n) (0x00001038+(n<<7)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_DIRECTION_Z(n) (0x0000103c+(n<<7)) + +#define NV30_TCL_PRIMITIVE_3D_LIGHT_CONSTANT_ATTENUATION(n) (0x00001228+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_LINEAR_ATTENUATION(n) (0x0000122c+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_QUADRATIC_ATTENUATION(n) (0x00001230+(n<<6)) + +/* These commands seem right on NV34, but I do not know how the parameters are + * calculated. */ +#define NV30_TCL_PRIMITIVE_3D_LIGHT_SPOT_CUTOFF_A(n) (0x00001200+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_SPOT_EXPONENT(n) (0x00001204+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_SPOT_CUTOFF_B(n) (0x00001208+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_SPOT_DIR_X(n) (0x0000120c+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_SPOT_DIR_Y(n) (0x00001210+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_SPOT_DIR_Z(n) (0x00001214+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_SPOT_CUTOFF_C(n) (0x00001218+(n<<6)) + +#define NV30_TCL_PRIMITIVE_3D_LIGHT_POSITION_X(n) (0x0000121c+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_POSITION_Y(n) (0x00001220+(n<<6)) +#define NV30_TCL_PRIMITIVE_3D_LIGHT_POSITION_Z(n) (0x00001224+(n<<6)) + +#define NV30_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_A 0x00001400 +#define NV30_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_B 0x00001404 +#define NV30_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_C 0x00001408 +#define NV30_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_D 0x0000140c +#define NV30_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_E 0x00001410 +#define NV30_TCL_PRIMITIVE_3D_FRONT_MATERIAL_SHININESS_F 0x00001414 +#define NV30_TCL_PRIMITIVE_3D_ENABLED_LIGHTS 0x00001420 + +/** + Clipping planes enable / Disable
+ for each clipping plane first the matrix is uploaded followed by + a 0x1478. The 32 bit parameter is a bitmap, where bit (plane * 2 +1) is + set for each active bitmap. Clearing this bit would deactivate the clipping plane + So for Clipping planes 0, 2 and 3 to be enabled you would see + 0x1478 0x00002202. + So effectively 16 bit of the 32 bits are used for clipping planes. Currently + the use of the other 16 bit is unknown. + +*/ + + +#define NV30_TCL_PRIMITIVE_3D_SET_CLIPPING_PLANES 0x00001478 +#define NV30_TCL_PRIMITIVE_3D_POLYGON_STIPPLE_ENABLE 0x0000147C +#define NV30_TCL_PRIMITIVE_3D_POLYGON_STIPPLE_PATTERN(i) (0x00001480 + (i<<2)) +#define NV30_TCL_PRIMITIVE_3D_POLYGON_STIPPLE_PATTERN__SIZE 32 + + +/* These seem to contain default values for each vertex attribute (0-15). + * Values set outside of glBegin()/glEnd() appear here. + */ +#define NV30_TCL_PRIMITIVE_3D_VTX_ATTR_3X(a) (0x00001500 + (a * 0x10)) +#define NV30_TCL_PRIMITIVE_3D_VTX_ATTR_3Y(a) (0x00001504 + (a * 0x10)) +#define NV30_TCL_PRIMITIVE_3D_VTX_ATTR_3Z(a) (0x00001508 + (a * 0x10)) +#define NV30_TCL_PRIMITIVE_3D_VTX_ATTR_3W(a) (0x0000150C + (a * 0x10)) /* This exists, but not used on gl*4f calls.. */ +#define NV30_TCL_PRIMITIVE_3D_VB_POINTER_ATTR(a) (0x00001680 + (a * 0x04)) + +#define NV30_TCL_PRIMITIVE_3D_VERTEX_UNK_0 0x00001718 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR(i) (0x00001740 + (i * 0x04)) +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR__SIZE 16 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR0_POS 0x00001740 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR1_WGH 0x00001744 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR2_NOR 0x00001748 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR3_COL 0x0000174c +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR4_COL2 0x00001750 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR5_FOG 0x00001754 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR6 0x00001758 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR7 0x0000175c +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR8_TX0 0x00001760 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR9_TX1 0x00001764 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR10_TX2 0x00001768 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR11_TX3 0x0000176c +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR12_TX4 0x00001770 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR13_TX5 0x00001774 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR14_TX6 0x00001778 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_ATTR15_TX7 0x0000177c +#define NV30_TCL_PRIMITIVE_3D_LIGHT_MODEL_BACK_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_R 0x000017a0 +#define NV30_TCL_PRIMITIVE_3D_LIGHT_MODEL_BACK_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_G 0x000017a4 +#define NV30_TCL_PRIMITIVE_3D_LIGHT_MODEL_BACK_SIDE_PRODUCT_AMBIENT_PLUS_EMISSION_B 0x000017a8 +#define NV30_TCL_PRIMITIVE_3D_COLOR_MATERIAL_BACK_R 0x000017b0 +#define NV30_TCL_PRIMITIVE_3D_COLOR_MATERIAL_BACK_G 0x000017b4 +#define NV30_TCL_PRIMITIVE_3D_COLOR_MATERIAL_BACK_B 0x000017b8 +#define NV30_TCL_PRIMITIVE_3D_COLOR_MATERIAL_BACK_A 0x000017c0 +/** + \brief Enable Color buffer or Occlusion query + This primitive is called on two occasions: +
    +
  • If you clear the color buffer, you will see this command + with value of 0x00000002 +
  • If you are enabling an occlusion query, you will see + this command with a value of 0x00000001 +
+*/ +#define NV30_TCL_PRIMITIVE_3D_OCC_QUERY_OR_COLOR_BUFF_ENABLE 0x000017c8 +/** + \brief store the result of an occlusion query + + This primitive is called on two occasions: +
    +
  • If you clear the color buffer, you will see this command + with value of 0x00000002 (Red?), 0x00000003 (Green?), + 0x00000004 (Blue?), and 0x00000005 (Alpha?) +
  • If you are enabling an occlusion query, you will see + this command with a value of 0x01vvvvvv + vvvvvv defines the query number (starting from 0) + multiplied with 16 +
+*/ +#define NV30_TCL_PRIMITIVE_3D_STORE_RESULT 0x00001800 +#define NV30_TCL_PRIMITIVE_3D_BEGIN_END 0x00001808 +#define NV30_TCL_PRIMITIVE_3D_VB_ELEMENT_U16 0x0000180c +#define NV30_TCL_PRIMITIVE_3D_VB_ELEMENT_U32 0x00001810 +#define NV30_TCL_PRIMITIVE_3D_VB_VERTEX_BATCH 0x00001814 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_DATA 0x00001818 +#define NV30_TCL_PRIMITIVE_3D_SET_DISPLAY_LIST_MEM_OFFSET 0x0000181c +#define NV30_TCL_PRIMITIVE_3D_EXECUTE_DISPLAY_LIST 0x00001824 +#define NV30_TCL_PRIMITIVE_3D_POLYGON_MODE_FRONT 0x00001828 +#define NV30_TCL_PRIMITIVE_3D_POLYGON_MODE_BACK 0x0000182c +#define NV30_TCL_PRIMITIVE_3D_CULL_FACE 0x00001830 +#define NV30_TCL_PRIMITIVE_3D_FRONT_FACE 0x00001834 +#define NV30_TCL_PRIMITIVE_3D_POLYGON_SMOOTH_ENABLE 0x00001838 +#define NV30_TCL_PRIMITIVE_3D_CULL_FACE_ENABLE 0x0000183c +#define NV30_TCL_PRIMITIVE_3D_TX_DEPTH_UNIT(n) (0x00001840 + (n*4)) +#define NV30_TCL_PRIMITIVE_3D_TX_DEPTH 31:24 +#define NV30_TCL_PRIMITIVE_3D_TX_NPOT_PITCH 23:0 +#define NV30_TCL_PRIMITIVE_3D_TX_ADDRESS_UNIT(n) (0x00001A00 + (n * 32)) +#define NV30_TCL_PRIMITIVE_3D_TX_FORMAT_UNIT(n) (0x00001A04 + (n * 32)) +#define NV30_TCL_PRIMITIVE_3D_TX_FORMAT_MIPMAP_COUNT 23:20 +#define NV30_TCL_PRIMITIVE_3D_TX_FORMAT_TYPE 14:13 +#define NV30_TCL_PRIMITIVE_3D_TX_FORMAT_FORMAT 12:8 +#define NV30_TCL_PRIMITIVE_3D_TX_FORMAT_NCOMP 7:4 /* 2=2D, 3=3D, high bit may be wrong */ +#define NV30_TCL_PRIMITIVE_3D_TX_FORMAT_CUBIC 2:2 +#define NV30_TCL_PRIMITIVE_3D_TX_WRAP_UNIT(n) (0x00001A08 + (n * 32)) +#define NV30_TCL_PRIMITIVE_3D_TX_WRAP_S 7:0 +#define NV30_TCL_PRIMITIVE_3D_TX_WRAP_T 15:8 +#define NV30_TCL_PRIMITIVE_3D_TX_WRAP_R 23:16 +#define NV30_TCL_PRIMITIVE_3D_TX_ENABLE_UNIT(n) (0x00001A0C + (n * 32)) +#define NV30_TCL_PRIMITIVE_3D_TX_SWIZZLE_UNIT(n) (0x00001A10 + (n * 32)) +#define NV30_TCL_PRIMITIVE_3D_TX_SWIZZLE_S0_ZERO 0 +#define NV30_TCL_PRIMITIVE_3D_TX_SWIZZLE_S0_ONE 1 +#define NV30_TCL_PRIMITIVE_3D_TX_SWIZZLE_S0_S1 2 +#define NV30_TCL_PRIMITIVE_3D_TX_SWIZZLE_S1_X 3 +#define NV30_TCL_PRIMITIVE_3D_TX_SWIZZLE_S1_Y 2 +#define NV30_TCL_PRIMITIVE_3D_TX_SWIZZLE_S1_Z 1 +#define NV30_TCL_PRIMITIVE_3D_TX_SWIZZLE_S1_W 0 +#define NV30_TCL_PRIMITIVE_3D_TX_FILTER_UNIT(n) (0x00001A14 + (n * 32)) +#define NV30_TCL_PRIMITIVE_3D_TX_FILTER_MIN 19:16 +#define NV30_TCL_PRIMITIVE_3D_TX_FILTER_MAG 27:24 +#define NV30_TCL_PRIMITIVE_3D_TX_XY_DIM_UNIT(n) (0x00001A18 + (n * 32)) +#define NV30_TCL_PRIMITIVE_3D_TX_UNK07_UNIT(n) (0x00001A1C + (n * 32)) +/* These seem to contain default values for each vertex attribute (0-15). + * Values set outside of glBegin()/glEnd() appear here. + */ +#define NV30_TCL_PRIMITIVE_3D_VTX_ATTR_4X(a) (0x00001C00 + (a * 0x10)) +#define NV30_TCL_PRIMITIVE_3D_VTX_ATTR_4Y(a) (0x00001C04 + (a * 0x10)) +#define NV30_TCL_PRIMITIVE_3D_VTX_ATTR_4Z(a) (0x00001C08 + (a * 0x10)) +#define NV30_TCL_PRIMITIVE_3D_VTX_ATTR_4W(a) (0x00001C0C + (a * 0x10)) + +#define NV30_TCL_PRIMITIVE_3D_VERTEX_NOR_3I_XY 0x00000a90 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_NOR_3I_Z 0x00000a94 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX0_2F_S 0x000018c0 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX0_2F_T 0x000018c4 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX1_2F_S 0x000018c8 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX1_2F_T 0x000018cc +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX2_2F_S 0x000018d0 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX2_2F_T 0x000018d4 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX3_2F_S 0x000018d8 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX3_2F_T 0x000018dc +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX0_2I 0x00001920 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX1_2I 0x00001924 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX2_2I 0x00001928 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX3_2I 0x0000192c +#define NV30_TCL_PRIMITIVE_3D_VERTEX_COL_4I 0x0000194c +#define NV30_TCL_PRIMITIVE_3D_VERTEX_COL2_3I 0x00001950 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX0_4I_ST 0x000019c0 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX0_4I_RQ 0x000019c4 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX1_4I_ST 0x000019c8 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX1_4I_RQ 0x000019cc +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX2_4I_ST 0x000019d0 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX2_4I_RQ 0x000019d4 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX3_4I_ST 0x000019d8 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_TX3_4I_RQ 0x000019dc +#define NV30_TCL_PRIMITIVE_3D_FP_CONTROL 0x00001d60 +#define NV30_TCL_PRIMITIVE_3D_VERTEX_FOG_1F 0x00001e54 +/* Offset into the memory pointed at by dma object specified in SET_OBJECT6 */ +#define NV30_TCL_PRIMITIVE_3D_UNK1D6C_OFFSET 0x00001d6c +/* Write VALUE at the offset specified in UNK1D6C_OFFSET */ +#define NV30_TCL_PRIMITIVE_3D_UNK1D70_VALUE 0x00001d70 +#define NV30_TCL_PRIMITIVE_3D_LINE_STIPPLE_ENABLE 0x00001db4 +#define NV30_TCL_PRIMITIVE_3D_LINE_STIPPLE_PATTERN 0x00001db8 +#define NV30_TCL_PRIMITIVE_3D_CLEAR_VALUE_DEPTH 0x00001d8c +#define NV30_TCL_PRIMITIVE_3D_CLEAR_VALUE_ARGB 0x00001d90 +/* CLEAR_WHICH_BUFFERS initiates the clear operation */ +#define NV30_TCL_PRIMITIVE_3D_CLEAR_WHICH_BUFFERS 0x00001d94 +#define NV30_TCL_PRIMITIVE_3D_DO_VERTICES 0x00001dac +#define NV30_TCL_PRIMITIVE_3D_BACK_MATERIAL_SHININESS_A 0x00001e20 +#define NV30_TCL_PRIMITIVE_3D_BACK_MATERIAL_SHININESS_B 0x00001e24 +#define NV30_TCL_PRIMITIVE_3D_BACK_MATERIAL_SHININESS_C 0x00001e28 +#define NV30_TCL_PRIMITIVE_3D_BACK_MATERIAL_SHININESS_D 0x00001e2c +#define NV30_TCL_PRIMITIVE_3D_BACK_MATERIAL_SHININESS_E 0x00001e30 +#define NV30_TCL_PRIMITIVE_3D_BACK_MATERIAL_SHININESS_F 0x00001e34 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_FROM_ID 0x00001e9C +#define NV30_TCL_PRIMITIVE_3D_VP_PROGRAM_START_ID 0x00001ea0 +#define NV30_TCL_PRIMITIVE_3D_POINT_PARAMETER_A 0x00001ec0 +#define NV30_TCL_PRIMITIVE_3D_POINT_PARAMETER_B 0x00001ec4 +#define NV30_TCL_PRIMITIVE_3D_POINT_PARAMETER_C 0x00001ec8 +#define NV30_TCL_PRIMITIVE_3D_POINT_PARAMETER_D 0x00001ecc +#define NV30_TCL_PRIMITIVE_3D_POINT_PARAMETER_E 0x00001ed0 +#define NV30_TCL_PRIMITIVE_3D_POINT_PARAMETER_F 0x00001ed4 +#define NV30_TCL_PRIMITIVE_3D_POINT_PARAMETER_G 0x00001ed8 +#define NV30_TCL_PRIMITIVE_3D_POINT_PARAMETER_H 0x00001edc +#define NV30_TCL_PRIMITIVE_3D_POINT_SIZE 0x00001ee0 +#define NV30_TCL_PRIMITIVE_3D_POINT_PARAMETERS_ENABLE 0x00001ee4 +#define NV30_TCL_PRIMITIVE_3D_POINT_SPRITE 0x00001ee8 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_ID 0x00001efc +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P0_X 0x00001f00 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P0_Y 0x00001f04 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P0_Z 0x00001f08 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P0_W 0x00001f0C +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P1_X 0x00001f10 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P1_Y 0x00001f14 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P1_Z 0x00001f18 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P1_W 0x00001f1C +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P2_X 0x00001f20 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P2_Y 0x00001f24 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P2_Z 0x00001f28 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P2_W 0x00001f2C +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P3_X 0x00001f30 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P3_Y 0x00001f34 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P3_Z 0x00001f38 +#define NV30_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_P3_W 0x00001f3C +#define NV30_TCL_PRIMITIVE_3D_VP_IN_REG 0x00001ff0 +#define NV30_TCL_PRIMITIVE_3D_VP_OUT_REG 0x00001ff4 + + +#define NV40_TCL_PRIMITIVE_3D 0x00000097 +#define NV40_TCL_PRIMITIVE_3D_COLOR_MASK_BUFFER123 0x00000370 + + +#define NV30_CLEAR_BUFFER 0x00000066 +#define NV30_CLEAR_BUFFER_SET_DMA_NOTIFY 0x00000180 +#define NV30_CLEAR_BUFFER_SET_IMAGE_PATTERN 0x00000188 +#define NV30_CLEAR_BUFFER_SET_RASTER_OP 0x0000018c +#define NV30_CLEAR_BUFFER_SET_CONTEXT_SURFACE_2D 0x00000198 +#define NV30_CLEAR_BUFFER_UNK002fc 0x000002fc + + +#define NV50_TCL_PRIMITIVE_3D 0x00000097 + +#define NV50_TCL_PRIMITIVE_3D_SET_OBJECT_0(n) (0x00000180 + (n<<2)) +#define NV50_TCL_PRIMITIVE_3D_SET_OBJECT_0__SIZE 12 +#define NV50_TCL_PRIMITIVE_3D_SET_OBJECT_1(n) (0x000001c0 + (n<<2)) +#define NV50_TCL_PRIMITIVE_3D_SET_OBJECT_1__SIZE 8 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_FOG_1F 0x00000314 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_POS_2F_X 0x00000380 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_POS_2F_Y 0x00000384 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX0_2F_S 0x000003c0 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX0_2F_T 0x000003c4 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX1_2F_S 0x000003c8 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX1_2F_T 0x000003cc +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX2_2F_S 0x000003d0 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX2_2F_T 0x000003d4 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX3_2F_S 0x000003d8 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX3_2F_T 0x000003dc +#define NV50_TCL_PRIMITIVE_3D_VERTEX_POS_3F_X 0x00000400 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_POS_3F_Y 0x00000404 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_POS_3F_Z 0x00000408 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_NOR_3F_X 0x00000420 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_NOR_3F_Y 0x00000424 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_NOR_3F_Z 0x00000428 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_COL_3F_R 0x00000430 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_COL_3F_G 0x00000434 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_COL_3F_B 0x00000438 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_COL2_3F_R 0x00000440 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_COL2_3F_G 0x00000444 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_COL2_3F_B 0x00000448 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_POS_4F_X 0x00000500 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_POS_4F_Y 0x00000504 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_POS_4F_Z 0x00000508 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_POS_4F_W 0x0000050c +#define NV50_TCL_PRIMITIVE_3D_VERTEX_COL_4F_R 0x00000530 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_COL_4F_G 0x00000534 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_COL_4F_B 0x00000538 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_COL_4F_A 0x0000053c +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX0_4F_S 0x00000580 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX0_4F_T 0x00000584 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX0_4F_R 0x00000588 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX0_4F_Q 0x0000058c +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX1_4F_S 0x00000590 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX1_4F_T 0x00000594 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX1_4F_R 0x00000598 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX1_4F_Q 0x0000059c +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX2_4F_S 0x000005a0 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX2_4F_T 0x000005a4 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX2_4F_R 0x000005a8 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX2_4F_Q 0x000005ac +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX3_4F_S 0x000005b0 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX3_4F_T 0x000005b4 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX3_4F_R 0x000005b8 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX3_4F_Q 0x000005bc +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX0_2I 0x000006a0 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX1_2I 0x000006a4 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX2_2I 0x000006a8 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX3_2I 0x000006ac +#define NV50_TCL_PRIMITIVE_3D_VERTEX_POS_4I_XY 0x00000700 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_POS_4I_ZW 0x00000704 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX0_4I_ST 0x00000740 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX0_4I_RQ 0x00000744 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX1_4I_ST 0x00000748 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX1_4I_RQ 0x0000074c +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX2_4I_ST 0x00000750 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX2_4I_RQ 0x00000754 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX3_4I_ST 0x00000758 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_TX3_4I_RQ 0x0000075c +#define NV50_TCL_PRIMITIVE_3D_VERTEX_NOR_3I_XY 0x00000790 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_NOR_3I_Z 0x00000794 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_COL_4I 0x0000088c +#define NV50_TCL_PRIMITIVE_3D_VERTEX_COL2_3I 0x00000890 +#define NV50_TCL_PRIMITIVE_3D_VIEWPORT_UNK0_X 0x00000a00 +#define NV50_TCL_PRIMITIVE_3D_VIEWPORT_UNK0_Y 0x00000a04 +#define NV50_TCL_PRIMITIVE_3D_VIEWPORT_UNK0_Z 0x00000a08 +#define NV50_TCL_PRIMITIVE_3D_VIEWPORT_UNK1_X 0x00000a0c +#define NV50_TCL_PRIMITIVE_3D_VIEWPORT_UNK1_Y 0x00000a10 +#define NV50_TCL_PRIMITIVE_3D_VIEWPORT_UNK1_Z 0x00000a14 +#define NV50_TCL_PRIMITIVE_3D_VIEWPORT_DIMS_0 0x00000c00 +#define NV50_TCL_PRIMITIVE_3D_VIEWPORT_DIMS_1 0x00000c04 +#define NV50_TCL_PRIMITIVE_3D_DEPTH_RANGE_NEAR 0x00000c08 +#define NV50_TCL_PRIMITIVE_3D_DEPTH_RANGE_FAR 0x00000c0c +#define NV50_TCL_PRIMITIVE_3D_VIEWPORT_CLIP_HORIZ(n) (0x0000d00+(n<<3)) +#define NV50_TCL_PRIMITIVE_3D_VIEWPORT_CLIP_VERT(n) (0x0000d04+(n<<3)) +#define NV50_TCL_PRIMITIVE_3D_VERTEX_BUFFER_FIRST 0x00000d74 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_BUFFER_COUNT 0x00000d78 +#define NV50_TCL_PRIMITIVE_3D_CLEAR_COLOR_R 0x00000d80 +#define NV50_TCL_PRIMITIVE_3D_CLEAR_COLOR_G 0x00000d84 +#define NV50_TCL_PRIMITIVE_3D_CLEAR_COLOR_B 0x00000d88 +#define NV50_TCL_PRIMITIVE_3D_CLEAR_COLOR_A 0x00000d8c +#define NV50_TCL_PRIMITIVE_3D_CLEAR_DEPTH 0x00000d90 +#define NV50_TCL_PRIMITIVE_3D_CLEAR_STENCIL 0x00000da0 +#define NV50_TCL_PRIMITIVE_3D_POLYGON_MODE_FRONT 0x00000dac +#define NV50_TCL_PRIMITIVE_3D_POLYGON_MODE_BACK 0x00000db0 +#define NV50_TCL_PRIMITIVE_3D_POLYGON_SMOOTH_ENABLE 0x00000db4 +#define NV50_TCL_PRIMITIVE_3D_POLYGON_OFFSET_POINT_ENABLE 0x00000dc0 +#define NV50_TCL_PRIMITIVE_3D_POLYGON_OFFSET_LINE_ENABLE 0x00000dc4 +#define NV50_TCL_PRIMITIVE_3D_POLYGON_OFFSET_FILL_ENABLE 0x00000dc8 +#define NV50_TCL_PRIMITIVE_3D_SCISSOR_WIDTH_XPOS 0x00000e04 +#define NV50_TCL_PRIMITIVE_3D_SCISSOR_HEIGHT_YPOS 0x00000e08 +#define NV50_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_ID 0x00000f00 +#define NV50_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_X 0x00000f04 +#define NV50_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_Y 0x00000f08 +#define NV50_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_Z 0x00000f0c +#define NV50_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_W 0x00000f10 +#define NV50_TCL_PRIMITIVE_3D_STENCIL_FRONT_FUNC_REF 0x00000f54 +#define NV50_TCL_PRIMITIVE_3D_STENCIL_FRONT_MASK 0x00000f58 +#define NV50_TCL_PRIMITIVE_3D_STENCIL_FRONT_FUNC_MASK 0x00000f5c +#define NV50_TCL_PRIMITIVE_3D_DEPTH_TEST_ENABLE 0x000012cc +#define NV50_TCL_PRIMITIVE_3D_SHADE_MODEL 0x000012d4 +#define NV50_TCL_PRIMITIVE_3D_DEPTH_WRITE_ENABLE 0x000012e8 +#define NV50_TCL_PRIMITIVE_3D_ALPHA_FUNC_ENABLE 0x000012ec +#define NV50_TCL_PRIMITIVE_3D_DEPTH_FUNC 0x0000130c +#define NV50_TCL_PRIMITIVE_3D_ALPHA_FUNC_REF 0x00001310 +#define NV50_TCL_PRIMITIVE_3D_ALPHA_FUNC_FUNC 0x00001314 +#define NV50_TCL_PRIMITIVE_3D_BLEND_COLOR_R 0x0000131c +#define NV50_TCL_PRIMITIVE_3D_BLEND_COLOR_G 0x00001320 +#define NV50_TCL_PRIMITIVE_3D_BLEND_COLOR_B 0x00001324 +#define NV50_TCL_PRIMITIVE_3D_BLEND_COLOR_A 0x00001328 +#define NV50_TCL_PRIMITIVE_3D_BLEND_EQUATION_RGB 0x00001340 +#define NV50_TCL_PRIMITIVE_3D_BLEND_FUNC_SRC_RGB 0x00001344 +#define NV50_TCL_PRIMITIVE_3D_BLEND_FUNC_DST_RGB 0x00001348 +#define NV50_TCL_PRIMITIVE_3D_BLEND_EQUATION_ALPHA 0x0000134c +#define NV50_TCL_PRIMITIVE_3D_BLEND_FUNC_SRC_ALPHA 0x00001350 +#define NV50_TCL_PRIMITIVE_3D_BLEND_FUNC_DST_ALPHA 0x00001358 +#define NV50_TCL_PRIMITIVE_3D_STENCIL_BACK_ENABLE 0x00001380 +#define NV50_TCL_PRIMITIVE_3D_STENCIL_BACK_OP_FAIL 0x00001384 +#define NV50_TCL_PRIMITIVE_3D_STENCIL_BACK_OP_ZFAIL 0x00001388 +#define NV50_TCL_PRIMITIVE_3D_STENCIL_BACK_OP_ZPASS 0x0000138c +#define NV50_TCL_PRIMITIVE_3D_STENCIL_BACK_FUNC_FUNC 0x00001390 +#define NV50_TCL_PRIMITIVE_3D_STENCIL_BACK_FUNC_REF 0x00001394 +#define NV50_TCL_PRIMITIVE_3D_STENCIL_BACK_MASK 0x00001398 +#define NV50_TCL_PRIMITIVE_3D_STENCIL_BACK_FUNC_MASK 0x0000139c +#define NV50_TCL_PRIMITIVE_3D_LINE_WIDTH 0x000013b0 +#define NV50_TCL_PRIMITIVE_3D_POINT_SIZE 0x00001518 +#define NV50_TCL_PRIMITIVE_3D_POLYGON_OFFSET_FACTOR 0x0000156c +#define NV50_TCL_PRIMITIVE_3D_LINE_SMOOTH_ENABLE 0x00001570 +#define NV50_TCL_PRIMITIVE_3D_STENCIL_FRONT_ENABLE 0x00001594 +#define NV50_TCL_PRIMITIVE_3D_STENCIL_FRONT_OP_FAIL 0x00001598 +#define NV50_TCL_PRIMITIVE_3D_STENCIL_FRONT_OP_ZFAIL 0x0000159c +#define NV50_TCL_PRIMITIVE_3D_STENCIL_FRONT_OP_ZPASS 0x000015a0 +#define NV50_TCL_PRIMITIVE_3D_STENCIL_FRONT_FUNC_FUNC 0x000015a4 +#define NV50_TCL_PRIMITIVE_3D_POLYGON_OFFSET_UNITS 0x000015bc +#define NV50_TCL_PRIMITIVE_3D_VERTEX_BEGIN 0x000015dc +#define NV50_TCL_PRIMITIVE_3D_VERTEX_END 0x000015e0 +#define NV50_TCL_PRIMITIVE_3D_VERTEX_DATA 0x00001640 +#define NV50_TCL_PRIMITIVE_3D_LINE_STIPPLE_ENABLE 0x0000166c +#define NV50_TCL_PRIMITIVE_3D_LINE_STIPPLE_PATTERN 0x00001680 +#define NV50_TCL_PRIMITIVE_3D_POLYGON_STIPPLE_ENABLE 0x0000168c +#define NV50_TCL_PRIMITIVE_3D_POLYGON_STIPPLE_PATTERN(n) (0x00001700+(n<<2)) +#define NV50_TCL_PRIMITIVE_3D_POLYGON_STIPPLE_PATTERN__SIZE 32 +#define NV50_TCL_PRIMITIVE_3D_CULL_FACE_ENABLE 0x00001918 +#define NV50_TCL_PRIMITIVE_3D_FRONT_FACE 0x0000191c +#define NV50_TCL_PRIMITIVE_3D_CULL_FACE 0x00001920 +#define NV50_TCL_PRIMITIVE_3D_LOGIC_OP_ENABLE 0x000019c4 +#define NV50_TCL_PRIMITIVE_3D_LOGIC_OP_OP 0x000019c8 +#define NV50_TCL_PRIMITIVE_3D_CLEAR_BUFFERS 0x000019d0 +#define NV50_TCL_PRIMITIVE_3D_COLOR_MASK(n) (0x00001a00+(n<<2)) +#define NV50_TCL_PRIMITIVE_3D_COLOR_MASK__SIZE 8 diff --git a/src/libXFX/PBKit/outer.h b/src/libXFX/PBKit/outer.h new file mode 100644 index 0000000..28f69cf --- /dev/null +++ b/src/libXFX/PBKit/outer.h @@ -0,0 +1,524 @@ +//based on nv10reg.h (rules) file + +//this part already exists in openxdk hal/video.h header (openxdk header) + +//outer GPU registers base address +#define VIDEO_BASE 0xFD000000 + +//Access macros (volatile means C optimizer must not consider useless to read again Ram) +#define VIDEOREG(x) (*(volatile unsigned int*)(VIDEO_BASE + (x))) +#define VIDEOREG16(x) (*(volatile unsigned short*)(VIDEO_BASE + (x))) +#define VIDEOREG8(x) (*(volatile unsigned char*)(VIDEO_BASE + (x))) + +// Registers relative addresses and associated encoding constants +#define PCIO_CRTC_STATUS 0x006013DA + +#define PCRTC_START 0x00600800 +#define PCRTC_INTR 0x00600100 +#define PCRTC_INTR_VBLANK_RESET 0x00000001 + +#define PCRTC_INTR_EN 0x00600140 +#define PCRTC_INTR_EN_VBLANK_DISABLED 0x00000000 +#define PCRTC_INTR_EN_VBLANK_ENABLED 0x00000001 + +#define NV_PMC_INTR_EN_0 0x00000140 +#define NV_PMC_INTR_EN_0_INTA_DISABLED 0x00000000 +#define NV_PMC_INTR_EN_0_INTA_HARDWARE 0x00000001 +#define NV_PMC_INTR_EN_0_INTA_SOFTWARE 0x00000002 + + +//this part is new and doesn't exist in hal/video.h yet, and is not coming from "rules" + +//additional needed registers +#define NV_PBUS_ROM_VERSION 0x00001218 +#define NV_PBUS_ROM_VERSION_MASK 0x00000100 + +#define NV_PFB_WC_CACHE 0x00100410 +#define NV_PFB_WC_CACHE_FLUSH_TRIGGER 0x00010000 +#define NV_PFB_WC_CACHE_FLUSH_IN_PROGRESS 0x00010000 + +#define NV_PGRAPH_UNKNOWN_400098 0x00400098 +#define NV_PGRAPH_UNKNOWN_40009C 0x0040009C + +//these two ones are different from nv10reg.h +#define NV_PGRAPH_CHANNEL_CTX_POINTER 0x00400784 +#define NV_PGRAPH_CHANNEL_CTX_POINTER_INST 0x0000FFFF + +#define NV_PGRAPH_CHANNEL_CTX_STATUS 0x00400788 +#define NV_PGRAPH_CHANNEL_CTX_STATUS_LOADED 1 +#define NV_PGRAPH_CHANNEL_CTX_STATUS_UNLOADED 2 + +#define NV_PGRAPH_DEBUG_7 0x00400880 +#define NV_PGRAPH_DEBUG_7_UNKNOWN_OPTIONS 0x0008CFFF + +#define NV_PGRAPH_TILE_XBOX 0x00400900 +#define NV_PGRAPH_TLIMIT_XBOX 0x00400904 +#define NV_PGRAPH_TSIZE_XBOX 0x00400908 +#define NV_PGRAPH_ZCOMP_XBOX 0x00400980 +#define NV_PGRAPH_ZCOMP_OFFSET_XBOX 0x004009A0 +#define NV_PGRAPH_CFG0_XBOX 0x004009A4 +#define NV_PGRAPH_CFG1_XBOX 0x004009A8 + +#define NV_PGRAPH_UNKNOWN_400B80 0x00400B80 +#define NV_PGRAPH_UNKNOWN_400B84 0x00400B84 +#define NV_PGRAPH_UNKNOWN_400B88 0x00400B88 + +#define NV_PGRAPH_PARAMETER_A 0x00401A88 +#define NV_PGRAPH_PARAMETER_B 0x0040186C + + +//already known registers (coming from rules - nv10reg.h) +#define NV_PMC_INTR_0 0x00000100 +#define NV_PMC_INTR_0_NOT_PENDING 0 +#define NV_PMC_INTR_0_MD_PENDING 0x00000001 +#define NV_PMC_INTR_0_PMEDIA_PENDING 0x00000010 +#define NV_PMC_INTR_0_PFIFO_PENDING 0x00000100 +#define NV_PMC_INTR_0_PGRAPH_PENDING 0x00001000 +#define NV_PMC_INTR_0_PVIDEO_PENDING 0x00010000 +#define NV_PMC_INTR_0_PTIMER_PENDING 0x00100000 +#define NV_PMC_INTR_0_PCRTC_PENDING 0x01000000 + +#define NV_PMC_ENABLE 0x00000200 +#define NV_PMC_ENABLE_ALL_ENABLE 0xFFFFFFFF +#define NV_PMC_ENABLE_ALL_DISABLE 0 +#define NV_PMC_ENABLE_PGRAPH_DISABLED 0xFFFFEFFF +#define NV_PMC_ENABLE_PGRAPH_ENABLED 0x00001000 + +#define NV_PBUS_PCI_NV_0 0x00001800 +#define NV_CONFIG_PCI_NV_0_DEVICE_ID 0xFFFC0000 + +#define NV_PBUS_PCI_NV_1 0x00001804 +#define NV_PBUS_PCI_NV_1_BUS_MASTER_ENABLED 4 + +#define NV_PBUS_PCI_NV_2 0x00001808 +#define NV_PBUS_PCI_NV_2_REVISION_ID 0x000000FF + +#define NV_PBUS_PCI_NV_3 0x0000180C +#define NV_PBUS_PCI_NV_3_LATENCY_TIMER_248_CLOCKS 0x0000F800 + +#define NV_PBUS_PCI_NV_12 0x00001830 +#define NV_PBUS_PCI_NV_12_ROM_DECODE_DISABLED 0 + +#define NV_PBUS_PCI_NV_19 0x0000184C +#define NV_PBUS_PCI_NV_19_AGP_COMMAND_SBA_ENABLE_OFF 0xFFFFFDFF +#define NV_PBUS_PCI_NV_19_AGP_COMMAND_AGP_ENABLE_OFF 0xFFFFFEFF + +#define NV_PFIFO_DELAY_0 0x00002040 +#define NV_PFIFO_DELAY_0_WAIT_RETRY 0x000003FF + +#define NV_PFIFO_DMA_TIMESLICE 0x00002044 +#define NV_PFIFO_DMA_TIMESLICE_SELECT_128K 0x0001FFFF +#define NV_PFIFO_DMA_TIMESLICE_TIMEOUT_ENABLED 0x01000000 +#define NV_PFIFO_DMA_TIMESLICE_ALL_DISABLE 0 + +#define NV_PFIFO_TIMESLICE 0x0000204C +#define NV_PFIFO_TIMESLICE_TIMER_EXPIRED 0x001FFFFF + +#define NV_PFIFO_DEBUG_0 0x00002080 +#define NV_PFIFO_DEBUG_0_CACHE_ERROR0_PENDING 0x00000001 + +#define NV_PFIFO_INTR_0 0x00002100 +#define NV_PFIFO_INTR_0_NOT_PENDING 0 +#define NV_PFIFO_INTR_0_CACHE_ERROR_PENDING 0x00000001 +#define NV_PFIFO_INTR_0_CACHE_ERROR_RESET 0x00000001 +#define NV_PFIFO_INTR_0_RUNOUT_PENDING 0x00000010 +#define NV_PFIFO_INTR_0_RUNOUT_OVERFLOW_PENDING 0x00000100 +#define NV_PFIFO_INTR_0_DMA_PUSHER_PENDING 0x00001000 +#define NV_PFIFO_INTR_0_DMA_PUSHER_RESET 0x00001000 +#define NV_PFIFO_INTR_0_DMA_PT_PENDING 0x00010000 +#define NV_PFIFO_INTR_0_DMA_PT_RESET 0x00010000 +#define NV_PFIFO_INTR_0_SEMAPHORE_PENDING 0x00100000 +#define NV_PFIFO_INTR_0_SEMAPHORE_RESET 0x00100000 +#define NV_PFIFO_INTR_0_ACQUIRE_TIMEOUT_PENDING 0x01000000 +#define NV_PFIFO_INTR_0_ACQUIRE_TIMEOUT_RESET 0x01000000 +#define NV_PFIFO_INTR_0_ALL_RESET 0xFFFFFFFF + +#define NV_PFIFO_INTR_EN_0 0x00002140 +#define NV_PFIFO_INTR_EN_0_ALL_DISABLE 0 +#define NV_PFIFO_INTR_EN_0_ALL_ENABLE 0x01111111 + +#define NV_PFIFO_RAMHT 0x00002210 +#define NV_PFIFO_RAMHT_BASE_ADDRESS 0x000001F0 +#define NV_PFIFO_RAMHT_BASE_ADDRESS_10000 0x00000100 +#define NV_PFIFO_RAMHT_SEARCH_128 0x03000000 + +#define NV_PFIFO_RAMFC 0x00002214 +#define NV_PFIFO_RAMFC_BASE_ADDRESS 0x000001FC +#define NV_PFIFO_RAMFC_BASE_ADDRESS_11000 0x00000110 + +#define NV_PFIFO_RUNOUT_STATUS 0x00002400 +#define NV_PFIFO_RUNOUT_STATUS_LOW_MARK_EMPTY 0x00000010 + +#define NV_PFIFO_RUNOUT_PUT 0x00002410 +#define NV_PFIFO_RUNOUT_PUT_ADDRESS 0x00001FF8 + +#define NV_PFIFO_RUNOUT_GET 0x00002420 +#define NV_PFIFO_RUNOUT_GET_ADDRESS 0x00003FF8 + +#define NV_PFIFO_CACHES 0x00002500 +#define NV_PFIFO_CACHES_ALL_DISABLE 0 +#define NV_PFIFO_CACHES_REASSIGN_ENABLED 0x00000001 +#define NV_PFIFO_CACHES_DMA_SUSPEND_BUSY 0x00000010 + +#define NV_PFIFO_MODE 0x00002504 +#define NV_PFIFO_MODE_ALL_PIO 0 + +#define NV_PFIFO_DMA 0x00002508 +#define NV_PFIFO_DMA_NOT_PENDING 0 + +#define NV_PFIFO_SIZE 0x0000250C + +#define NV_PFIFO_CACHE0_PUSH0 0x00003000 +#define NV_PFIFO_CACHE0_PUSH0_ACCESS_DISABLE 0 + +#define NV_PFIFO_CACHE0_PULL0 0x00003050 +#define NV_PFIFO_CACHE0_PULL0_ACCESS_DISABLE 0 + +#define NV_PFIFO_CACHE0_HASH 0x00003058 +#define NV_PFIFO_CACHE0_HASH_INSTANCE 0x0000FFFF +#define NV_PFIFO_CACHE0_HASH_VALID 0x00010000 + +#define NV_PFIFO_CACHE1_PUSH0 0x00003200 +#define NV_PFIFO_CACHE1_PUSH0_ACCESS_DISABLE 0 +#define NV_PFIFO_CACHE1_PUSH0_ACCESS_ENABLE 0x00000001 + +#define NV_PFIFO_CACHE1_PUSH1 0x00003204 +#define NV_PFIFO_CACHE1_PUSH1_CHID 0x0000001F +#define NV_PFIFO_CACHE1_PUSH1_MODE_DMA 0x00000100 + +#define NV_PFIFO_CACHE1_PUT 0x00003210 +#define NV_PFIFO_CACHE1_PUT_ADDRESS 0x000003FC + +#define NV_PFIFO_CACHE1_STATUS 0x00003214 +#define NV_PFIFO_CACHE1_STATUS_LOW_MARK_EMPTY 0x00000010 + +#define NV_PFIFO_CACHE1_DMA_PUSH 0x00003220 +#define NV_PFIFO_CACHE1_DMA_PUSH_ACCESS_DISABLE 0 +#define NV_PFIFO_CACHE1_DMA_PUSH_ACCESS_ENABLE 0x00000001 +#define NV_PFIFO_CACHE1_DMA_PUSH_STATE_BUSY 0x00000010 +#define NV_PFIFO_CACHE1_DMA_PUSH_STATUS_RUNNING 0xFFFFEFFF + +#define NV_PFIFO_CACHE1_DMA_FETCH 0x00003224 +#define NV_PFIFO_CACHE1_DMA_FETCH_TRIG 0x000000F8 +#define NV_PFIFO_CACHE1_DMA_FETCH_TRIG_128_BYTES 0x00000078 +#define NV_PFIFO_CACHE1_DMA_FETCH_SIZE 0x0000E000 +#define NV_PFIFO_CACHE1_DMA_FETCH_SIZE_32_BYTES 0x00000000 +#define NV_PFIFO_CACHE1_DMA_FETCH_MAX_REQS 0x001F0000 +#define NV_PFIFO_CACHE1_DMA_FETCH_MAX_REQS_15 0x000F0000 + +#define NV_PFIFO_CACHE1_DMA_STATE 0x00003228 +#define NV_PFIFO_CACHE1_DMA_STATE_METHOD_COUNT_0 0x00000000 + +#define NV_PFIFO_CACHE1_DMA_INSTANCE 0x0000322C +#define NV_PFIFO_CACHE1_DMA_INSTANCE_ADDRESS 0x0000FFFF + +#define NV_PFIFO_CACHE1_DMA_CTL 0x00003230 +#define NV_PFIFO_CACHE1_DMA_CTL_ALL_DISABLE 0 + +#define NV_PFIFO_CACHE1_DMA_PUT 0x00003240 +#define NV_PFIFO_CACHE1_DMA_PUT_OFFSET 0x1FFFFFFC + +#define NV_PFIFO_CACHE1_DMA_GET 0x00003244 +#define NV_PFIFO_CACHE1_DMA_GET_OFFSET 0x1FFFFFFC + +#define NV_PFIFO_CACHE1_REF 0x00003248 +#define NV_PFIFO_CACHE1_REF_CNT 0xFFFFFFFF + +#define NV_PFIFO_CACHE1_DMA_SUBROUTINE 0x0000324C +#define NV_PFIFO_CACHE1_DMA_SUBROUTINE_STATE_ACTIVE 0x00000001 +#define NV_PFIFO_CACHE1_DMA_SUBROUTINE_RETURN_OFFSET 0x0FFFFFFC + +#define NV_PFIFO_CACHE1_PULL0 0x00003250 +#define NV_PFIFO_CACHE1_PULL0_ACCESS_DISABLE 0 +#define NV_PFIFO_CACHE1_PULL0_ACCESS_ENABLE 0x00000001 +#define NV_PFIFO_CACHE1_PULL0_HASH_FAILED 0x00000010 +#define NV_PFIFO_CACHE1_PULL0_DEVICE_SOFTWARE 0x00000100 +#define NV_PFIFO_CACHE1_PULL0_HASH_STATE_BUSY 0x00001000 + +#define NV_PFIFO_CACHE1_PULL1 0x00003254 + +#define NV_PFIFO_CACHE1_HASH 0x00003258 +#define NV_PFIFO_CACHE1_HASH_INSTANCE 0x0000FFFF +#define NV_PFIFO_CACHE1_HASH_VALID 0x00010000 + +#define NV_PFIFO_CACHE1_ACQUIRE_0 0x00003260 +#define NV_PFIFO_CACHE1_ACQUIRE_0_TIMEOUT 0xFFFFFFFF + +#define NV_PFIFO_CACHE1_ACQUIRE_1 0x00003264 +#define NV_PFIFO_CACHE1_ACQUIRE_1_TIMESTAMP 0xFFFFFFFF + +#define NV_PFIFO_CACHE1_ACQUIRE_2 0x00003268 +#define NV_PFIFO_CACHE1_ACQUIRE_2_VALUE 0x7FFFFFFF + +#define NV_PFIFO_CACHE1_SEMAPHORE 0x0000326C +#define NV_PFIFO_CACHE1_SEMAPHORE_CTXDMA_VALID 0x00000001 +#define NV_PFIFO_CACHE1_SEMAPHORE_OFFSET 0x00000FFC +#define NV_PFIFO_CACHE1_SEMAPHORE_PAGE_ADDRESS 0xFFFFF000 + +#define NV_PFIFO_CACHE1_GET 0x00003270 +#define NV_PFIFO_CACHE1_GET_ADDRESS 0x000003FC + +#define NV_PFIFO_CACHE1_ENGINE 0x00003280 +#define NV_PFIFO_CACHE1_ENGINE_ALL_SW 0 + +#define NV_PVIDEO_DEBUG_2 0x00008088 +#define NV_PVIDEO_DEBUG_2_BURST1_CLEAR 0xFFFFF43F +#define NV_PVIDEO_DEBUG_2_BURST1_INIT 0x00000400 +#define NV_PVIDEO_DEBUG_2_BURST2_CLEAR 0xF43FFFFF +#define NV_PVIDEO_DEBUG_2_BURST2_INIT 0x04000000 + +#define NV_PVIDEO_DEBUG_3 0x0000808C +#define NV_PVIDEO_DEBUG_3_WATER_MARK1_CLEAR 0xFFFFF40F +#define NV_PVIDEO_DEBUG_3_WATER_MARK1_INIT 0x00000400 +#define NV_PVIDEO_DEBUG_3_WATER_MARK2_CLEAR 0xF40FFFFF +#define NV_PVIDEO_DEBUG_3_WATER_MARK2_INIT 0x04000000 + +#define NV_PVIDEO_INTR 0x00008100 +#define NV_PVIDEO_INTR_BUFFER_0_PENDING 0x00000001 +#define NV_PVIDEO_INTR_BUFFER_0_RESET 0x00000001 + +#define NV_PVIDEO_LUMINANCE_0 0x00008910 +#define NV_PVIDEO_LUMINANCE_1 0x00008914 +#define NV_PVIDEO_LUMINANCE_CONTRAST_UNITY 0x00001000 +#define NV_PVIDEO_LUMINANCE_BRIGHTNESS_UNITY 0x00000000 + +#define NV_PVIDEO_CHROMINANCE_0 0x00008918 +#define NV_PVIDEO_CHROMINANCE_1 0x0000891C +#define NV_PVIDEO_CHROMINANCE_SAT_COS_UNITY 0x00001000 +#define NV_PVIDEO_CHROMINANCE_SAT_SIN_UNITY 0x00000000 + +#define NV_PVIDEO_OFFSET_0 0x00008920 +#define NV_PVIDEO_OFFSET_1 0x00008924 +#define NV_PVIDEO_OFFSET_VALUE_ZERO 0x00000000 + +#define NV_PVIDEO_SIZE_IN_0 0x00008928 +#define NV_PVIDEO_SIZE_IN_1 0x0000892C +#define NV_PVIDEO_SIZE_IN_UNKNOWN_WIDTH 0x0000FFFF +#define NV_PVIDEO_SIZE_IN_UNKNOWN_HEIGHT 0xFFFF0000 + +#define NV_PVIDEO_POINT_IN_0 0x00008930 +#define NV_PVIDEO_POINT_IN_1 0x00008934 +#define NV_PVIDEO_POINT_IN_S_ORIGIN 0x00000000 +#define NV_PVIDEO_POINT_IN_T_ORIGIN 0x00000000 + +#define NV_PVIDEO_DS_DX_0 0x00008938 +#define NV_PVIDEO_DS_DX_1 0x0000893C +#define NV_PVIDEO_DS_DX_RATIO_UNITY 0x00100000 + +#define NV_PVIDEO_DT_DY_0 0x00008940 +#define NV_PVIDEO_DT_DY_1 0x00008944 +#define NV_PVIDEO_DT_DY_RATIO_UNITY 0x00100000 + +#define NV_PTIMER_INTR_0 0x00009100 +#define NV_PTIMER_INTR_0_ALARM_NOT_PENDING 0 +#define NV_PTIMER_INTR_0_ALARM_RESET 0x00000001 + +#define NV_PTIMER_INTR_EN_0 0x00009140 +#define NV_PTIMER_INTR_EN_0_ALARM_DISABLED 0 + +#define NV_PTIMER_NUMERATOR 0x00009200 + +#define NV_PTIMER_DENOMINATOR 0x00009210 + +#define NV_PTIMER_TIME_0 0x00009400 + +#define NV_PTIMER_TIME_1 0x00009410 + +#define NV_PTIMER_ALARM_0 0x00009420 + +#define NV_PFB_CFG0 0x00100200 +#define NV_PFB_CFG0_PART_3 0x00000003 + +#define NV_PFB_CFG1 0x00100204 + +#define NV_PFB_FIFO_DATA 0x0010020C + +#define NV_PFB_NVM 0x00100214 +#define NV_PFB_NVM_MODE_DISABLE 0xFFFFFFFE +#define NV_PFB_NVM_MODE_ENABLE 0x00000001 + +#define NV_PFB_TILE 0x00100240 + +#define NV_PFB_TLIMIT 0x00100244 + +#define NV_PFB_TSIZE 0x00100248 + +#define NV_PFB_ZCOMP 0x00100300 + +#define NV_PFB_ZCOMP_OFFSET 0x00100324 + +#define NV_PGRAPH_DEBUG_0 0x00400080 +#define NV_PGRAPH_DEBUG_0_NO_RESET 0 +#define NV_PGRAPH_DEBUG_0_IDX_STATE_RESET 0x00010000 +#define NV_PGRAPH_DEBUG_0_VTX_STATE_RESET 0x00020000 +#define NV_PGRAPH_DEBUG_0_CAS_STATE_RESET 0x00040000 + +#define NV_PGRAPH_DEBUG_1 0x00400084 +#define NV_PGRAPH_DEBUG_1_VTX_PTE_ENABLED 0x00000100 +#define NV_PGRAPH_DEBUG_1_VTX_CACHE_ENABLED 0x00000200 +#define NV_PGRAPH_DEBUG_1_VTX_FILE_ENABLED 0x00000400 +#define NV_PGRAPH_DEBUG_1_DRAWDIR_Y_INCR 0x00008000 +#define NV_PGRAPH_DEBUG_1_INSTANCE_ENABLED 0x00010000 +#define NV_PGRAPH_DEBUG_1_CTX_ENABLED 0x00100000 +#define NV_PGRAPH_DEBUG_1_CACHE_INVALIDATE 0x01000000 + +#define NV_PGRAPH_DEBUG_3 0x0040008C +#define NV_PGRAPH_DEBUG_3_FLUSHING_ENABLED 0x00000001 +#define NV_PGRAPH_DEBUG_3_SYNC_TO_CRTC_ENABLED 0x00000008 +#define NV_PGRAPH_DEBUG_3_FAST_DATA_STRTCH_ENABLED 0x00000010 +#define NV_PGRAPH_DEBUG_3_FAST_3D_SHADOW_DATA_ENABLED 0x00000020 +#define NV_PGRAPH_DEBUG_3_FAST_DMA_READ_ENABLED 0x00000040 +#define NV_PGRAPH_DEBUG_3_IDLE_FILTER_ENABLED 0x00000400 +#define NV_PGRAPH_DEBUG_3_SINGLE_CYCLE_LOAD_ENABLED 0x00020000 +#define NV_PGRAPH_DEBUG_3_BILINEAR_3D_ENABLED 0x00040000 +#define NV_PGRAPH_DEBUG_3_VOLATILE_RESET_ENABLED 0x00080000 +#define NV_PGRAPH_DEBUG_3_DATA_CHECK_ENABLED 0x00100000 +#define NV_PGRAPH_DEBUG_3_FORMAT_CHECK_ENABLED 0x00400000 +#define NV_PGRAPH_DEBUG_3_DMA_CHECK_ENABLED 0x00800000 +#define NV_PGRAPH_DEBUG_3_STATE_CHECK_ENABLED 0x01000000 +#define NV_PGRAPH_DEBUG_3_IMAGE_64BIT_ENABLED 0x02000000 +#define NV_PGRAPH_DEBUG_3_XFMODE_COALESCE_ENABLED 0x10000000 +#define NV_PGRAPH_DEBUG_3_CTX_METHODS_ENABLED 0x20000000 +#define NV_PGRAPH_DEBUG_3_OP_METHODS_ENABLED 0x40000000 +#define NV_PGRAPH_DEBUG_3_IGNORE_PATCHVALID_ENABLED 0x80000000 + +#define NV_PGRAPH_DEBUG_4 0x00400090 +#define NV_PGRAPH_DEBUG_4_ALL_DISABLE 0 + +#define NV_PGRAPH_DEBUG_5 0x00400094 +#define NV_PGRAPH_DEBUG_5_ZCULL_SPARE2_ENABLED 0x00000004 + +#define NV_PGRAPH_INTR 0x00400100 +#define NV_PGRAPH_INTR_NOT_PENDING 0 +#define NV_PGRAPH_INTR_NOTIFY_PENDING 0x00000001 +#define NV_PGRAPH_INTR_NOTIFY_RESET 0x00000001 +#define NV_PGRAPH_INTR_MISSING_HW_PENDING 0x00000010 +#define NV_PGRAPH_INTR_MISSING_HW_RESET 0x00000010 +#define NV_PGRAPH_INTR_TLB_PRESENT_A_PENDING 0x00000100 +#define NV_PGRAPH_INTR_TLB_PRESENT_B_PENDING 0x00000200 +#define NV_PGRAPH_INTR_CONTEXT_SWITCH_PENDING 0x00001000 +#define NV_PGRAPH_INTR_CONTEXT_SWITCH_RESET 0x00001000 +#define NV_PGRAPH_INTR_BUFFER_NOTIFY_PENDING 0x00010000 +#define NV_PGRAPH_INTR_ERROR_PENDING 0x00100000 +#define NV_PGRAPH_INTR_ERROR_RESET 0x00100000 +#define NV_PGRAPH_INTR_SINGLE_STEP_PENDING 0x01000000 +#define NV_PGRAPH_INTR_SINGLE_STEP_RESET 0x01000000 +#define NV_PGRAPH_INTR_MORE_RESET 0xFFF00000 +#define NV_PGRAPH_INTR_ALL_ENABLE 0xFFFFFFFF + +#define NV_PGRAPH_NSOURCE 0x00400108 +#define NV_PGRAPH_NSOURCE_DATA_ERROR_PENDING 0x00000002 +#define NV_PGRAPH_NSOURCE_PROTECTION_ERROR_PENDING 0x00000004 +#define NV_PGRAPH_NSOURCE_RANGE_EXCEPTION_PENDING 0x00000008 +#define NV_PGRAPH_NSOURCE_LIMIT_COLOR_PENDING 0x00000010 +#define NV_PGRAPH_NSOURCE_LIMIT_ZETA_PENDING 0x00000020 +#define NV_PGRAPH_NSOURCE_ILLEGAL_MTHD_PENDING 0x00000040 +#define NV_PGRAPH_NSOURCE_DMA_R_PROTECTION_PENDING 0x00000080 +#define NV_PGRAPH_NSOURCE_DMA_W_PROTECTION_PENDING 0x00000100 +#define NV_PGRAPH_NSOURCE_FORMAT_EXCEPTION_PENDING 0x00000200 +#define NV_PGRAPH_NSOURCE_PATCH_EXCEPTION_PENDING 0x00000400 +#define NV_PGRAPH_NSOURCE_STATE_INVALID_PENDING 0x00000800 +#define NV_PGRAPH_NSOURCE_DOUBLE_NOTIFY_PENDING 0x00001000 +#define NV_PGRAPH_NSOURCE_NOTIFY_IN_USE_PENDING 0x00002000 +#define NV_PGRAPH_NSOURCE_METHOD_CNT_PENDING 0x00004000 +#define NV_PGRAPH_NSOURCE_BFR_NOTIFICATION_PENDING 0x00008000 +#define NV_PGRAPH_NSOURCE_DMA_VTX_PROTECTION_PENDING 0x00010000 +#define NV_PGRAPH_NSOURCE_IDX_INLINE_REUSE_PENDING 0x00020000 +#define NV_PGRAPH_NSOURCE_INVALID_OPERATION_PENDING 0x00040000 +#define NV_PGRAPH_NSOURCE_FD_INVALID_OPERATION_PENDING 0x00080000 +#define NV_PGRAPH_NSOURCE_TEX_A_PROTECTION_PENDING 0x00400000 +#define NV_PGRAPH_NSOURCE_TEX_B_PROTECTION_PENDING 0x00800000 + +#define NV_PGRAPH_INTR_EN 0x00400140 +#define NV_PGRAPH_INTR_EN_ALL_ENABLE 0xFFFFFFFF + +#define NV_PGRAPH_CTX_CONTROL 0x00400144 +#define NV_PGRAPH_CTX_CONTROL_TIME_NOT_EXPIRED 0x00000100 +#define NV_PGRAPH_CTX_CONTROL_CHID_VALID 0x00010000 +#define NV_PGRAPH_CTX_CONTROL_DEVICE_ENABLED 0x10000000 + +#define NV_PGRAPH_CTX_USER 0x00400148 +#define NV_PGRAPH_CTX_USER_CHID 0x1F000000 + +#define NV_PGRAPH_CTX_SWITCH1 0x0040014C +#define NV_PGRAPH_CTX_SWITCH1_ALL_DISABLE 0 +#define NV_PGRAPH_CTX_SWITCH1_GRCLASS 0x000000FF + +#define NV_PGRAPH_CTX_SWITCH2 0x00400150 +#define NV_PGRAPH_CTX_SWITCH2_ALL_DISABLE 0 + +#define NV_PGRAPH_CTX_SWITCH3 0x00400154 +#define NV_PGRAPH_CTX_SWITCH3_ALL_DISABLE 0 + +#define NV_PGRAPH_CTX_SWITCH4 0x00400158 +#define NV_PGRAPH_CTX_SWITCH4_ALL_DISABLE 0 + +#define NV_PGRAPH_STATUS 0x00400700 +#define NV_PGRAPH_STATUS_NOT_BUSY 0 + +#define NV_PGRAPH_TRAPPED_ADDR 0x00400704 +#define NV_PGRAPH_TRAPPED_ADDR_MTHD 0x00001FFC +#define NV_PGRAPH_TRAPPED_ADDR_CHID 0x01F00000 + +#define NV_PGRAPH_TRAPPED_DATA_LOW 0x00400708 +#define NV_PGRAPH_TRAPPED_DATA_LOW_VALUE 0xFFFFFFFF + +#define NV_PGRAPH_TRAPPED_DATA_HIGH 0x0040070C +#define NV_PGRAPH_TRAPPED_DATA_HIGH_VALUE 0xFFFFFFFF + +#define NV_PGRAPH_INCREMENT 0x0040071C +#define NV_PGRAPH_INCREMENT_READ_3D_TRIGGER 0x00000002 + +#define NV_PGRAPH_FIFO 0x00400720 +#define NV_PGRAPH_FIFO_ACCESS_DISABLE 0 +#define NV_PGRAPH_FIFO_ACCESS_ENABLE 0x00000001 + +#define NV_PGRAPH_RDI_INDEX 0x00400750 //addr +#define NV_PGRAPH_RDI_INDEX_ADDRESS 0x00001FFC +#define NV_PGRAPH_RDI_INDEX_SELECT 0x01FF0000 + +#define NV_PGRAPH_RDI_DATA 0x00400754 //data + +#define NV_PGRAPH_FFINTFC_ST2 0x00400764 +#define NV_PGRAPH_FFINTFC_ST2_CHID_STATUS_VALID 0x08000000 +#define NV_PGRAPH_FFINTFC_ST2_CHSWITCH_CLEAR 0xEFFFFFFF +#define NV_PGRAPH_FFINTFC_ST2_FIFOHOLD_CLEAR 0xDFFFFFFF + +#define NV_PGRAPH_CHANNEL_CTX_TABLE 0x00400780 +#define NV_PGRAPH_CHANNEL_CTX_TABLE_INST 0x0000FFFF + +#define NV_PCRTC_CONFIG 0x00600804 +#define NV_PCRTC_CONFIG_START_ADDRESS 0x00000007 +#define NV_PCRTC_CONFIG_START_ADDRESS_VGA 0x00000000 +#define NV_PCRTC_CONFIG_START_ADDRESS_NON_VGA 0x00000001 +#define NV_PCRTC_CONFIG_START_ADDRESS_HSYNC 0x00000002 + +#define NV_PRMCIO_CRX__COLOR 0x006013D4 //addr +#define NV_PRMCIO_CR__COLOR 0x006013D5 //data + +#define NV_PRAMDAC_NVPLL_COEFF 0x00680500 +#define NV_PRAMDAC_NVPLL_COEFF_MDIV 0x000000FF +#define NV_PRAMDAC_NVPLL_COEFF_NDIV 0x0000FF00 +#define NV_PRAMDAC_NVPLL_COEFF_PDIV 0x00070000 + +#define NV_PRAMDAC_MPLL_COEFF 0x00680504 +#define NV_PRAMDAC_MPLL_COEFF_MDIV 0x000000FF +#define NV_PRAMDAC_MPLL_COEFF_NDIV 0x0000FF00 +#define NV_PRAMDAC_MPLL_COEFF_PDIV 0x00070000 + +#define NV_PRAMDAC_VPLL_COEFF 0x00680508 +#define NV_PRAMDAC_VPLL_COEFF_MDIV 0x000000FF +#define NV_PRAMDAC_VPLL_COEFF_NDIV 0x0000FF00 +#define NV_PRAMDAC_VPLL_COEFF_PDIV 0x00070000 + +#define NV_USER_DAC_WRITE_MODE_ADDRESS 0x006813C8 +#define NV_USER_DAC_WRITE_MODE_ADDRESS_VALUE 0x000000FF + +#define NV_USER_DAC_PALETTE_DATA 0x006813C9 +#define NV_USER_DAC_PALETTE_DATA_VALUE 0x000000FF + +#define NV_PRAMIN 0x00700000 + +#define NV_USER 0x00800000 + + diff --git a/src/libXFX/PBKit/pbKit.cpp b/src/libXFX/PBKit/pbKit.cpp new file mode 100644 index 0000000..dc89069 --- /dev/null +++ b/src/libXFX/PBKit/pbKit.cpp @@ -0,0 +1,5224 @@ +//pbKit core functions +//see AFL license + +//#define DBG +//#define LOG +extern "C"{ +#include +#include +#include +#include +#include +} + +#include "pbKit.h" +#include "outer.h" +#include "nv_objects.h" //shared with renouveau files +#include "nv20_shader.h" //(search "nouveau" on wiki) + + + +#include +#include +#include +#include + + + + + +#define INSTANCE_MEM_MAXSIZE 0x5000 //20Kb + +#define ADDR_SYSMEM 1 +#define ADDR_FBMEM 2 +#define ADDR_AGPMEM 3 + +#define DMA_CLASS_2 2 +#define DMA_CLASS_3 3 +#define DMA_CLASS_3D 0x3D + +#define GR_CLASS_30 0x30 +#define GR_CLASS_39 0x39 +#define GR_CLASS_62 0x62 +#define GR_CLASS_97 0x97 +#define GR_CLASS_9F 0x9F + +#define GPU_IRQ 3 + +#define XTAL_16MHZ 16.6667f +#define DW_XTAL_16MHZ 16666666 + +#define MAX_EXTRA_BUFFERS 8 + +#define MAXRAM 0x03FFAFFF + +#define NONE -1 + +#define TICKSTIMEOUT 100 //if Dma doesn't react in that time, send a warning + +#define PB_SETOUTER 0xB2A +#define PB_SETNOISE 0xBAA +#define PB_FINISHED 0xFAB + +struct s_CtxDma +{ + DWORD ChannelID; + DWORD Inst; //Addr in PRAMIN area, unit=16 bytes blocks, baseaddr=VIDEO_BASE+NV_PRAMIN + DWORD Class; + DWORD isGr; +}; + + +struct s_PseudoReg +{ + int reg; + int num; + union { + int msk; + int swz; + }; + int mod; + int idx; +}; + +struct s_PseudoRegs +{ + int n; + struct s_PseudoReg dest; + struct s_PseudoReg src0; + struct s_PseudoReg src1; + struct s_PseudoReg src2; +}; + + +static int pb_running=0; + +static DWORD pb_vbl_counter=0; + +#ifdef DBG +static int pb_trace_mode=1; +#else +static int pb_trace_mode=0; +#endif + //if set, we wait after each block sending (pb_end) + //so we are sure GPU received all the data (slower) + //and that any GPU error comes from last block sent. + +static int pb_disable_gpu=0; + //if set, prevents GPU from delaying CPU when FIFO is + //full (allows to see how fast CPU code is fast alone) + +static KINTERRUPT pb_InterruptObject; +static KDPC pb_DPCObject; + +static HANDLE pb_VBlankEvent; + +static DWORD pb_OldMCEnable; +static DWORD pb_OldMCInterrupt; +static DWORD pb_OldFBConfig0; +static DWORD pb_OldFBConfig1; +static DWORD pb_OldVideoStart; + +static DWORD *pb_DmaBuffer8; //points at 32 contiguous bytes (Dma Channel ID 8 buffer) +static DWORD *pb_DmaBuffer2; //points at 32 contiguous bytes (Dma Channel ID 2 buffer) +static DWORD *pb_DmaBuffer7; //points at 32 contiguous bytes (Dma Channel ID 7 buffer) + +static DWORD pb_Size=512*1024;//push buffer size, must be >64Kb and a power of 2 +static DWORD *pb_Head; //points at push buffer head +static DWORD *pb_Tail; //points at push buffer tail +static DWORD *pb_Put=NULL; //where next command+params are to be written + +static float pb_CpuFrequency; + +static DWORD pb_GpuInstMem; + +static DWORD pb_PushBase; +static DWORD pb_PushLimit; + +static DWORD pb_FifoHTAddr; +static DWORD pb_FifoFCAddr; +static DWORD pb_FifoU1Addr; + +static DWORD pb_3DGrCtxInst[2]={0,0};//Adress of the two 3D graphic contexts (addr=inst<<4+NV_PRAMIN) +static DWORD pb_GrCtxTableInst; //Adress of the table that points at the two graphic contexts +static DWORD pb_GrCtxInst[2]; //Adress of the two graphic contexts (addr=inst<<4+NV_PRAMIN) +static int pb_GrCtxID; //Current context ID : 0,1 or NONE + +static DWORD pb_FifoBigInst; //graphic contexts are stored there, and much more (addr=inst<<4+NV_PRAMIN) + +static DWORD pb_FreeInst; //next free space in PRAMIN area (addr=inst<<4+NV_PRAMIN) + +static int pb_GammaRampIdx=0; +static int pb_GammaRampbReady[3]={0,0,0}; +static BYTE pb_GammaRamp[3][3][256]; + +static int pb_BackBufferNxt=0; +static int pb_BackBufferNxtVBL=0; +static int pb_BackBufferbReady[3]={0,0,0}; +static int pb_BackBufferIndex[3]; + +static DWORD pb_FifoChannelsReady=0; +static DWORD pb_FifoChannelsMode=NV_PFIFO_MODE_ALL_PIO; +static DWORD pb_FifoChannelID=0; + +static DWORD pb_PutRunSize=0; +static DWORD pb_GetRunSize; + +static DWORD pb_FrameBuffersCount; +static DWORD pb_FrameBuffersWidth; +static DWORD pb_FrameBuffersHeight; +static DWORD pb_FrameBuffersAddr; +static DWORD pb_FrameBuffersPitch; +static DWORD pb_FBAddr[3]; //frame buffers addresses +static DWORD pb_FBSize; //size of 1 buffer +static DWORD pb_FBGlobalSize; //size of all buffers +static DWORD pb_FBVFlag; +static DWORD pb_GPUFrameBuffersFormat;//encoded format for GPU +static DWORD pb_EXAddr[8]; //extra buffers addresses +static DWORD pb_ExtraBuffersCount=0; + +static DWORD pb_DepthStencilAddr; +static DWORD pb_DepthStencilPitch; +static int pb_DepthStencilLast; +static DWORD pb_DSAddr; //depth stencil address +static DWORD pb_DSSize; //size of depth stencil buffer +static DWORD pb_GPUDepthStencilFormat;//encoded format for GPU + +static int pb_front_index; +static int pb_back_index; + +static DWORD pb_Viewport_x; +static DWORD pb_Viewport_y; +static DWORD pb_Viewport_width; +static DWORD pb_Viewport_height; +static DWORD pb_Viewport_zmin; +static DWORD pb_Viewport_zmax; + +static float pb_XScale; +static float pb_YScale; +static float pb_ZScale; +static float pb_GlobalScale; +static float pb_Bias; + +static int pb_debug_screen_active; + +static DWORD pb_DmaChID9Inst; +static DWORD pb_DmaChID10Inst; +static DWORD pb_DmaChID11Inst; + +static DWORD *pb_DmaUserAddr; + +static DWORD pb_PushIndex; +static DWORD *pb_PushStart; +static DWORD *pb_PushNext; + +static int pb_BeginEndPair=0; + +static float pb_FixedPipelineConstants[12]={ + 0.0f, 0.5f, 1.0f, 2.0f, + -1.0f, 0.0f, 1.0f, 2.0f, + 0.0f, 0.0f, -1.0f, 0.0f }; + +static float pb_IdentityMatrix[16]={ + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f }; + +static DWORD pb_TilePitches[16]={ + 0x0200,0x0400,0x0600,0x0800, + 0x0A00,0x0C00,0x0E00,0x1000, + 0x1400,0x1800,0x1C00,0x2800, + 0x3000,0x3800,0x5000,0x7000 }; + +static float pb_BiasTable[7]={ + 0.0f, + 0.585f, + 1.0f, + 1.322f, + 1.585f, + 1.907f, + 2.0f }; + + //temporary storage for pb_pcode2mcode() +static DWORD pb_gpu_programnc[136*5+192*7+8];//vertex shader micro-code setup (max:136 instructions + 192 constants) +static DWORD pb_gpu_registers[6*8+7];//pixel shader registers values +static int pb_tmp_registers[16];//some vertex shader macros need to find free temp registers +static int pb_exp_constflag; +static int pb_log_constflag; + +//forward references +static void pb_load_gr_ctx(int ctx_id); + + +//private pb_text_screen functions + +#define ROWS 16 +#define COLS 60 + +static char pb_text_screen[ROWS][COLS]; + +static int pb_next_row=0; +static int pb_next_col=0; + +static unsigned char systemFont[] = +{ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,56,56,56,56,56,0,56,56, + 108,108,0,0,0,0,0,0,0,108,254,254,108,254,254,108, + 48,126,224,124,14,254,252,48,98,230,204,24,48,102,206,140, + 120,220,252,120,250,222,252,118,28,28,56,0,0,0,0,0, + 14,28,28,28,28,28,28,14,112,56,56,56,56,56,56,112, + 0,0,0,230,124,56,124,206,0,0,28,28,127,127,28,28, + 0,0,0,0,0,28,28,56,0,0,0,0,124,124,0,0, + 0,0,0,0,0,0,56,56,28,28,56,56,112,112,224,224, + 124,254,238,238,238,254,254,124,56,120,248,56,56,254,254,254, + 252,254,14,60,112,254,254,254,252,254,14,60,14,254,254,252, + 238,238,238,254,254,14,14,14,254,254,224,252,14,254,254,252, + 124,252,224,252,238,254,254,124,252,254,14,14,28,28,56,56, + 124,254,238,124,238,254,254,124,124,254,238,126,14,254,254,252, + 0,0,28,28,0,28,28,28,0,0,28,28,0,28,28,56, + 6,14,28,56,56,28,14,6,0,0,124,124,0,124,124,124, + 112,56,28,14,14,28,56,112,124,254,206,28,56,0,56,56, + 124,198,190,182,190,182,200,126,124,254,238,254,238,238,238,238, + 252,254,206,252,206,254,254,252,124,254,238,224,238,254,254,124, + 252,254,238,238,238,254,254,252,254,254,224,248,224,254,254,254, + 126,254,224,248,224,224,224,224,126,254,224,238,238,254,254,124, + 238,238,238,254,238,238,238,238,254,254,56,56,56,254,254,254, + 254,254,14,14,238,254,254,124,238,238,252,248,252,238,238,238, + 224,224,224,224,224,254,254,126,130,198,238,254,254,238,238,238, + 206,238,254,254,254,254,238,230,124,254,238,238,238,254,254,124, + 252,254,238,238,252,224,224,224,124,254,238,238,254,254,252,118, + 252,254,238,238,252,238,238,238,126,254,224,124,14,254,254,252, + 254,254,56,56,56,56,56,56,238,238,238,238,238,254,254,124, + 238,238,238,238,238,238,124,56,238,238,238,254,254,238,198,130, + 238,238,124,56,124,238,238,238,238,238,124,124,56,56,112,112, + 254,254,28,56,112,254,254,254,124,124,112,112,112,124,124,124, + 112,112,56,56,28,28,14,14,124,124,28,28,28,124,124,124, + 56,124,238,198,0,0,0,0,0,0,0,0,0,254,254,254, + 56,56,28,0,0,0,0,0,0,124,254,238,254,238,238,238, + 0,252,254,206,252,206,254,252,0,124,254,238,224,238,254,124, + 0,252,254,238,238,238,254,252,0,254,254,224,248,224,254,254, + 0,126,254,224,248,224,224,224,0,126,254,224,238,238,254,124, + 0,238,238,238,254,238,238,238,0,254,254,56,56,56,254,254, + 0,254,254,14,14,238,254,124,0,238,238,252,248,252,238,238, + 0,224,224,224,224,224,254,126,0,130,198,238,254,254,238,238, + 0,206,238,254,254,254,238,230,0,124,254,238,238,238,254,124, + 0,252,254,238,238,252,224,224,0,124,254,238,238,254,252,118, + 0,252,254,238,238,252,238,238,0,126,254,224,124,14,254,252, + 0,254,254,56,56,56,56,56,0,238,238,238,238,238,254,124, + 0,238,238,238,238,238,124,56,0,238,238,238,254,238,198,130, + 0,238,238,124,56,124,238,238,0,238,238,124,124,56,56,112, + 0,254,254,28,56,112,254,254,60,124,112,112,112,124,124,60, + 56,56,56,0,56,56,56,56,120,124,28,28,28,124,124,120, + 236,254,118,0,0,0,0,0,0,16,56,124,254,254,254,254, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; + + +static void pb_scrollup(void) +{ + int i; + for(i=0;i=ROWS) { pb_next_row=ROWS-1; pb_scrollup(); } + pb_next_col=0; + } + else + if (c=='\r') + { + pb_next_col=0; + } + else + if (c==8) + { + pb_next_col--; + if (pb_next_col<0) pb_next_col=0; + } + else + if (c>=32) + { + pb_text_screen[pb_next_row][pb_next_col]=c; + pb_next_col++; + if (pb_next_col>=COLS) + { + pb_next_row++; + if (pb_next_row>=ROWS) { pb_next_row=ROWS-1; pb_scrollup(); } + pb_next_col=0; + } + } +} + + + +//private functions + +static void pb_set_gamma_ramp(BYTE *pGammaRamp) +{ + int i; + + VIDEOREG8(NV_USER_DAC_WRITE_MODE_ADDRESS)=0; //&NV_USER_DAC_WRITE_MODE_ADDRESS_VALUE + + for(i=0;i<256;i++) + { + VIDEOREG8(NV_USER_DAC_PALETTE_DATA)=pGammaRamp[i]; //&NV_USER_DAC_PALETTE_DATA_VALUE + VIDEOREG8(NV_USER_DAC_PALETTE_DATA)=pGammaRamp[i+256]; //&NV_USER_DAC_PALETTE_DATA_VALUE + VIDEOREG8(NV_USER_DAC_PALETTE_DATA)=pGammaRamp[i+512]; //&NV_USER_DAC_PALETTE_DATA_VALUE + } +} + + + + + +static void pb_vbl_handler(void) +{ + BYTE old_color_addr; //important index to preserve if we are called from Dpc or Isr + + int flag; + int next; + int index; + + old_color_addr=VIDEOREG8(NV_PRMCIO_CRX__COLOR); + + pb_vbl_counter++; + + //Index of next back buffer to show up (0-4) + next=pb_BackBufferNxtVBL; + + //Is the next back buffer to show up is ready? + if (pb_BackBufferbReady[next]==1) + { + //screen swapping has been done already, theoretically, in ISR + pb_BackBufferbReady[next]=0; + + index=pb_GammaRampIdx; + if (pb_GammaRampbReady[index]) + { + pb_set_gamma_ramp(&pb_GammaRamp[index][0][0]); + pb_GammaRampbReady[index]=0; + index=(index+1)%3; + pb_GammaRampIdx=index; + } + + VIDEOREG(NV_PGRAPH_INCREMENT)|=NV_PGRAPH_INCREMENT_READ_3D_TRIGGER; + + //rotate next back buffer & gamma ramp index + next=(next+1)%3; + pb_BackBufferNxtVBL=next; + } + + do + { + VIDEOREG(PCRTC_INTR)=PCRTC_INTR_VBLANK_RESET; + }while(VIDEOREG(NV_PMC_INTR_0)&NV_PMC_INTR_0_PCRTC_PENDING); + + NtPulseEvent(pb_VBlankEvent, NULL); + +// if (UserCallback) UserCallback(); //user callback must be brief and preserve fpu state + + VIDEOREG8(NV_PRMCIO_CRX__COLOR)=old_color_addr; //restore color index +} + + + + + + + +static void pb_cache_flush(void) +{ + __asm__ __volatile__ ("sfence"); + //assembler instruction "sfence" : waits end of previous instructions + + VIDEOREG(NV_PFB_WC_CACHE)|=NV_PFB_WC_CACHE_FLUSH_TRIGGER; + while(VIDEOREG(NV_PFB_WC_CACHE)&NV_PFB_WC_CACHE_FLUSH_IN_PROGRESS) {}; +} + + + + +static void pb_subprog(DWORD subprogID, DWORD paramA, DWORD paramB) +{ + //inner registers 0x1D8C & 0x1D90 match 2 outer registers : + //[0x1D8C]=[NV20_TCL_PRIMITIVE_3D_PARAMETER_A]=VIDEOREG(NV_PGRAPH_PARAMETER_A)=[0xFD401A88] + //[0x1D90]=[NV20_TCL_PRIMITIVE_3D_PARAMETER_B]=VIDEOREG(NV_PGRAPH_PARAMETER_B)=[0xFD40186C] + //so they can be used by a push buffer sequence to set parameters + //before triggering a subprogram by the command 0x0100 which will + //throw an interrupt and have CPU execute its code right here. + + //Here just test the subprogID value and execute your own subprogram + //associated code (avoid using subprogID=0, it seems to be reserved) + + int next; + + switch(subprogID) + { + case PB_SETOUTER: //sets an outer register + VIDEOREG(paramA)=paramB; + break; + + case PB_SETNOISE: //Dxt1NoiseEnable: copy paramA in NV_PGRAPH_RDI(sel 0xE0 adr 0x50 & sel 0xDF adr 0x08) + VIDEOREG(NV_PGRAPH_RDI_INDEX)=((0xE0<<16)&NV_PGRAPH_RDI_INDEX_SELECT)|((0x50)&NV_PGRAPH_RDI_INDEX_ADDRESS); + VIDEOREG(NV_PGRAPH_RDI_DATA)=paramA; + VIDEOREG(NV_PGRAPH_RDI_INDEX)=((0xDF<<16)&NV_PGRAPH_RDI_INDEX_SELECT)|((0x08)&NV_PGRAPH_RDI_INDEX_ADDRESS); + VIDEOREG(NV_PGRAPH_RDI_DATA)=paramA; + break; + + case PB_FINISHED: //warns that all drawing has been finished for the frame + next=pb_BackBufferNxt; + pb_BackBufferIndex[next]=paramA; + pb_BackBufferbReady[next]=1; + next=(next+1)%3; + pb_BackBufferNxt=next; + break; + + default: + debugPrint( "Unknown subProgID %d has been detected by DPC (A=%x B=%x).\n", + subprogID, + paramA, + paramB ); + break; + } +} + + + +static DWORD pb_gr_handler(void) +{ + DWORD status; + + DWORD trapped_address; + int trapped_ctx_id; + + DWORD nsource; + + DWORD GrClass; + + DWORD DataLow; + + int i; + + DWORD *p; + + VIDEOREG(NV_PGRAPH_FIFO)=NV_PGRAPH_FIFO_ACCESS_DISABLE; + + status=VIDEOREG(NV_PGRAPH_INTR); + trapped_address=VIDEOREG(NV_PGRAPH_TRAPPED_ADDR); + nsource=VIDEOREG(NV_PGRAPH_NSOURCE); + + trapped_ctx_id=(trapped_address&NV_PGRAPH_TRAPPED_ADDR_CHID)>>20; + trapped_address&=NV_PGRAPH_TRAPPED_ADDR_MTHD; + + if (status&NV_PGRAPH_INTR_CONTEXT_SWITCH_PENDING) + { + VIDEOREG(NV_PGRAPH_INTR)=NV_PGRAPH_INTR_CONTEXT_SWITCH_RESET; + + while(VIDEOREG(NV_PGRAPH_STATUS)); + + pb_load_gr_ctx(trapped_ctx_id); + } + + if (status&NV_PGRAPH_INTR_MISSING_HW_PENDING) + { + VIDEOREG(NV_PGRAPH_INTR)=NV_PGRAPH_INTR_MISSING_HW_RESET; + } + + if ( (status&NV_PGRAPH_INTR_NOTIFY_PENDING)|| + (status&NV_PGRAPH_INTR_ERROR_PENDING) ) + { + if (nsource&NV_PGRAPH_NSOURCE_ILLEGAL_MTHD_PENDING) + { + if (status&NV_PGRAPH_INTR_NOTIFY_PENDING) + VIDEOREG(NV_PGRAPH_INTR)= NV_PGRAPH_INTR_NOTIFY_RESET| + NV_PGRAPH_INTR_ERROR_RESET| + NV_PGRAPH_INTR_SINGLE_STEP_RESET| + NV_PGRAPH_INTR_MORE_RESET; + else + VIDEOREG(NV_PGRAPH_INTR)=NV_PGRAPH_INTR_ERROR_RESET; + } + } + + status=VIDEOREG(NV_PGRAPH_INTR); + + if (status) + { + VIDEOREG(NV_PGRAPH_INTR)=NV_PGRAPH_INTR_CONTEXT_SWITCH_RESET; + + if ( (status!=NV_PGRAPH_INTR_CONTEXT_SWITCH_PENDING)&& + (status!=NV_PGRAPH_INTR_SINGLE_STEP_PENDING) ) + { + if (status&NV_PGRAPH_INTR_MISSING_HW_PENDING) + { + while(VIDEOREG(NV_PGRAPH_STATUS)) {}; + } + + if (nsource) + { + if ( (status&NV_PGRAPH_INTR_NOTIFY_PENDING)|| + (status&NV_PGRAPH_INTR_ERROR_PENDING) ) + { + GrClass=VIDEOREG(NV_PGRAPH_CTX_SWITCH1)&NV_PGRAPH_CTX_SWITCH1_GRCLASS; + DataLow=VIDEOREG(NV_PGRAPH_TRAPPED_DATA_LOW); //&NV_PGRAPH_TRAPPED_DATA_LOW_VALUE + + if ((nsource&NV_PGRAPH_NSOURCE_ILLEGAL_MTHD_PENDING)==0) + { + if (trapped_address==0x0100) + { + //The following line may be a bad idea. But without it, interrupt fires permanently... + VIDEOREG(NV_PGRAPH_INTR)=NV_PGRAPH_INTR_ERROR_RESET; + //calls subprogram + pb_subprog(DataLow,VIDEOREG(NV_PGRAPH_PARAMETER_A),VIDEOREG(NV_PGRAPH_PARAMETER_B)); + } + else + { + pb_show_debug_screen(); + + debugPrint("\n"); + if (nsource&NV_PGRAPH_NSOURCE_DATA_ERROR_PENDING) debugPrint("GPU Error : invalid data error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_PROTECTION_ERROR_PENDING) debugPrint("GPU Error : protection error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_RANGE_EXCEPTION_PENDING) debugPrint("GPU Error : range exception error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_LIMIT_COLOR_PENDING) debugPrint("GPU Error : color buffer limit error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_LIMIT_ZETA_PENDING) debugPrint("GPU Error : zeta buffer limit error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_DMA_R_PROTECTION_PENDING) debugPrint("GPU Error : dma read protection error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_DMA_W_PROTECTION_PENDING) debugPrint("GPU Error : dma write protection error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_FORMAT_EXCEPTION_PENDING) debugPrint("GPU Error : format exception error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_PATCH_EXCEPTION_PENDING) debugPrint("GPU Error : patch exception error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_STATE_INVALID_PENDING) debugPrint("GPU Error : object state invalid error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_DOUBLE_NOTIFY_PENDING) debugPrint("GPU Error : double notify error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_NOTIFY_IN_USE_PENDING) debugPrint("GPU Error : notify in use error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_METHOD_CNT_PENDING) debugPrint("GPU Error : method count error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_BFR_NOTIFICATION_PENDING) debugPrint("GPU Error : buffer notification error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_DMA_VTX_PROTECTION_PENDING) debugPrint("GPU Error : DMA vertex protection error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_IDX_INLINE_REUSE_PENDING) debugPrint("Graphics index inline reuse error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_INVALID_OPERATION_PENDING) debugPrint("GPU Error : invalid operation error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_FD_INVALID_OPERATION_PENDING) debugPrint("GPU Error : FD invalid operation error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_TEX_A_PROTECTION_PENDING) debugPrint("GPU Error : texture A protection error!\n"); + if (nsource&NV_PGRAPH_NSOURCE_TEX_B_PROTECTION_PENDING) debugPrint("GPU Error : texture B protection error!\n"); + + debugPrint( "Error binary flags : %08x\n" + "Channel ID : %d (0=3D)\n" + "Channel class : %x\n" + "Push buffer inner register target : %04x\n" + "Push buffer data (lo) or instance : %08x\n" + "Push buffer data (hi) or instance : %08x\n" + "Multi-purpose register A [0x1D8C] : %08x\n" + "Multi-purpose register B [0x1D90] : %08x\n\n", + nsource, + trapped_ctx_id, + GrClass, + trapped_address, + DataLow, + VIDEOREG(NV_PGRAPH_TRAPPED_DATA_HIGH), + VIDEOREG(NV_PGRAPH_PARAMETER_A), + VIDEOREG(NV_PGRAPH_PARAMETER_B) ); + + if (pb_trace_mode==0) debugPrint("Report is accurate only if pb_trace_mode=1 (slower)\n"); + + debugPrint("System halted\n"); + + //calling XReboot() from here doesn't work well. + + while(1) {}; + } + } + } + } + + if (status&NV_PGRAPH_INTR_BUFFER_NOTIFY_PENDING) + { + while (VIDEOREG(NV_PGRAPH_STATUS)) {}; + } + } + } + + VIDEOREG(NV_PGRAPH_FIFO)=NV_PGRAPH_FIFO_ACCESS_ENABLE; + + return VIDEOREG(NV_PGRAPH_INTR); +} + + +static void pb_wait_until_gr_not_busy(void) +{ + DWORD status; + + while(VIDEOREG(NV_PGRAPH_STATUS)!=NV_PGRAPH_STATUS_NOT_BUSY) + { + status=VIDEOREG(NV_PMC_INTR_0); + if (status&NV_PMC_INTR_0_PGRAPH_PENDING) pb_gr_handler(); + if (status&NV_PMC_INTR_0_PCRTC_PENDING) pb_vbl_handler(); + } +} + + + + +static void pb_load_gr_ctx(int ctx_id) +{ + DWORD old_fifo_access; + DWORD dummy; + int i; + + if (VIDEOREG(NV_PGRAPH_INTR)!=NV_PGRAPH_INTR_NOT_PENDING) pb_gr_handler(); + + old_fifo_access=VIDEOREG(NV_PGRAPH_FIFO); + VIDEOREG(NV_PGRAPH_FIFO)=NV_PGRAPH_FIFO_ACCESS_DISABLE; + + pb_wait_until_gr_not_busy(); + + if ((ctx_id!=pb_GrCtxID)&&(ctx_id!=NONE)) + { + VIDEOREG(NV_PGRAPH_CHANNEL_CTX_POINTER)=pb_GrCtxInst[ctx_id]&NV_PGRAPH_CHANNEL_CTX_POINTER_INST; + VIDEOREG(NV_PGRAPH_CHANNEL_CTX_STATUS)=NV_PGRAPH_CHANNEL_CTX_STATUS_UNLOADED; + + pb_wait_until_gr_not_busy(); + + VIDEOREG(NV_PGRAPH_CTX_CONTROL)=NV_PGRAPH_CTX_CONTROL_DEVICE_ENABLED; + } + + pb_GrCtxID=ctx_id; + + if (ctx_id==NONE) + { + VIDEOREG(NV_PGRAPH_CTX_CONTROL)=NV_PGRAPH_CTX_CONTROL_DEVICE_ENABLED|NV_PGRAPH_CTX_CONTROL_TIME_NOT_EXPIRED; + VIDEOREG(NV_PGRAPH_FFINTFC_ST2)=NV_PGRAPH_FFINTFC_ST2_CHID_STATUS_VALID; + + VIDEOREG(NV_PGRAPH_FIFO)=old_fifo_access|NV_PGRAPH_FIFO_ACCESS_ENABLE; + } + else + { + if (pb_3DGrCtxInst[ctx_id]) + { + VIDEOREG(NV_PGRAPH_DEBUG_0) = NV_PGRAPH_DEBUG_0_IDX_STATE_RESET| + NV_PGRAPH_DEBUG_0_VTX_STATE_RESET| + NV_PGRAPH_DEBUG_0_CAS_STATE_RESET; + dummy=VIDEOREG(NV_PGRAPH_DEBUG_0); + VIDEOREG(NV_PGRAPH_DEBUG_0)=NV_PGRAPH_DEBUG_0_NO_RESET; + dummy=VIDEOREG(NV_PGRAPH_DEBUG_0); + + VIDEOREG(NV_PGRAPH_RDI_INDEX)=((0x00)&NV_PGRAPH_RDI_INDEX_ADDRESS)|((0x3D<<16)&NV_PGRAPH_RDI_INDEX_SELECT); + for(i=0;i<15;i++) VIDEOREG(NV_PGRAPH_RDI_DATA)=0; + } + + VIDEOREG(NV_PGRAPH_DEBUG_1)|=NV_PGRAPH_DEBUG_1_CACHE_INVALIDATE; + + VIDEOREG(NV_PGRAPH_CTX_USER)=(ctx_id<<24)&NV_PGRAPH_CTX_USER_CHID; + VIDEOREG(NV_PGRAPH_CHANNEL_CTX_POINTER)=pb_GrCtxInst[ctx_id]&NV_PGRAPH_CHANNEL_CTX_POINTER_INST; + VIDEOREG(NV_PGRAPH_CHANNEL_CTX_STATUS)=NV_PGRAPH_CHANNEL_CTX_STATUS_LOADED; + + pb_wait_until_gr_not_busy(); + + VIDEOREG(NV_PGRAPH_CTX_USER)=(VIDEOREG(NV_PGRAPH_CTX_USER)&~NV_PGRAPH_CTX_USER_CHID)|((ctx_id<<24)&NV_PGRAPH_CTX_USER_CHID); + + VIDEOREG(NV_PGRAPH_CTX_CONTROL) = NV_PGRAPH_CTX_CONTROL_TIME_NOT_EXPIRED| + NV_PGRAPH_CTX_CONTROL_CHID_VALID| + NV_PGRAPH_CTX_CONTROL_DEVICE_ENABLED; + + VIDEOREG(NV_PGRAPH_FFINTFC_ST2)&=(NV_PGRAPH_FFINTFC_ST2_CHSWITCH_CLEAR&NV_PGRAPH_FFINTFC_ST2_FIFOHOLD_CLEAR); + } +} + + + +static DWORD pb_fifo_handler(void) +{ + DWORD i; + DWORD status; + DWORD pull; + DWORD get_address; + int skip_waiting; + + skip_waiting=0; + + status=VIDEOREG(NV_PFIFO_INTR_0); + + if (status&NV_PFIFO_INTR_0_SEMAPHORE_PENDING) + { + VIDEOREG(NV_PFIFO_INTR_0)=NV_PFIFO_INTR_0_SEMAPHORE_RESET; + } + + if (status&NV_PFIFO_INTR_0_ACQUIRE_TIMEOUT_PENDING) + { + VIDEOREG(NV_PFIFO_INTR_0)=NV_PFIFO_INTR_0_ACQUIRE_TIMEOUT_RESET; + } + + status=VIDEOREG(NV_PFIFO_INTR_0); + + if (status&NV_PFIFO_INTR_0_CACHE_ERROR_PENDING) + { + pull=VIDEOREG(NV_PFIFO_CACHE1_PULL0); + get_address=VIDEOREG(NV_PFIFO_CACHE1_GET); //&NV_PFIFO_CACHE1_GET_ADDRESS (0x3FC) + get_address>>=2; + VIDEOREG(NV_PFIFO_CACHES)=NV_PFIFO_CACHES_ALL_DISABLE; + VIDEOREG(NV_PFIFO_CACHE1_PULL0)=NV_PFIFO_CACHE1_PULL0_ACCESS_DISABLE; + VIDEOREG(NV_PFIFO_INTR_0)=NV_PFIFO_INTR_0_CACHE_ERROR_RESET; + + for(i=0;i<65535;i++) + { + if ((pull&NV_PFIFO_CACHE1_PULL0_HASH_STATE_BUSY)==0) break; + pull=VIDEOREG(NV_PFIFO_CACHE1_PULL0); + } + + if ( (pull&NV_PFIFO_CACHE1_PULL0_DEVICE_SOFTWARE)|| + (pull&NV_PFIFO_CACHE1_PULL0_HASH_FAILED) ) + { + VIDEOREG(NV_PFIFO_CACHE1_GET)=((get_address+1)<<2)&NV_PFIFO_CACHE1_GET_ADDRESS; + } + + VIDEOREG(NV_PFIFO_CACHE1_HASH)=0; //&NV_PFIFO_CACHE1_HASH_INSTANCE + VIDEOREG(NV_PFIFO_CACHE1_PULL0)=NV_PFIFO_CACHE1_PULL0_ACCESS_ENABLE; + VIDEOREG(NV_PFIFO_CACHES)=NV_PFIFO_CACHES_REASSIGN_ENABLED; + } + + if (status&NV_PFIFO_INTR_0_DMA_PUSHER_PENDING) + { + pb_show_debug_screen(); + debugPrint("Software Put=%08x\n",pb_Put); + debugPrint("Hardware Put=%08x\n",VIDEOREG(NV_PFIFO_CACHE1_DMA_PUT)); + debugPrint("Hardware Get=%08x\n",VIDEOREG(NV_PFIFO_CACHE1_DMA_GET)); + debugPrint("Dma push buffer engine encountered invalid data at these addresses.\n"); + + VIDEOREG(NV_PFIFO_INTR_0)=NV_PFIFO_INTR_0_DMA_PUSHER_RESET; + VIDEOREG(NV_PFIFO_CACHE1_DMA_STATE)=NV_PFIFO_CACHE1_DMA_STATE_METHOD_COUNT_0; + + if (VIDEOREG(NV_PFIFO_CACHE1_DMA_PUT)!=VIDEOREG(NV_PFIFO_CACHE1_DMA_GET)) + VIDEOREG(NV_PFIFO_CACHE1_DMA_GET)+=(1<<2); + } + + if (status&NV_PFIFO_INTR_0_DMA_PT_PENDING) + { + VIDEOREG(NV_PFIFO_INTR_0)=NV_PFIFO_INTR_0_DMA_PT_RESET; + } + + if (VIDEOREG(NV_PFIFO_CACHE1_DMA_PUSH)&NV_PFIFO_CACHE1_DMA_PUSH_STATE_BUSY) + { + if ((VIDEOREG8(NV_PFIFO_CACHE1_STATUS)&NV_PFIFO_CACHE1_STATUS_LOW_MARK_EMPTY)==0) + do + { + if (VIDEOREG(NV_PFIFO_INTR_0)==NV_PFIFO_INTR_0_NOT_PENDING) + { + if (VIDEOREG(NV_PGRAPH_INTR)) pb_fifo_handler(); + + if (VIDEOREG(NV_PMC_INTR_0)&NV_PMC_INTR_0_PCRTC_PENDING) pb_vbl_handler(); + + if ((VIDEOREG8(NV_PFIFO_CACHE1_STATUS)&NV_PFIFO_CACHE1_STATUS_LOW_MARK_EMPTY)==0) + continue; //jump to loop start + } + + if ((VIDEOREG8(NV_PFIFO_CACHE1_STATUS)&NV_PFIFO_CACHE1_STATUS_LOW_MARK_EMPTY)==0) + { + skip_waiting=1; + break; + } + + }while(VIDEOREG8(NV_PFIFO_CACHE1_STATUS)&NV_PFIFO_CACHE1_STATUS_LOW_MARK_EMPTY); + + if (skip_waiting==0) + { + //wait + while(VIDEOREG8(NV_PFIFO_CACHES)&NV_PFIFO_CACHES_DMA_SUSPEND_BUSY); + VIDEOREG(NV_PFIFO_CACHE1_DMA_PUSH)&=NV_PFIFO_CACHE1_DMA_PUSH_STATUS_RUNNING; + } + } + + if (VIDEOREG(NV_PFIFO_INTR_0)==NV_PFIFO_INTR_0_NOT_PENDING) + { + VIDEOREG(NV_PFIFO_CACHE1_PULL0)=NV_PFIFO_CACHE1_PULL0_ACCESS_ENABLE; + VIDEOREG(NV_PFIFO_CACHES)=NV_PFIFO_CACHES_REASSIGN_ENABLED; + } + + return VIDEOREG(NV_PFIFO_INTR_0)|(VIDEOREG(NV_PFIFO_DEBUG_0)&NV_PFIFO_DEBUG_0_CACHE_ERROR0_PENDING); +} + + +static void pb_set_fifo_channel(int channel) +{ + DWORD old_caches,old_push,old_pull,old_channel; + + DWORD *p; + + DWORD pending_flags; + + old_caches=VIDEOREG(NV_PFIFO_CACHES); + old_push=VIDEOREG(NV_PFIFO_CACHE1_PUSH0); + old_pull=VIDEOREG(NV_PFIFO_CACHE1_PULL0); + VIDEOREG(NV_PFIFO_CACHES)=NV_PFIFO_CACHES_ALL_DISABLE; + VIDEOREG(NV_PFIFO_CACHE1_PUSH0)=NV_PFIFO_CACHE1_PUSH0_ACCESS_DISABLE; + VIDEOREG(NV_PFIFO_CACHE1_PULL0)=NV_PFIFO_CACHE1_PULL0_ACCESS_DISABLE; + + old_channel=VIDEOREG(NV_PFIFO_CACHE1_PUSH1)&NV_PFIFO_CACHE1_PUSH1_CHID; + + //backup old channel details into PRAMIN area + p=(DWORD *)(VIDEO_BASE+pb_FifoFCAddr+old_channel*64); + *(p+0)=VIDEOREG(NV_PFIFO_CACHE1_DMA_PUT); //&NV_PFIFO_CACHE1_DMA_PUT_OFFSET + *(p+1)=VIDEOREG(NV_PFIFO_CACHE1_DMA_GET); //&NV_PFIFO_CACHE1_DMA_GET_OFFSET + *(p+2)=VIDEOREG(NV_PFIFO_CACHE1_REF); //&NV_PFIFO_CACHE1_REF_CNT + *(p+3)=VIDEOREG(NV_PFIFO_CACHE1_DMA_INSTANCE); //&NV_PFIFO_CACHE1_DMA_INSTANCE_ADDRESS + *(p+4)=VIDEOREG(NV_PFIFO_CACHE1_DMA_STATE); + *(p+5)=VIDEOREG(NV_PFIFO_CACHE1_DMA_FETCH); + *(p+6)=VIDEOREG(NV_PFIFO_CACHE1_ENGINE); + *(p+7)=VIDEOREG(NV_PFIFO_CACHE1_PULL1); + *(p+8)=VIDEOREG(NV_PFIFO_CACHE1_ACQUIRE_2); //&NV_PFIFO_CACHE1_ACQUIRE_2_VALUE + *(p+9)=VIDEOREG(NV_PFIFO_CACHE1_ACQUIRE_1); //&NV_PFIFO_CACHE1_ACQUIRE_1_TIMESTAMP + *(p+10)=VIDEOREG(NV_PFIFO_CACHE1_ACQUIRE_0); //&NV_PFIFO_CACHE1_ACQUIRE_0_TIMEOUT + *(p+11)=VIDEOREG(NV_PFIFO_CACHE1_SEMAPHORE); + *(p+12)=VIDEOREG(NV_PFIFO_CACHE1_DMA_SUBROUTINE); + + if (VIDEOREG(NV_PFIFO_CACHE1_PUSH1)&NV_PFIFO_CACHE1_PUSH1_MODE_DMA) + { + pending_flags=VIDEOREG(NV_PFIFO_DMA); + pending_flags&=~(1<>2)|0x80000000; + + if (tile_flags&0x04000000) EncodedZStartTag|=0x04000000; + + //points tile Zcomp in NV_PFB + pZcomp=(DWORD *)(VIDEO_BASE+NV_PFB_ZCOMP+tile_index*4); + + //points tile Zcomp in NV_PGRAPH + p=(DWORD *)(VIDEO_BASE+NV_PGRAPH_ZCOMP_XBOX+tile_index*4); + + //points tile Zcomp in NV_PGRAPH_RDI(0x90) + addr90=((tile_index*4+0x90)&NV_PGRAPH_RDI_INDEX_ADDRESS)|((0xEA<<16)&NV_PGRAPH_RDI_INDEX_SELECT); + + do + { + pb_wait_until_gr_not_busy(); + + *(pZcomp+0)=EncodedZStartTag; + *(p+0)=EncodedZStartTag; + VIDEOREG(NV_PGRAPH_RDI_INDEX)=addr90; VIDEOREG(NV_PGRAPH_RDI_DATA)=EncodedZStartTag; + }while (*(pZcomp+0)!=*(p+0)); + + if (tile_z_offset) + { + EncodedZOffset=tile_z_offset|tile_index|0x80000000; + + do + { + pb_wait_until_gr_not_busy(); + + VIDEOREG(NV_PFB_ZCOMP_OFFSET)=EncodedZOffset; + VIDEOREG(NV_PGRAPH_ZCOMP_OFFSET_XBOX)=EncodedZOffset; + }while(VIDEOREG(NV_PFB_ZCOMP_OFFSET)!=VIDEOREG(NV_PGRAPH_ZCOMP_OFFSET_XBOX)); + } + } + + VIDEOREG(NV_PFIFO_CACHE1_DMA_PUSH)=old_dma_push; +} + + + +static void pb_prepare_tiles(void) +{ + DWORD *pTile; + DWORD *pTlimit; + DWORD *pTsize; + DWORD *pZcomp; + + DWORD Tile; + DWORD Tlimit; + DWORD Tsize; + DWORD Zcomp; + DWORD Zcomp_offset; + DWORD Config0; + DWORD Config1; + + DWORD *p; + + int i; + + p=(DWORD *)(VIDEO_BASE+NV_PGRAPH_TILE_XBOX); + pTlimit=(DWORD *)(VIDEO_BASE+NV_PFB_TLIMIT); + pTsize=(DWORD *)(VIDEO_BASE+NV_PFB_TSIZE); + pTile=(DWORD *)(VIDEO_BASE+NV_PFB_TILE); + + //Copy 8 Tiles details from NV_PFB to NV_PGRAPH and to NV_PGRAPH_RDI(0x10) + for(i=0x10;i<0x30;i+=4) + { + Tile=*(pTile+0); + *(p+0)=Tile; + VIDEOREG(NV_PGRAPH_RDI_INDEX)=((i+0x00)&NV_PGRAPH_RDI_INDEX_ADDRESS)|((0xEA<<16)&NV_PGRAPH_RDI_INDEX_SELECT); + VIDEOREG(NV_PGRAPH_RDI_DATA)=Tile; + + Tlimit=*(pTlimit+0); + *(p+1)=Tlimit; + VIDEOREG(NV_PGRAPH_RDI_INDEX)=((i+0x20)&NV_PGRAPH_RDI_INDEX_ADDRESS)|((0xEA<<16)&NV_PGRAPH_RDI_INDEX_SELECT); + VIDEOREG(NV_PGRAPH_RDI_DATA)=Tlimit; + + Tsize=*(pTsize+0); + *(p+2)=Tsize; + VIDEOREG(NV_PGRAPH_RDI_INDEX)=((i+0x40)&NV_PGRAPH_RDI_INDEX_ADDRESS)|((0xEA<<16)&NV_PGRAPH_RDI_INDEX_SELECT); + VIDEOREG(NV_PGRAPH_RDI_DATA)=Tsize; + + p+=4; //move 16 bytes forward + pTile+=4; + pTlimit+=4; + pTsize+=4; + } + + p=(DWORD *)(VIDEO_BASE+NV_PGRAPH_ZCOMP_XBOX); + pZcomp=(DWORD *)(VIDEO_BASE+NV_PFB_ZCOMP); + + //Copy 8 Tiles Zcomp from NV_PFB to NV_PGRAPH and to NV_PGRAPH_RDI(0x90) + for(i=0x90;i<0x110;i+=4) + { + Zcomp=*(pZcomp+0); + *(p+0)=Zcomp; + VIDEOREG(NV_PGRAPH_RDI_INDEX)=((i+0x00)&NV_PGRAPH_RDI_INDEX_ADDRESS)|((0xEA<<16)&NV_PGRAPH_RDI_INDEX_SELECT); + VIDEOREG(NV_PGRAPH_RDI_DATA)=Tsize; + + p++; //move 4 bytes forward + pZcomp++; + } + + //Copy 3 parameters from NV_PFB to NV_PGRAPH and to NV_PGRAPH_RDI(sel 0xEA : 0xC, 0 & 4) + + Zcomp_offset=VIDEOREG(NV_PFB_ZCOMP_OFFSET); + VIDEOREG(NV_PGRAPH_ZCOMP_OFFSET_XBOX)=Zcomp_offset; + VIDEOREG(NV_PGRAPH_RDI_INDEX)=((0x0C)&NV_PGRAPH_RDI_INDEX_ADDRESS)|((0xEA<<16)&NV_PGRAPH_RDI_INDEX_SELECT); + VIDEOREG(NV_PGRAPH_RDI_DATA)=Zcomp_offset; + + Config0=VIDEOREG(NV_PFB_CFG0); + VIDEOREG(NV_PGRAPH_CFG0_XBOX)=Config0; + VIDEOREG(NV_PGRAPH_RDI_INDEX)=((0x00)&NV_PGRAPH_RDI_INDEX_ADDRESS)|((0xEA<<16)&NV_PGRAPH_RDI_INDEX_SELECT); + VIDEOREG(NV_PGRAPH_RDI_DATA)=Config0; + + Config1=VIDEOREG(NV_PFB_CFG1); + VIDEOREG(NV_PGRAPH_CFG1_XBOX)=Config1; + VIDEOREG(NV_PGRAPH_RDI_INDEX)=((0x04)&NV_PGRAPH_RDI_INDEX_ADDRESS)|((0xEA<<16)&NV_PGRAPH_RDI_INDEX_SELECT); + VIDEOREG(NV_PGRAPH_RDI_DATA)=Config1; +} + + + +static void pb_create_dma_ctx( DWORD ChannelID, + DWORD Class, + DWORD Base, + DWORD Limit, + struct s_CtxDma *pDmaObject ) +{ + DWORD Addr; + DWORD AddrSpace; + DWORD Inst; + DWORD dma_flags; + + Addr=0; + AddrSpace=0; + + if ((Base&0xF0000000)!=0x80000000) + { + Addr=Base; + AddrSpace=ADDR_FBMEM; + } + else + { + Addr=Base&0x03FFFFFF; + AddrSpace=ADDR_SYSMEM; + } + + Inst=pb_FreeInst; pb_FreeInst+=1; //reserve 1 block (16 bytes) + + dma_flags=Class; + dma_flags|=0x00003000; + if (AddrSpace==ADDR_AGPMEM) dma_flags|=0x00030000; + if (AddrSpace==ADDR_SYSMEM) dma_flags|=0x00020000; + dma_flags|=0x00008000; + + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x08)=Addr|3; //0x00000003|Addr + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x0C)=Addr|3; //0x00000003|Addr + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x00)=dma_flags; //0x???sB0cl ???=Addr&0xFFF + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x04)=Limit; //0x03FFAFFF (MAXRAM) + + memset(pDmaObject,0,sizeof(struct s_CtxDma)); + + pDmaObject->ChannelID=ChannelID; + pDmaObject->Inst=Inst; + pDmaObject->Class=Class; + pDmaObject->isGr=0; +} + + + + +static void pb_bind_channel(struct s_CtxDma *pCtxDmaObject) +{ + DWORD entry; + DWORD *p; + + //entry in hash table + entry=(((pCtxDmaObject->ChannelID>>11)^pCtxDmaObject->ChannelID)>>11)^pCtxDmaObject->ChannelID; + + //entry*8 max valid value is 0x1000 + + //points at entry in hash table (table element size is 8 bytes = 2 dwords) + p=(DWORD *)(VIDEO_BASE+pb_FifoHTAddr+entry*8); + + *(p+0)= pCtxDmaObject->ChannelID; + *(p+1)= (0x80000000)| + (pb_FifoChannelID<<24)| + (pCtxDmaObject->isGr<<16)| + (pCtxDmaObject->Inst&0xFFFF); +} + + + +static void pb_3D_init(void) +{ + DWORD Inst; + + int channel; + + int i; + + DWORD offset; + + DWORD offset_cmn; + + DWORD offset_pipe; + + DWORD offset_4dwords; + + DWORD offset_20dwords; + + //Initialization of 3 big structures in PRAMIN area + //At offset 0x0000 size=0x231C bytes=0x1A9C+0x0880 + //At offset 0x231C size=0x0C00 bytes + //At offset 0x2F1C size=0x0784 bytes + //Padding 4 dwords (at offset 0x36A0 size=0x0010 bytes?) + + channel=pb_FifoChannelID; + + Inst=pb_GrCtxInst[channel]; + + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x000)|=1; + + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x33C)=0xFFFF0000; + for(i=0x340;i<=0x39C;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x3A0)=0x0FFF0000; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x3A4)=0x0FFF0000; + for(i=0x3A8;i<=0x478;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x47C)=0x00000101; + for(i=0x480;i<=0x48C;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x490)=0x00000111; + for(i=0x494;i<=0x4A4;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x4A8)=0x44400000; + for(i=0x4AC;i<=0x4D0;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; + for(i=0x4D4;i<=0x4E0;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0x00030303; + for(i=0x4E4;i<=0x4F0;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; + for(i=0x4F4;i<=0x500;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0x00080000; + for(i=0x504;i<=0x508;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; + for(i=0x50C;i<=0x518;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0x01012000; + for(i=0x51C;i<=0x528;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0x000105B8; + for(i=0x52C;i<=0x538;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0x00080008; + for(i=0x53C;i<=0x558;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; + for(i=0x55C;i<=0x578;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0x07FF0000; //8 dwords + for(i=0x57C;i<=0x598;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0x07FF0000; //8 dwords + for(i=0x59C;i<=0x5A0;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x5A4)=0x4B7FFFFF; + for(i=0x5A8;i<=0x5F8;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x5FC)=0x00000001; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x600)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x604)=0x00004000; + for(i=0x608;i<=0x60C;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x610)=0x00000001; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x614)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x618)=0x00040000; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x61C)=0x00010000; + for(i=0x620;i<=0x628;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; + for(i=0x62C;i<=0x6B4;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; //35 dwords + for(i=0x6B8;i<=0x728;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; //26 dwords + for(i=0x72C;i<=0x79C;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; //26 dwords + for(i=0x7A0;i<=0x810;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; //26 dwords + for(i=0x814;i<=0x818;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; //2 dwords + for(i=0x81C;i<=0xA18;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; //128 dwords + for(i=0xA1C;i<=0xC18;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; //128 dwords + for(i=0xC1C;i<=0xE18;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; //128 dwords + for(i=0xE1C;i<=0x1018;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; //128 dwords + for(i=0x101C;i<=0x1318;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; //192 dwords + for(i=0x131C;i<=0x1A98;i+=4) VIDEOREG(NV_PRAMIN+(Inst<<4)+i)=0; //224 dwords + + offset=0x1A9C/4; //number of dwords initialized so far = 0x6A7 + + for(i=0;i<0x88;i++) //136 blocks (unit=16 bytes=4 dwords) + { + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4+i*16+0x00)=0x10700FF9; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4+i*16+0x04)=0x0436086C; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4+i*16+0x08)=0x000C001B; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4+i*16+0x0C)=0; + offset+=4; + } + + offset_cmn=offset; //0x231C/4 + + for(i=0;i<0x300;i++) VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4+i*4)=0;//768 dwords + offset+=0x300; //0xC00 bytes + + offset_pipe=offset; //0x2F1C/4 + + for(i=0;i<0x68;i++) VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4+i*4)=0;//104 dwords + offset+=0x68; + for(i=0;i<0xD0;i++) VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4+i*4)=0;//208 dwords + offset+=0xD0; + offset_4dwords=offset; + + for(i=0;i<0x04;i++) VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4+i*4)=0;//004 dwords + offset+=0x04; + offset_20dwords=offset; + for(i=0;i<0x14;i++) VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4+i*4)=0;//020 dwords + offset+=0x14; + for(i=0;i<0x0F;i++) VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4+i*4)=0;//015 dwords + offset+=0x0F; + + for(i=0;i<0x0E;i++) VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4+i*4)=0;//014 dwords + offset+=0x0E; + for(i=0;i<0x44;i++) VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4+i*4)=0;//068 dwords + offset+=0x44; + for(i=0;i<0x20;i++) VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4+i*4)=0;//032 dwords + offset+=0x20; + for(i=0;i<0x0F;i++) VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4+i*4)=0;//015 dwords + offset+=0x0F; + + //total: +0x1E0 + //theoretically, offset=0x369C/4=0xDA7 + + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset*4)=0; + offset++; + + //total: +0x1E1 + //theoretically, offset=0x36A0/4=0xDA8 + + //Padding : 4 dwords? + + //total: +0x1E5 + //theoretically, offset=0x36B0/4=0xDAC + +#ifdef DBG + if (offset+4!=0x36B0/4) debugPrint("pb_3D_init: bad final value for offset\n"); +#endif + //floating point post-initializations in cmn structure + + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x380)=0x3F800000; //1.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x384)=0x00000000; //0.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x388)=0x00000000; //0.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x38C)=0x00000000; //0.0f + + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3C0)=0x40000000; //2.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3C4)=0x3F800000; //1.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3C8)=0x3F000000; //0.5f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3CC)=0x00000000; //0.0f + + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3D0)=0x40000000; //2.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3D4)=0x3F800000; //1.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3D8)=0x00000000; //0.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3DC)=0xBF800000; //-1.0f + + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3E0)=0x00000000; //0.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3E4)=0xBF800000; //-1.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3E8)=0x00000000; //0.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3EC)=0x00000000; //0.0f + + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x390)=0x00000000; //0.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x394)=0x3F800000; //1.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x398)=0x00000000; //0.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x39C)=0x00000000; //0.0f + + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3F0)=0x00000000; //0.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3F4)=0x00000000; //0.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3F8)=0x00000000; //0.0f + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_cmn*4+0x3FC)=0x00000000; //0.0f + + //post-initializations in pipe structure + + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x160)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x164)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x168)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x16C)=0; + + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x100)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x104)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x108)=0x000FE000; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x10C)=0; + + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x110)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x114)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x118)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x11C)=0; + + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x130)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x134)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x138)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x13C)=0; + + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x180)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x184)=0x000003F8; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x188)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_pipe*4+0x18C)=0; + + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_4dwords*4)=0x002FE000; + + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_20dwords*4+0x010)=0x001C527C; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_20dwords*4+0x014)=0x001C527C; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_20dwords*4+0x018)=0x001C527C; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_20dwords*4+0x01C)=0x001C527C; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_20dwords*4+0x020)=0x001C527C; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_20dwords*4+0x024)=0x001C527C; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_20dwords*4+0x028)=0x001C527C; + VIDEOREG(NV_PRAMIN+(Inst<<4)+offset_20dwords*4+0x02C)=0x001C527C; + +#ifdef DBG + //at this point pb_GrCtxID and pb_FifoChannelID must be different + //debugPrint("pb_3D_init: gr=%d fifo=%d\n",pb_GrCtxID,pb_FifoChannelID); +#endif +} + + + + + +static void pb_create_gr_ctx( int ChannelID, + int Class, + struct s_CtxDma *pGrObject ) +{ + DWORD flags; + DWORD flags3D; + + int size; + + DWORD Inst; + + flags3D=0; + + if ( (Class!=GR_CLASS_30)&& + (Class!=GR_CLASS_39)&& + (Class!=GR_CLASS_62)&& + (Class!=GR_CLASS_97)&& + (Class!=GR_CLASS_9F) ) + { + //"CreateGrObject invalid class number" + size=Class; + } + else + { + size=16; //16 bytes + if (Class==GR_CLASS_97) + { + size=0x330; //816 bytes + flags3D=1; + } + } + + Inst=pb_FreeInst; pb_FreeInst+=(size>>4); + + if (flags3D) + { + pb_3DGrCtxInst[pb_FifoChannelID]=Inst; + pb_3D_init(); + } + + + flags=Class&0x000000FF; + flags3D=0x00000000; + + if (Class==GR_CLASS_39) flags|=0x01000000; + + if (Class==GR_CLASS_97) flags3D=0x00000A00; + + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x00)=flags; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x04)=flags3D; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x08)=0; + VIDEOREG(NV_PRAMIN+(Inst<<4)+0x0C)=0; + + + memset(pGrObject,0,sizeof(struct s_CtxDma)); + + pGrObject->ChannelID=ChannelID; + pGrObject->Class=Class; + pGrObject->isGr=1; + pGrObject->Inst=Inst; +} + + +static void pb_start(void) +{ + if (pb_disable_gpu==0) //do we really want to send data to GPU? + { + //asks push buffer Dma engine to detect incoming Dma data (written at pb_Put) + + pb_cache_flush(); + *(pb_DmaUserAddr+0x40/4)=((DWORD)pb_Put)&0x03FFFFFF; + //from now any write will be detected + +#ifdef DBG + if ((*(pb_DmaUserAddr+0x44/4))>0x04000000) + { + debugPrint("pb_start: wrong GetAddr\n"); + return; + } +#endif + } +} + + + + +static void pb_jump_to_head(void) +{ + //Have Dma engine pointer point at push buffer head again. + //(so we don't run into the tail of push buffer) + //The best method would be to call this once per frame since it costs time. + //Of course, avoid writing more data than push buffer size in 1 frame time. + //If it happens you will get a message suggesting to call pb_reset more often + //or to enlarge push buffer (with pb_size, before calling pb_init). + //Default size is 512Kb (128*1024 dwords) + + DWORD *pGetAddr; + + DWORD TimeStampTicks; + +#ifdef DBG + if (pb_BeginEndPair) + { + debugPrint("pb_reset musn't be called inside a begin-end block.\n"); + return; + } +#endif + + //writes a jump command + //forces GPU to jump at push buffer head address at next fetch + *(pb_Put+0)=1+(((DWORD)pb_Head)&0x0FFFFFFF); + pb_Put=pb_Head; + pb_start(); + + TimeStampTicks=KeTickCount; + + //wait for arrival of Gpu Get to push buffer head + do + { + if ((*(pb_DmaUserAddr+0x44/4))>0x04000000) + { +#ifdef DBG + debugPrint("pb_reset: bad getaddr\n"); +#endif + return; + } + + + if (KeTickCount-TimeStampTicks>TICKSTIMEOUT) + { + debugPrint("pb_reset: too long\n"); + break; + } + + //converts physical address into virtual address + pGetAddr=(DWORD *)((*(pb_DmaUserAddr+0x44/4))|0x80000000); + }while (pGetAddr!=pb_Head); + +} + + + + + + + + +//public functions + +int pb_busy(void) +{ + DWORD PutAddr; + DWORD GetAddr; + + GetAddr=*(pb_DmaUserAddr+0x44/4); +#ifdef DBG + if (GetAddr>0x04000000) + { + debugPrint("pb_busy: wrong GetAddr\n"); + return 0; + } +#endif + PutAddr=(DWORD)pb_Put; + + if ((GetAddr^PutAddr)&0x0FFFFFFF) return 1; //means different addresses + + if (VIDEOREG(NV_PGRAPH_STATUS)) return 1; + + return 0; +} + +DWORD pb_back_buffer_width(void) +{ + return pb_FrameBuffersWidth; +} + +DWORD pb_back_buffer_height(void) +{ + return pb_FrameBuffersHeight; +} + +DWORD pb_back_buffer_pitch(void) +{ + return pb_FrameBuffersPitch; +} + +DWORD *pb_back_buffer(void) +{ + return (DWORD *)pb_FBAddr[pb_back_index]; +} + +DWORD *pb_extra_buffer(int index_buffer) +{ + if (index_buffer>pb_ExtraBuffersCount) + { + debugPrint("pb_target_extra_buffer: buffer index out of range\n"); + return pb_back_buffer(); + } + + return (DWORD *)pb_EXAddr[index_buffer]; +} + + +void pb_target_back_buffer(void) +{ + DWORD *p; + + DWORD width; + DWORD height; + DWORD pitch; + DWORD pitch_depth_stencil; + + DWORD dma_flags; + DWORD dma_addr; + DWORD dma_limit; + + int flag; + int depth_stencil; + + width=pb_FrameBuffersWidth; + height=pb_FrameBuffersHeight; + pitch=pb_FrameBuffersPitch; + pitch_depth_stencil=pb_DepthStencilPitch; + + //DMA channel 9 is used by GPU in order to render pixels + dma_addr=pb_FBAddr[pb_back_index]&0x03FFFFFF; + dma_limit=height*pitch-1; //(last byte) + dma_flags=DMA_CLASS_3D|0x0000B000; + dma_addr|=3; + + p=pb_begin(); + pb_push1(p,NV20_TCL_PRIMITIVE_3D_WAIT_MAKESPACE,0); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID9Inst<<4)+0x08,dma_addr); p+=3; //set params addr,data + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; //calls subprogID PB_SETOUTER: does VIDEOREG(addr)=data + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID9Inst<<4)+0x0C,dma_addr); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID9Inst<<4)+0x00,dma_flags); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID9Inst<<4)+0x04,dma_limit); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_SET_OBJECT3,9); p+=2; + pb_end(p); + + //DMA channel 11 is used by GPU in order to bitblt images + dma_addr=pb_FBAddr[pb_back_index]&0x03FFFFFF; + dma_limit=height*pitch-1; //(last byte) + dma_flags=DMA_CLASS_3D|0x0000B000; + dma_addr|=3; + + p=pb_begin(); + pb_push1(p,NV20_TCL_PRIMITIVE_3D_WAIT_MAKESPACE,0); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID11Inst<<4)+0x08,dma_addr); p+=3; //set params addr,data + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; //calls subprogID PB_SETOUTER: does VIDEOREG(addr)=data + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID11Inst<<4)+0x0C,dma_addr); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID11Inst<<4)+0x00,dma_flags); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID11Inst<<4)+0x04,dma_limit); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push1to(SUBCH_4,p,NV20_TCL_PRIMITIVE_3D_SET_OBJECT2,11); p+=2; + pb_end(p); + + depth_stencil=1; + + if (depth_stencil!=-1) //don't care + if (pb_DepthStencilLast!=depth_stencil) //changed? + { + //DMA channel 10 is used by GPU in order to render depth stencil + if (depth_stencil) + { + dma_addr=pb_DSAddr&0x03FFFFFF; + dma_limit=height*pitch_depth_stencil-1; //(last byte) + dma_flags=DMA_CLASS_3D|0x0000B000; + dma_addr|=3; + flag=1; + } + else + { + dma_addr=0; + dma_limit=0; + dma_flags=DMA_CLASS_3D|0x0000B000; + dma_addr|=3; + flag=0; + pitch_depth_stencil=pitch; + } + + p=pb_begin(); + pb_push1(p,NV20_TCL_PRIMITIVE_3D_WAIT_MAKESPACE,0); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID10Inst<<4)+0x08,dma_addr); p+=3; //set params addr,data + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; //calls subprogID PB_SETOUTER: does VIDEOREG(addr)=data + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID10Inst<<4)+0x0C,dma_addr); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID10Inst<<4)+0x00,dma_flags); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID10Inst<<4)+0x04,dma_limit); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_SET_OBJECT4,10); p+=2; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_DEPTH_TEST_ENABLE,flag); p+=2; //ZEnable=TRUE or FALSE (But don't use W, see below) + pb_push1(p,NV20_TCL_PRIMITIVE_3D_STENCIL_ENABLE,1); p+=2; //StencilEnable=TRUE + pb_end(p); + + pb_DepthStencilLast=depth_stencil; + } + + p=pb_begin(); + pb_push3(p,NV20_TCL_PRIMITIVE_3D_BUFFER_PITCH,(pitch_depth_stencil<<16)|(pitch&0xFFFF),0,0); p+=4; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_VIEWPORT_HORIZ,width<<16,height<<16); p+=3; + //Default (0x00100001) + //We use W (0x00010000) + //We don't enable YUV (0x10000000) + //We don't use floating point depth (0x00001000) + pb_push1(p,NV20_TCL_PRIMITIVE_3D_W_YUV_FPZ_FLAGS,0x00110001); p+=2; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_BUFFER_FORMAT,pb_GPUFrameBuffersFormat|pb_FBVFlag); p+=2; + pb_end(p); +} + + +void pb_target_extra_buffer(int index_buffer) +{ + DWORD *p; + + DWORD width; + DWORD height; + DWORD pitch; + DWORD pitch_depth_stencil; + + DWORD dma_flags; + DWORD dma_addr; + DWORD dma_limit; + + int flag; + int depth_stencil; + + if (index_buffer>=pb_ExtraBuffersCount) + { + debugPrint("pb_target_extra_buffer: buffer index out of range\n"); + return; + } + + width=pb_FrameBuffersWidth; + height=pb_FrameBuffersHeight; + pitch=pb_FrameBuffersPitch; + pitch_depth_stencil=pb_DepthStencilPitch; + + //DMA channel 9 is used by GPU in order to render pixels + dma_addr=pb_EXAddr[index_buffer]&0x03FFFFFF; + dma_limit=height*pitch-1; //(last byte) + dma_flags=DMA_CLASS_3D|0x0000B000; + dma_addr|=3; + + p=pb_begin(); + pb_push1(p,NV20_TCL_PRIMITIVE_3D_WAIT_MAKESPACE,0); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID9Inst<<4)+0x08,dma_addr); p+=3; //set params addr,data + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; //calls subprogID PB_SETOUTER: does VIDEOREG(addr)=data + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID9Inst<<4)+0x0C,dma_addr); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID9Inst<<4)+0x00,dma_flags); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID9Inst<<4)+0x04,dma_limit); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_SET_OBJECT3,9); p+=2; + pb_end(p); + + //DMA channel 11 is used by GPU in order to bitblt images + dma_addr=pb_EXAddr[index_buffer]&0x03FFFFFF; + dma_limit=height*pitch-1; //(last byte) + dma_flags=DMA_CLASS_3D|0x0000B000; + dma_addr|=3; + + p=pb_begin(); + pb_push1(p,NV20_TCL_PRIMITIVE_3D_WAIT_MAKESPACE,0); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID11Inst<<4)+0x08,dma_addr); p+=3; //set params addr,data + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; //calls subprogID PB_SETOUTER: does VIDEOREG(addr)=data + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID11Inst<<4)+0x0C,dma_addr); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID11Inst<<4)+0x00,dma_flags); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID11Inst<<4)+0x04,dma_limit); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push1to(SUBCH_4,p,NV20_TCL_PRIMITIVE_3D_SET_OBJECT2,11); p+=2; + pb_end(p); + + depth_stencil=1; + + if (depth_stencil!=-1) //don't care + if (pb_DepthStencilLast!=depth_stencil) //changed? + { + //DMA channel 10 is used by GPU in order to render depth stencil + if (depth_stencil) + { + dma_addr=pb_DSAddr&0x03FFFFFF; + dma_limit=height*pitch_depth_stencil-1; //(last byte) + dma_flags=DMA_CLASS_3D|0x0000B000; + dma_addr|=3; + flag=1; + } + else + { + dma_addr=0; + dma_limit=0; + dma_flags=DMA_CLASS_3D|0x0000B000; + dma_addr|=3; + flag=0; + pitch_depth_stencil=pitch; + } + + p=pb_begin(); + pb_push1(p,NV20_TCL_PRIMITIVE_3D_WAIT_MAKESPACE,0); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID10Inst<<4)+0x08,dma_addr); p+=3; //set params addr,data + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; //calls subprogID PB_SETOUTER: does VIDEOREG(addr)=data + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID10Inst<<4)+0x0C,dma_addr); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID10Inst<<4)+0x00,dma_flags); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PRAMIN+(pb_DmaChID10Inst<<4)+0x04,dma_limit); p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_SET_OBJECT4,10); p+=2; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_DEPTH_TEST_ENABLE,flag); p+=2; //ZEnable=TRUE or FALSE (But don't use W, see below) + pb_push1(p,NV20_TCL_PRIMITIVE_3D_STENCIL_ENABLE,1); p+=2; //StencilEnable=TRUE + pb_end(p); + + pb_DepthStencilLast=depth_stencil; + } + + p=pb_begin(); + pb_push3(p,NV20_TCL_PRIMITIVE_3D_BUFFER_PITCH,(pitch_depth_stencil<<16)|(pitch&0xFFFF),0,0); p+=4; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_VIEWPORT_HORIZ,width<<16,height<<16); p+=3; + //Default (0x00100001) + //We use W (0x00010000) + //We don't enable YUV (0x10000000) + //We don't use floating point depth (0x00001000) + pb_push1(p,NV20_TCL_PRIMITIVE_3D_W_YUV_FPZ_FLAGS,0x00110001); p+=2; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_BUFFER_FORMAT,pb_GPUFrameBuffersFormat|pb_FBVFlag); p+=2; + pb_end(p); +} + +DWORD pb_get_vbl_counter(void) +{ + return pb_vbl_counter; //allows caller to know if a frame has been missed +} + + +DWORD pb_wait_for_vbl(void) +{ + NtWaitForSingleObject(pb_VBlankEvent, FALSE, NULL); + return pb_vbl_counter; //allows caller to know if a frame has been missed +} + + +void pb_print(char *format, ...) +{ + char buffer[512]; + int i; + + va_list argList; + va_start(argList, format); + vsprintf(buffer, format, argList); + va_end(argList); + + for(i=0;i=0)&&(row=0)&&(col>=1) + if (systemFont[c*8+l]&m) + { + if (x1>=0) + x2=20+j*10+k; + else + x1=20+j*10+k; + } + else + { + if (x2>=0) + { + y=25+i*25+l*2; + pb_fill(x1,y,x2-x1+1,2,0xFFFFFF); + x1=x2=-1; + } + else + if (x1>=0) + { + y=25+i*25+l*2; + pb_fill(x1,y,1,2,0xFFFFFF); + x1=-1; + } + } + } + } +} + + +void pb_extra_buffers(int n) +{ + if (n>MAX_EXTRA_BUFFERS) + debugPrint("Too many extra buffers\n"); + else + pb_ExtraBuffersCount=n; +} + +void pb_size(DWORD size) +{ + if (pb_running) + debugPrint("Can't set size while push buffer Dma engine is running.\n"); + else + { + if (size<64*1024) + debugPrint("Push buffer size must be equal or larger than 64Kb.\n"); + else + if ((size-1)&size) + debugPrint("Push buffer size must be a power of 2.\n"); + else + pb_Size=size; + } +} + + +void pb_reset(void) +{ + pb_jump_to_head(); +} + + +DWORD *pb_begin(void) +{ +#ifdef DBG + if (pb_Put>=pb_Tail) debugPrint("ERROR! Push buffer overflow! Use pb_reset more often or enlarge push buffer!\n"); + + if (pb_BeginEndPair==1) debugPrint("pb_start without a pb_end earlier\n"); + pb_BeginEndPair=1; + pb_PushIndex=0; + pb_PushNext=pb_Put; + pb_PushStart=pb_Put; +#endif + return pb_Put; +} + +#ifdef LOG +static FILE *fd; +static int logging=0; + + +void pb_start_log(void) +{ + if (logging) return; + + logging=1; + + fd=fopen("pbkit_record.txt","w"); +} + +void pb_stop_log(void) +{ + if (logging==0) return; + + logging=0; + fclose(fd); +} +#endif + + +void pb_end(DWORD *pEnd) +{ + DWORD TimeStamp1; + DWORD TimeStamp2; + + int i; + +#ifdef LOG + DWORD *p; + int n; + + if (logging) + { + p=pb_PushStart; + while (p!=pEnd) + { + n=(*p>>18)&0x7FF; + fprintf(fd,"0x%08x, ",*(p++)); + for(i=0;iTICKSTIMEOUT) + { + debugPrint("pb_end: Busy for too long (%d) (%08x)\n", + ((DWORD)(pb_Put)-(DWORD)(pb_Head)), + VIDEOREG(NV_PFIFO_CACHE1_DMA_GET) + ); + break; + } + } + } +} + + + +void pb_push1to(DWORD subchannel, DWORD *p, DWORD command, DWORD param1) +{ +#ifdef DBG + if (p!=pb_PushNext) debugPrint("pb_push1to: new write address invalid or not following previous write addresses\n"); + if (pb_BeginEndPair==0) debugPrint("pb_push1to: missing pb_begin earlier\n"); + pb_PushIndex+=2; + pb_PushNext+=2; + if (pb_PushIndex>128) debugPrint("pb_push1to: begin-end block musn't exceed 128 dwords\n"); +#endif + + *(p+0)=EncodeMethod(subchannel,command,1); + *(p+1)=param1; +} + +void pb_push2to(DWORD subchannel, DWORD *p, DWORD command, DWORD param1, DWORD param2) +{ +#ifdef DBG + if (p!=pb_PushNext) debugPrint("pb_push2to : new write address invalid or not following previous write addresses\n"); + if (pb_BeginEndPair==0) debugPrint("pb_push2to : missing pb_begin earlier\n"); + pb_PushIndex+=3; + pb_PushNext+=3; + if (pb_PushIndex>128) debugPrint("pb_push2to: begin-end block musn't exceed 128 dwords\n"); +#endif + + *(p+0)=EncodeMethod(subchannel,command,2); + *(p+1)=param1; + *(p+2)=param2; +} + +void pb_push3to(DWORD subchannel, DWORD *p, DWORD command, DWORD param1, DWORD param2, DWORD param3) +{ +#ifdef DBG + if (p!=pb_PushNext) debugPrint("pb_push3to : new write address invalid or not following previous write addresses\n"); + if (pb_BeginEndPair==0) debugPrint("pb_push3to : missing pb_begin earlier\n"); + pb_PushIndex+=4; + pb_PushNext+=4; + if (pb_PushIndex>128) debugPrint("pb_push3to: begin-end block musn't exceed 128 dwords\n"); +#endif + + *(p+0)=EncodeMethod(subchannel,command,3); + *(p+1)=param1; + *(p+2)=param2; + *(p+3)=param3; +} + +void pb_push4to(DWORD subchannel, DWORD *p, DWORD command, DWORD param1, DWORD param2, DWORD param3, DWORD param4) +{ +#ifdef DBG + if (p!=pb_PushNext) debugPrint("pb_push4to : new write address invalid or not following previous write addresses\n"); + if (pb_BeginEndPair==0) debugPrint("pb_push4to : missing pb_begin earlier\n"); + pb_PushIndex+=5; + pb_PushNext+=5; + if (pb_PushIndex>128) debugPrint("pb_push4to: begin-end block musn't exceed 128 dwords\n"); +#endif + + *(p+0)=EncodeMethod(subchannel,command,4); + *(p+1)=param1; + *(p+2)=param2; + *(p+3)=param3; + *(p+4)=param4; +} + + +void pb_push1(DWORD *p, DWORD command, DWORD param1) +{ +#ifdef DBG + if (p!=pb_PushNext) debugPrint("pb_push1: new write address invalid or not following previous write addresses\n"); + if (pb_BeginEndPair==0) debugPrint("pb_push1: missing pb_begin earlier\n"); + pb_PushIndex+=2; + pb_PushNext+=2; + if (pb_PushIndex>128) debugPrint("pb_push1: begin-end block musn't exceed 128 dwords\n"); +#endif + + *(p+0)=EncodeMethod(SUBCH_3D,command,1); + *(p+1)=param1; +} + +void pb_push2(DWORD *p, DWORD command, DWORD param1, DWORD param2) +{ +#ifdef DBG + if (p!=pb_PushNext) debugPrint("pb_push2 : new write address invalid or not following previous write addresses\n"); + if (pb_BeginEndPair==0) debugPrint("pb_push2 : missing pb_begin earlier\n"); + pb_PushIndex+=3; + pb_PushNext+=3; + if (pb_PushIndex>128) debugPrint("pb_push2: begin-end block musn't exceed 128 dwords\n"); +#endif + + *(p+0)=EncodeMethod(SUBCH_3D,command,2); + *(p+1)=param1; + *(p+2)=param2; +} + +void pb_push3(DWORD *p, DWORD command, DWORD param1, DWORD param2, DWORD param3) +{ +#ifdef DBG + if (p!=pb_PushNext) debugPrint("pb_push3 : new write address invalid or not following previous write addresses\n"); + if (pb_BeginEndPair==0) debugPrint("pb_push3 : missing pb_begin earlier\n"); + pb_PushIndex+=4; + pb_PushNext+=4; + if (pb_PushIndex>128) debugPrint("pb_push3: begin-end block musn't exceed 128 dwords\n"); +#endif + + *(p+0)=EncodeMethod(SUBCH_3D,command,3); + *(p+1)=param1; + *(p+2)=param2; + *(p+3)=param3; +} + +void pb_push4(DWORD *p, DWORD command, DWORD param1, DWORD param2, DWORD param3, DWORD param4) +{ +#ifdef DBG + if (p!=pb_PushNext) debugPrint("pb_push4 : new write address invalid or not following previous write addresses\n"); + if (pb_BeginEndPair==0) debugPrint("pb_push4 : missing pb_begin earlier\n"); + pb_PushIndex+=5; + pb_PushNext+=5; + if (pb_PushIndex>128) debugPrint("pb_push4: begin-end block musn't exceed 128 dwords\n"); +#endif + + *(p+0)=EncodeMethod(SUBCH_3D,command,4); + *(p+1)=param1; + *(p+2)=param2; + *(p+3)=param3; + *(p+4)=param4; +} + +void pb_push4f(DWORD *p, DWORD command, float param1, float param2, float param3, float param4) +{ +#ifdef DBG + if (p!=pb_PushNext) debugPrint("pb_push4f : new write address invalid or not following previous write addresses\n"); + if (pb_BeginEndPair==0) debugPrint("pb_push4f : missing pb_begin earlier\n"); + pb_PushIndex+=5; + pb_PushNext+=5; + if (pb_PushIndex>128) debugPrint("pb_push4f: begin-end block musn't exceed 128 dwords\n"); +#endif + + *(p+0)=EncodeMethod(SUBCH_3D,command,4); + *((float *)(p+1))=param1; + *((float *)(p+2))=param2; + *((float *)(p+3))=param3; + *((float *)(p+4))=param4; +} + +void pb_push_transposed_matrix(DWORD *p, DWORD command, float *m) +{ +#ifdef DBG + if (p!=pb_PushNext) debugPrint("pb_push_transposed_matrix : new write address invalid or not following previous write addresses\n"); + if (pb_BeginEndPair==0) debugPrint("pb_push_transposed_matrix : missing pb_begin earlier\n"); + pb_PushIndex+=17; + pb_PushNext+=17; + if (pb_PushIndex>128) debugPrint("pb_push_transposed_matrix : begin-end block musn't exceed 128 dwords\n"); +#endif + + *(p++)=EncodeMethod(SUBCH_3D,command,16); + + *((float *)p++)=m[_11]; + *((float *)p++)=m[_21]; + *((float *)p++)=m[_31]; + *((float *)p++)=m[_41]; + + *((float *)p++)=m[_12]; + *((float *)p++)=m[_22]; + *((float *)p++)=m[_32]; + *((float *)p++)=m[_42]; + + *((float *)p++)=m[_13]; + *((float *)p++)=m[_23]; + *((float *)p++)=m[_33]; + *((float *)p++)=m[_43]; + + *((float *)p++)=m[_14]; + *((float *)p++)=m[_24]; + *((float *)p++)=m[_34]; + *((float *)p++)=m[_44]; +} + + + + + +void pb_show_front_screen(void) +{ + VIDEOREG(PCRTC_START)=pb_FBAddr[pb_front_index]&0x03FFFFFF; + pb_debug_screen_active=0; +} + +void pb_show_debug_screen(void) +{ + VIDEOREG(PCRTC_START)=((DWORD)XVideoGetFB())&0x0FFFFFFF; + pb_debug_screen_active=1; +} + +void pb_show_depth_screen(void) +{ + VIDEOREG(PCRTC_START)=pb_DSAddr&0x0FFFFFFF; + pb_debug_screen_active=1; +} + + + + + + + +void pb_set_viewport(int dwx,int dwy,int width,int height,float zmin,float zmax) +{ + DWORD *p; + DWORD dwzminscaled; + DWORD dwzmaxscaled; + float x,y,w,h; + + if (dwx<0) dwx=0; + if (dwy<0) dwy=0; + if (dwx+width>pb_FrameBuffersWidth) width=pb_FrameBuffersWidth-dwx; + if (dwy+height>pb_FrameBuffersHeight) height=pb_FrameBuffersHeight-dwy; + + pb_Viewport_x=dwx; + pb_Viewport_y=dwy; + pb_Viewport_width=width; + pb_Viewport_height=height; + pb_Viewport_zmin=zmin; + pb_Viewport_zmax=zmax; + + x=0.53125f+(float)dwx; + y=0.53125f+(float)dwy; + w=0.5f*((float)pb_Viewport_width); + h=-0.5f*((float)pb_Viewport_height); + *((float *)&dwzminscaled)=zmin*pb_ZScale; + *((float *)&dwzmaxscaled)=zmax*pb_ZScale; +/* + p=pb_begin(); + pb_push4f(p,NV20_TCL_PRIMITIVE_3D_VIEWPORT_OX,x+0.53125f,y+0.53125f,0.0f,0.0f); p+=5; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_DEPTH_RANGE_NEAR,dwzminscaled,dwzmaxscaled); p+=3; + pb_end(p); +*/ + p=pb_begin(); + pb_push4f(p,NV20_TCL_PRIMITIVE_3D_VIEWPORT_OX,x+w,y-h,zmin*pb_ZScale,0.0f); p+=5; + pb_push4f(p,NV20_TCL_PRIMITIVE_3D_VIEWPORT_PX_DIV2,w,h,(zmax-zmin)*pb_ZScale,0.0f); p+=5; + pb_push2(p,NV20_TCL_PRIMITIVE_3D_DEPTH_RANGE_NEAR,dwzminscaled,dwzmaxscaled); p+=3; + pb_end(p); +} + + + +void pb_fill(int x, int y, int w, int h, DWORD color) +{ + DWORD *p; + + int x1,y1,x2,y2; + + x1=x; + y1=y; + x2=x+w; + y2=y+h; + + //if you supply 32 bits color and res is 16 bits, apply function below + //color=((color>>8)&0xF800)|((color>>5)&0x07E0)|((color>>3)&0x001F); + + p=pb_begin(); + pb_push(p++,NV20_TCL_PRIMITIVE_3D_CLEAR_VALUE_HORIZ,2); //sets rectangle coordinates + *(p++)=((x2-1)<<16)|x1; + *(p++)=((y2-1)<<16)|y1; + pb_push(p++,NV20_TCL_PRIMITIVE_3D_CLEAR_VALUE_DEPTH,3); //sets data used to fill in rectangle + *(p++)=0; //(depth<<8)|stencil + *(p++)=color; //color + *(p++)=0xF0; //triggers the HW rectangle fill (0x03 for D&S) + pb_end(p); +} + + + + + +//ALWAYS use this at beginning of frame or you may lose one third of performance because +//automatic compression algorithm for tile #1 can't afford any garbage left behind... +//Also, try to draw from closest distance to farest distance to help algorithm +//Depth is set to max and stencil is set to 0. We assume D24S8 format is used. +//Implies that depth test function is set to "less or equal" +void pb_erase_depth_stencil_buffer(int x, int y, int w, int h) +{ + DWORD *p; + + int x1,y1,x2,y2; + + x1=x; + y1=y; + x2=x+w; + y2=y+h; + + p=pb_begin(); + pb_push(p++,NV20_TCL_PRIMITIVE_3D_CLEAR_VALUE_HORIZ,2); //sets rectangle coordinates + *(p++)=((x2-1)<<16)|x1; + *(p++)=((y2-1)<<16)|y1; + pb_push(p++,NV20_TCL_PRIMITIVE_3D_CLEAR_VALUE_DEPTH,3); //sets data used to fill in rectangle + *(p++)=0xffffff00; //(depth<<8)|stencil + *(p++)=0; //color + *(p++)=0x03; //triggers the HW rectangle fill (only on D&S) + pb_end(p); +} + + + + +//returns 1 if we have to retry later (means no free buffer, draw more details next time) +int pb_finished(void) +{ + DWORD *p; + + if (pb_BackBufferbReady[pb_BackBufferNxt]) return 1; //table is full, retry later + + //insert in push buffer the commands to trigger screen swapping at next VBlank + p=pb_begin(); + pb_push1(p,NV20_TCL_PRIMITIVE_3D_ASK_FOR_IDLE,0); p+=2; //ask for idle + pb_push1(p,NV20_TCL_PRIMITIVE_3D_NOP,0); p+=2; //wait for idle + pb_push1(p,NV20_TCL_PRIMITIVE_3D_WAIT_MAKESPACE,0); p+=2; //wait/makespace (obtains null status) + pb_push1(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,pb_back_index); p+=2; //set param=back buffer index to show up + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_FINISHED); p+=2; //subprogID PB_FINISHED: gets frame ready to show up soon +// pb_push1(p,NV20_TCL_PRIMITIVE_3D_STALL_PIPELINE,0); p+=2; //stall gpu pipeline (not sure it's needed in triple buffering technic) + pb_end(p); + + //insert in push buffer the commands to trigger selection of next back buffer + //(because previous ones may not have finished yet, so need to use 0x0100 call) + pb_back_index=(pb_back_index+1)%3; + pb_target_back_buffer(); + + return 0; +} + + + + +void pb_kill(void) +{ + void *pSavedData; + int i; + DWORD old_caches,old_push,old_pull; + DWORD *p; + + DWORD TimeStampTicks; + + int counter; + +#ifdef DBG +// debugPrint("Waiting until Dma is not busy\n"); +#endif + if (pb_Put) + { + pb_start(); + pb_wait_until_gr_not_busy(); + + *(pb_Put)=(((DWORD)pb_Head)&0x0FFFFFFF)+1; //writes a jump to push buffer head + pb_Put=pb_Head; + pb_start(); + + TimeStampTicks=KeTickCount; + + while(1) + { + if ((*(pb_DmaUserAddr+0x44/4))>0x04000000) + { + debugPrint("pb_kill: Bad get addr\n"); + break; + } + + //did GetAddr reach push buffer head as planned? + if (((*(pb_DmaUserAddr+0x44/4))&0x0FFFFFFF)==(((DWORD)pb_Head)&0x0FFFFFFF)) break; + + if (KeTickCount-TimeStampTicks>TICKSTIMEOUT) + { + debugPrint("pb_kill: Dma busy for too long\n"); + break; + } + } + } +#ifdef DBG +// if (KeTickCount-TimeStampTicks<=TICKSTIMEOUT) debugPrint("Dma not busy. All is ok.\n"); +#endif + + //wait until screen swapping is finished (if one is on its way) + while(pb_BackBufferbReady[pb_BackBufferNxt]); + + pb_running=0; + + if (pb_ExtraBuffersCount) MmFreeContiguousMemory((PVOID)pb_EXAddr[0]); + if (pb_DepthStencilAddr) MmFreeContiguousMemory((PVOID)pb_DepthStencilAddr); + if (pb_FrameBuffersAddr) MmFreeContiguousMemory((PVOID)pb_FrameBuffersAddr); + + if (pb_DmaBuffer8) MmFreeContiguousMemory(pb_DmaBuffer8); + if (pb_DmaBuffer2) MmFreeContiguousMemory(pb_DmaBuffer2); + if (pb_DmaBuffer7) MmFreeContiguousMemory(pb_DmaBuffer7); + + if (pb_Head) MmFreeContiguousMemory(pb_Head); + + + //eventually restore a previously saved video mode + + pSavedData=AvGetSavedDataAddress(); + if (pSavedData==0) AvSendTVEncoderOption((PVOID)VIDEO_BASE,VIDEO_ENC_VIDEOENABLE,1,NULL); + + + //restore system completely + + for(i=0;i<8;i++) pb_release_tile(i,1); + + VIDEOREG(NV_PFIFO_DMA_TIMESLICE)=NV_PFIFO_DMA_TIMESLICE_ALL_DISABLE; + + while ( ((VIDEOREG8(NV_PFIFO_CACHE1_STATUS)&NV_PFIFO_CACHE1_STATUS_LOW_MARK_EMPTY)==0)|| + ((VIDEOREG8(NV_PFIFO_RUNOUT_STATUS)&NV_PFIFO_RUNOUT_STATUS_LOW_MARK_EMPTY)==0)|| + ((VIDEOREG8(NV_PFIFO_CACHE1_DMA_PUSH)&NV_PFIFO_CACHE1_DMA_PUSH_STATE_BUSY)!=0) ) + { + pb_fifo_handler(); + if (VIDEOREG(NV_PGRAPH_INTR)!=NV_PGRAPH_INTR_NOT_PENDING) pb_gr_handler(); + if (VIDEOREG(NV_PMC_INTR_0)&NV_PMC_INTR_0_PCRTC_PENDING) pb_vbl_handler(); + } + + VIDEOREG(NV_PFIFO_CACHE1_DMA_PUSH)=NV_PFIFO_CACHE1_DMA_PUSH_ACCESS_DISABLE; + while((VIDEOREG8(NV_PFIFO_CACHE1_DMA_PUSH)&NV_PFIFO_CACHE1_DMA_PUSH_STATE_BUSY)!=0); + + VIDEOREG(NV_PFIFO_CACHES)=NV_PFIFO_CACHES_ALL_DISABLE; + VIDEOREG(NV_PFIFO_CACHE0_PUSH0)=NV_PFIFO_CACHE0_PUSH0_ACCESS_DISABLE; + VIDEOREG(NV_PFIFO_CACHE0_PULL0)=NV_PFIFO_CACHE0_PULL0_ACCESS_DISABLE; + VIDEOREG(NV_PFIFO_CACHE1_PUSH0)=NV_PFIFO_CACHE1_PUSH0_ACCESS_DISABLE; + VIDEOREG(NV_PFIFO_CACHE1_PULL0)=NV_PFIFO_CACHE1_PULL0_ACCESS_DISABLE; + + pb_set_fifo_channel(1); + + VIDEOREG(NV_PFIFO_CACHE1_PUT)=0; + VIDEOREG(NV_PFIFO_CACHE1_GET)=0; + + old_caches=VIDEOREG(NV_PFIFO_CACHES); + old_push=VIDEOREG(NV_PFIFO_CACHE1_PUSH0); + old_pull=VIDEOREG(NV_PFIFO_CACHE1_PULL0); + VIDEOREG(NV_PFIFO_CACHES)=NV_PFIFO_CACHES_ALL_DISABLE; + VIDEOREG(NV_PFIFO_CACHE1_PUSH0)=NV_PFIFO_CACHE1_PUSH0_ACCESS_DISABLE; + VIDEOREG(NV_PFIFO_CACHE1_PULL0)=NV_PFIFO_CACHE1_PULL0_ACCESS_DISABLE; + + //Neutralize DMA (for channels 0 and 1) + for(i=0;i<2;i++) + { + if (pb_FifoChannelsReady) //any active channel? + { + p=(DWORD *)(VIDEO_BASE+pb_FifoFCAddr+i*64); + *(p+1)=*(p+0); //DMA_GET=DMA_PUT + *(p+4)=0; //DMA_STATE=0 + } + } + + VIDEOREG(NV_PFIFO_CACHE1_PULL0)=old_pull; + VIDEOREG(NV_PFIFO_CACHE1_PUSH0)=old_push; + VIDEOREG(NV_PFIFO_CACHES)=old_caches; + + VIDEOREG(NV_PFIFO_DMA)=NV_PFIFO_DMA_NOT_PENDING; + VIDEOREG(NV_PFIFO_INTR_EN_0)=NV_PFIFO_INTR_EN_0_ALL_DISABLE; + + pb_load_gr_ctx(NONE); + + //restore most essential outer registers + VIDEOREG(NV_PFB_CFG0)=pb_OldFBConfig0; + VIDEOREG(NV_PFB_CFG1)=pb_OldFBConfig1; + VIDEOREG(NV_PMC_ENABLE)=pb_OldMCEnable; + VIDEOREG(NV_PMC_INTR_EN_0)=pb_OldMCInterrupt; + VIDEOREG(PCRTC_START)=pb_OldVideoStart; + + pb_uninstall_gpu_interrupt(); + + NtClose(pb_VBlankEvent); +} + + + + +int pb_init(void) +{ + DWORD old; + DWORD mdiv,ndiv,odiv,pdiv,result; + + BYTE old_color_31; + BYTE old_color_82; + + DWORD baseaddr,baseaddr2; + + int i,j,k; + + DWORD *p; + + struct s_CtxDma sDmaObject2; + struct s_CtxDma sDmaObject3; + struct s_CtxDma sDmaObject4; + struct s_CtxDma sDmaObject5; + struct s_CtxDma sDmaObject6; + struct s_CtxDma sDmaObject7; + struct s_CtxDma sDmaObject8; + struct s_CtxDma sDmaObject9; + struct s_CtxDma sDmaObject10; + struct s_CtxDma sDmaObject11; + struct s_CtxDma sDmaObject12; + + struct s_CtxDma sGrObject13; + struct s_CtxDma sGrObject14; + struct s_CtxDma sGrObject16; + struct s_CtxDma sGrObject17; + + DWORD UserAddr; + + DWORD TimeStamp1; + DWORD TimeStamp2; + DWORD GetAddr; + DWORD PutAddr; + //Dma channel properties + int dma_trig=128; //min 8 max 256 + int dma_size=128; //min 32 max 256 + int dma_max_reqs=8; //min 0 max 15 + + DWORD dummy; + + DWORD channel; + + DWORD *pGrCtxTable; + + VIDEO_MODE vm; + + DWORD format; + + DWORD BackBufferCount; + DWORD BackBufferFormat; + DWORD DepthStencilFormat; + + DWORD Width; + DWORD Height; + + DWORD FrameBufferCount; + + DWORD HScale; + DWORD VScale; + + DWORD HSize; + DWORD VSize; + + DWORD Pitch; + + DWORD Addr; + DWORD Size; + + DWORD FBAddr; + DWORD FBSize; + + DWORD DSAddr; + DWORD DSSize; + + DWORD EXAddr; + DWORD EXSize; + + int n; + + DWORD value; + + if (pb_running) return -8; + + //reset global vars (except pb_Size) + + pb_3DGrCtxInst[0]=0; + pb_3DGrCtxInst[1]=0; + + pb_FifoChannelsReady=0; + pb_FifoChannelsMode=NV_PFIFO_MODE_ALL_PIO; + pb_FifoChannelID=0; + + pb_GammaRampIdx=0; + for(i=0;i<3;i++) pb_GammaRampbReady[i]=0; + for(k=0;k<3;k++) for(i=0;i<3;i++) for(j=0;j<256;j++) pb_GammaRamp[k][i][j]=j; + + pb_BackBufferNxt=0; + for(i=0;i<5;i++) pb_BackBufferbReady[i]=0; + + pb_Put=NULL; + + pb_PutRunSize=0; + + pb_FrameBuffersAddr=0; + + + pb_DmaBuffer8=MmAllocateContiguousMemoryEx(32,0,MAXRAM,0,4); + pb_DmaBuffer2=MmAllocateContiguousMemoryEx(32,0,MAXRAM,0,4); + pb_DmaBuffer7=MmAllocateContiguousMemoryEx(32,0,MAXRAM,0,4); + //NumberOfBytes,LowestAcceptableAddress,HighestAcceptableAddress,Alignment,ProtectionType + if ((pb_DmaBuffer8==NULL)||(pb_DmaBuffer2==NULL)||(pb_DmaBuffer7==NULL)) return -2; + memset(pb_DmaBuffer8,0,32); + memset(pb_DmaBuffer2,0,32); + memset(pb_DmaBuffer7,0,32); + + pb_Head=MmAllocateContiguousMemoryEx(pb_Size+8*1024,0,MAXRAM,0,0x404); + //NumberOfBytes,LowestAcceptableAddress,HighestAcceptableAddress,Alignment OPTIONAL,ProtectionType + if (pb_Head==NULL) return -3; + + memset(pb_Head,0,pb_Size+8*1024); + + pb_Tail=pb_Head+pb_Size/4; + + pb_Put=pb_Head; + + pb_BackBufferNxt=0; //increments when we finish drawing a frame + pb_BackBufferbReady[0]=0; + pb_BackBufferbReady[1]=0; + pb_BackBufferbReady[2]=0; + + pb_BackBufferNxtVBL=0; //increments when VBlank event fires + + //initialize push buffer DMA engine + //DMA=Direct Memory Access (means CPU is not involved in the data transfert) + + NtCreateEvent(&pb_VBlankEvent, NULL, NotificationEvent, FALSE); + + VIDEOREG(NV_PBUS_PCI_NV_1)|=NV_PBUS_PCI_NV_1_BUS_MASTER_ENABLED; + VIDEOREG(PCRTC_INTR_EN)=PCRTC_INTR_EN_VBLANK_DISABLED; + VIDEOREG(NV_PTIMER_INTR_EN_0)=NV_PTIMER_INTR_EN_0_ALARM_DISABLED; + + if (pb_install_gpu_interrupt()==0) + { + if (pb_DmaBuffer8) MmFreeContiguousMemory(pb_DmaBuffer8); + if (pb_DmaBuffer2) MmFreeContiguousMemory(pb_DmaBuffer2); + if (pb_DmaBuffer7) MmFreeContiguousMemory(pb_DmaBuffer7); + if (pb_Head) MmFreeContiguousMemory(pb_Head); + NtClose(pb_VBlankEvent); + return -4; //OpenXDK probably hooked IRQ3 already + } + + //backup of the most essential outer registers (pb_kill will restore them) + pb_OldMCEnable=VIDEOREG(NV_PMC_ENABLE); + pb_OldMCInterrupt=VIDEOREG(NV_PMC_INTR_EN_0); + pb_OldFBConfig0=VIDEOREG(NV_PFB_CFG0); + pb_OldFBConfig1=VIDEOREG(NV_PFB_CFG1); + pb_OldVideoStart=((DWORD)XVideoGetFB())&0x03FFFFFF; + + VIDEOREG(NV_PBUS_PCI_NV_12)=NV_PBUS_PCI_NV_12_ROM_DECODE_DISABLED; + VIDEOREG(NV_PBUS_PCI_NV_3)=NV_PBUS_PCI_NV_3_LATENCY_TIMER_248_CLOCKS; + + VIDEOREG(NV_PMC_ENABLE)=NV_PMC_ENABLE_ALL_ENABLE; + VIDEOREG(NV_PMC_INTR_EN_0)=NV_PMC_INTR_EN_0_INTA_HARDWARE; + + mdiv=(VIDEOREG(NV_PRAMDAC_NVPLL_COEFF)&NV_PRAMDAC_NVPLL_COEFF_MDIV); + ndiv=(VIDEOREG(NV_PRAMDAC_NVPLL_COEFF)&NV_PRAMDAC_NVPLL_COEFF_NDIV)>>8; + odiv=1; + pdiv=(VIDEOREG(NV_PRAMDAC_NVPLL_COEFF)&NV_PRAMDAC_NVPLL_COEFF_PDIV)>>16; + + if (mdiv) + { + //Xtal in Xbox is at 16.666 Mhz but we want 31.25Mhz for GPU... + if (((DW_XTAL_16MHZ*ndiv)/(odiv<>8)&NV_PFIFO_RAMHT_BASE_ADDRESS)|NV_PFIFO_RAMHT_SEARCH_128; + // =NV_PFIFO_RAMHT_BASE_ADDRESS_10000 + + //FC (size 0x80) + pb_FifoFCAddr=baseaddr+NV_PRAMIN+0x1000;//=0x11000+NV_PRAMIN + + //U1 (size 0x20) Unknown1 + pb_FifoU1Addr=baseaddr+NV_PRAMIN+0x1080;//=0x11080+NV_PRAMIN + + //FC (dwFifoFCAddr, but 128 bytes aligned, with flag 0x200) + baseaddr2=((pb_FifoFCAddr+0x80)&0x1FC00)|0x200; //0x11200 + + VIDEOREG(NV_PFIFO_RAMFC)=baseaddr2<<7|((pb_FifoFCAddr>>8)&NV_PFIFO_RAMFC_BASE_ADDRESS); + // |NV_PFIFO_RAMFC_BASE_ADDRESS_11000 + //=0x00890110 (theoretical value) + //=0x008A0110 (current value read under openxdk : |0x400 instead of |0x200) + + pb_FreeInst=(pb_FifoU1Addr-NV_PRAMIN+0x20)>>4; + // =0x110A (unit=16 bytes block) + + VIDEOREG(NV_PFB_NVM)=VIDEOREG(NV_PFB_NVM)&NV_PFB_NVM_MODE_DISABLE; + + //zeroes whole GPU instance memory + for(i=0;i>8)&0xFF))*(XTAL_16MHZ/((float)(value&0xFF))); + else + pb_CpuFrequency=733.33f; //Mhz, theoretically + + + pb_create_dma_ctx(3,DMA_CLASS_3D,0,MAXRAM,&sDmaObject3); + pb_create_dma_ctx(5,DMA_CLASS_2,0,MAXRAM,&sDmaObject5); + pb_create_dma_ctx(4,DMA_CLASS_3,0,MAXRAM,&sDmaObject4); + + pb_create_dma_ctx(9,DMA_CLASS_3D,0,MAXRAM,&sDmaObject9); + pb_create_dma_ctx(10,DMA_CLASS_3D,0,MAXRAM,&sDmaObject10); + pb_create_dma_ctx(11,DMA_CLASS_3D,0,MAXRAM,&sDmaObject11); + pb_DmaChID9Inst=sDmaObject9.Inst; + pb_DmaChID10Inst=sDmaObject10.Inst; + pb_DmaChID11Inst=sDmaObject11.Inst; + + pb_create_dma_ctx(2,DMA_CLASS_3,(DWORD)pb_DmaBuffer2,0x1F,&sDmaObject2); + pb_create_dma_ctx(7,DMA_CLASS_3D,(DWORD)pb_DmaBuffer7,0x1F,&sDmaObject7); + //this one is damn important. memory address 0x80000000 acts as a trigger. + pb_create_dma_ctx(12,DMA_CLASS_3D,0x80000000,0x10000000,&sDmaObject12); + pb_create_dma_ctx(8,DMA_CLASS_3D,(DWORD)pb_DmaBuffer8,0x20,&sDmaObject8); + pb_create_dma_ctx(6,DMA_CLASS_2,0,MAXRAM,&sDmaObject6); + + //we initialized channel 0 first, that will match graphic context 0 + pb_FifoChannelID=0; + pb_FifoChannelsMode=NV_PFIFO_MODE_ALL_PIO; + + pb_FifoBigInst=pb_FreeInst; pb_FreeInst+=0x37F; //895 blocks=14320 bytes=0x37F0 bytes + + dummy=VIDEOREG(NV_PFIFO_CACHES); + + channel=pb_FifoChannelID; + + VIDEOREG(NV_PFIFO_CACHES)=NV_PFIFO_CACHES_ALL_DISABLE; + + //zeroes 0x37F0 bytes (0xDFC/4=0x37F blocks, 4 dwords in 1 block) + for(i=0;i<0xDFC;i++) VIDEOREG(NV_PRAMIN+(pb_FifoBigInst<<4)+i*4)=0; + + //here we go, we initialize first graphic context pointer + pGrCtxTable=(DWORD *)(VIDEO_BASE+NV_PRAMIN+(pb_GrCtxTableInst<<4)); + *(pGrCtxTable+channel)=pb_FifoBigInst; + pb_GrCtxInst[channel]=pb_FifoBigInst; + + //points at channel details in PRAMIN area + p=(DWORD *)(VIDEO_BASE+pb_FifoFCAddr+channel*64); + + //zeroes details + for(i=0;i<16;i++) *(p+i)=0; + + //set dma instance, future value for VIDEOREG(NV_PFIFO_CACHE1_DMA_INSTANCE) + *(p+3)=sDmaObject6.Inst; + + //encode trig & size + dma_trig=(dma_trig>>3)-1; + dma_size=(dma_size>>5)-1; + + //set dma fetch, future value for VIDEOREG(NV_PFIFO_CACHE1_DMA_FETCH) + *(p+5)= ((dma_trig<<3)&NV_PFIFO_CACHE1_DMA_FETCH_TRIG)| + ((dma_size<<13)&NV_PFIFO_CACHE1_DMA_FETCH_SIZE)| + ((dma_max_reqs<<16)&NV_PFIFO_CACHE1_DMA_FETCH_MAX_REQS); + + pb_FifoChannelsMode|=(1<0x04000000) + { + debugPrint("pb_init: Bad getaddr\n"); + pb_kill(); + return -9; + } + + PutAddr=((DWORD)pb_Put); + + if (((GetAddr^PutAddr)&0x0FFFFFFF)==0) break; //means same addresses (Dma is ready) + + TimeStamp2=KeTickCount; + + if (TimeStamp2-TimeStamp1>TICKSTIMEOUT) + { + debugPrint("pb_init: Dma didn't get ready in time\n"); + pb_kill(); + return -10; + } + } +#ifdef DBG +// debugPrint("Dma is ready!!!\n"); +#endif + + *((DWORD *)0x80000000)=0xFFFFFFFF; + + //Let's start initializing inner GPU registers!!! + + //These commands assign DMA channels to push buffer subchannels + //and associate some specific GPU parts to specific Dma channels + p=pb_begin(); + pb_push1to(SUBCH_2,p,NV20_TCL_PRIMITIVE_SET_MAIN_OBJECT,14); p+=2; + pb_push1to(SUBCH_3,p,NV20_TCL_PRIMITIVE_SET_MAIN_OBJECT,16); p+=2; + pb_push1to(SUBCH_4,p,NV20_TCL_PRIMITIVE_SET_MAIN_OBJECT,17); p+=2; + pb_push1to(SUBCH_3D,p,NV20_TCL_PRIMITIVE_SET_MAIN_OBJECT,13); p+=2; + pb_push1to(SUBCH_2,p,NV20_TCL_PRIMITIVE_3D_SET_OBJECT0,7); p+=2; + pb_push1to(SUBCH_3,p,NV20_TCL_PRIMITIVE_3D_SET_OBJECT5,17); p+=2; + pb_push1to(SUBCH_3,p,NV20_TCL_PRIMITIVE_3D_SET_OBJECT_UNKNOWN,3); p+=2; + pb_push2to(SUBCH_4,p,NV20_TCL_PRIMITIVE_3D_SET_OBJECT1,3,11); p+=3; + pb_end(p); //calls pb_start() which will trigger the reading and sending to GPU (asynchronous, no waiting) + + //setup needed for color computations + p=pb_begin(); + pb_push(p++,NV20_TCL_PRIMITIVE_3D_SET_OBJECT0,3); + *(p++)=2; + *(p++)=3; + *(p++)=3; + pb_push(p++,NV20_TCL_PRIMITIVE_3D_SET_OBJECT2A,6); + *(p++)=4; + *(p++)=9; + *(p++)=10; + *(p++)=3; + *(p++)=3; + *(p++)=8; + pb_push(p++,NV20_TCL_PRIMITIVE_3D_SET_OBJECT8,1); + *(p++)=12; + pb_push(p++,NV20_TCL_PRIMITIVE_3D_ACTIVATE_COLORS,1); + *(p++)=0; + pb_end(p); + + p=pb_begin(); + pb_push1(p,0x09FC,1); p+=2; + pb_push4f(p,0x0A50,0.0f,0.0f,0.0f,1.0f); p+=5; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_EDGE_FLAG,1); p+=2; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_TX_SHADER_PREVIOUS,0x00210000); p+=2; //(PSTextureInput) What previous stage is used at each stage + pb_push1(p,0x1D80,1); p+=2; + pb_push1(p,0x1E68,0x7F800000); p+=2; + pb_push1(p,0x1D78,1); p+=2; + pb_end(p); + + p=pb_begin(); + pb_push_transposed_matrix(p,NV20_TCL_PRIMITIVE_3D_CLIP_PLANE_A(0),pb_IdentityMatrix); p+=17; + pb_push_transposed_matrix(p,NV20_TCL_PRIMITIVE_3D_CLIP_PLANE_A(4),pb_IdentityMatrix); p+=17; + pb_push_transposed_matrix(p,NV20_TCL_PRIMITIVE_3D_CLIP_PLANE_A(8),pb_IdentityMatrix); p+=17; + pb_push_transposed_matrix(p,NV20_TCL_PRIMITIVE_3D_CLIP_PLANE_A(12),pb_IdentityMatrix); p+=17; +/* pb_push1(p,NV20_TCL_PRIMITIVE_3D_CLIP_PLANE_ENABLE(0),0x2202); p+=2; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_CLIP_PLANE_ENABLE(1),0x2202); p+=2; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_CLIP_PLANE_ENABLE(2),0x2202); p+=2; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_CLIP_PLANE_ENABLE(3),0x2202); p+=2; +*/ pb_push4f(p,0x09D0,0.0f,0.0f,1.0f,0.0f); p+=5; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_ID,0x0000003C); p+=2; //set shader constants cursor at C-36 + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_X,12); //loads C-36, C-35 & C-34 + memcpy(p,pb_FixedPipelineConstants,12*4); p+=12; //used by common xbox shaders, but I doubt we will use them. + //(also usually C-37 is screen center offset Decals vector & c-38 is Scales vector) + pb_end(p); + + //Frame buffers creation + //So far, tested only with 640*480 32 bits (default openxdk res) + //Even if it's a waste of memory, for now, we will leave the openxdk (& SDL) + //default frame buffer untouched. debugPrint (& SDL) will still target it. + //We will provide functions pb_show_debug_screen() and pb_show_front_screen() + //in order to let user (developper) toggle between screens at will. + + pb_FrameBuffersAddr=0; + pb_DepthStencilAddr=0; + pb_DepthStencilLast=-2; + + vm=XVideoGetMode(); + if (vm.bpp==32) pb_GPUFrameBuffersFormat=0x128;//A8R8G8B8 + else pb_GPUFrameBuffersFormat=0x113; //R5G6B5 (0x123 if D24S8 used, bpp 16 untested) + pb_ZScale=16777215.0f; //D24S8 + Width=vm.width; + Height=vm.height; + + BackBufferCount=2; //triple buffering technic! + //allows dynamic details adjustment + + pb_FrameBuffersCount=BackBufferCount+1; //front buffer + back buffers + pb_FrameBuffersWidth=Width; + pb_FrameBuffersHeight=Height; + + HScale=1; + VScale=1; + + HSize=HScale*Width; //Total width + VSize=VScale*Height; //Total height + + //Front and back buffers (tile #0) + + FrameBufferCount=BackBufferCount+1; + + //pitch is the gap between start of a pixel line and start of next pixel line + //(not necessarily the size of a pixel line, because of hardware optimization) + + Pitch=(((vm.bpp*HSize)>>3)+0x3F)&0xFFFFFFC0; //64 units aligned + pb_FrameBuffersPitch=Pitch; + + //look for a standard listed pitch value greater or equal to theoretical one + for(i=0;i<16;i++) + { + if (pb_TilePitches[i]>=Pitch) + { + Pitch=pb_TilePitches[i]; + break; + } + } + + Size=Pitch*VSize; + + //verify 64 bytes alignment for size of a frame buffer + if (Size&(64-1)) debugPrint("pb_init: FBSize is not well aligned.\n"); + + pb_FBSize=Size; + + //multiply size by number of physical frame buffers in order to obtain global size + FBSize=Size*FrameBufferCount; + + //Huge alignment enforcement (16 Kb aligned!) for the global size + FBSize=(FBSize+0x3FFF)&0xFFFFC000; + + FBAddr=(DWORD)MmAllocateContiguousMemoryEx(FBSize,0,0x03FFB000,0x4000,0x404); + //NumberOfBytes,LowestAcceptableAddress,HighestAcceptableAddress,Alignment OPTIONAL,ProtectionType + + pb_FBGlobalSize=FBSize; + + pb_FrameBuffersAddr=FBAddr; + if (!FBAddr) + { + pb_kill(); + return -11; + } + + for(i=0;i>3)+0x3F)&0xFFFFFFC0; //64 units aligned + pb_DepthStencilPitch=Pitch; + + //look for a standard listed pitch value greater or equal to theoretical one + for(i=0;i<16;i++) + { + if (pb_TilePitches[i]>=Pitch) + { + Pitch=pb_TilePitches[i]; + break; + } + } + + Size=Pitch*VSize; + + //verify 64 bytes alignment for size of a frame buffer + if (Size&(64-1)) debugPrint("pb_init: DSSize is not well aligned.\n"); + + pb_DSSize=Size; + + //multiply size by number of physical frame buffers in order to obtain global size + DSSize=Size*FrameBufferCount; + + //Huge alignment enforcement (16 Kb aligned!) for the global size + DSSize=(DSSize+0x3FFF)&0xFFFFC000; + + DSAddr=(DWORD)MmAllocateContiguousMemoryEx(FBSize,0,0x03FFB000,0x4000,0x404); + //NumberOfBytes,LowestAcceptableAddress,HighestAcceptableAddress,Alignment OPTIONAL,ProtectionType + + pb_DepthStencilAddr=DSAddr; + if (!DSAddr) + { + pb_kill(); + return -11; + } + + pb_DSAddr=DSAddr; + + pb_assign_tile( 1, //int tile_index, + pb_DepthStencilAddr&0x03FFFFFF, //DWORD tile_addr, + DSSize, //DWORD tile_size, + Pitch, //DWORD tile_pitch, + 0, //DWORD tile_z_start_tag, + 0, //DWORD tile_z_offset, + 0x84000001 //DWORD tile_flags (0x04000000 for 32 bits) + ); + + + if (pb_ExtraBuffersCount) + { + //Extra back buffers (tile #2) + + //pitch is the gap between start of a pixel line and start of next pixel line + //(not necessarily the size of a pixel line, because of hardware optimization) + + Pitch=(((vm.bpp*HSize)>>3)+0x3F)&0xFFFFFFC0; //64 units aligned + + //look for a standard listed pitch value greater or equal to theoretical one + for(i=0;i<16;i++) + { + if (pb_TilePitches[i]>=Pitch) + { + Pitch=pb_TilePitches[i]; + break; + } + } + + Size=Pitch*VSize; + + //verify 64 bytes alignment for size of a frame buffer + if (Size&(64-1)) debugPrint("pb_init: EXSize is not well aligned.\n"); + + //multiply size by number of physical frame buffers in order to obtain global size + EXSize=Size*pb_ExtraBuffersCount; + + //Huge alignment enforcement (16 Kb aligned!) for the global size + EXSize=(EXSize+0x3FFF)&0xFFFFC000; + + EXAddr=(DWORD)MmAllocateContiguousMemoryEx(EXSize,0,0x03FFB000,0x4000,0x404); + //NumberOfBytes,LowestAcceptableAddress,HighestAcceptableAddress,Alignment OPTIONAL,ProtectionType + + if (!EXAddr) + { + pb_kill(); + return -11; + } + + for(i=0;i8 (0-511) + pb_push1(p,NV20_TCL_PRIMITIVE_3D_WAIT_MAKESPACE,0); p+=2; //prepare subprogram call (wait/makespace, will obtain null status) + pb_push1(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,1); p+=2; //set parameter for subprogram (TRUE) + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETNOISE); p+=2; //call subprogID PB_SETNOISE: Dxt1NoiseEnable=TRUE + pb_push1(p,NV20_TCL_PRIMITIVE_3D_CULL_ENABLE,3); p+=2; //bit0:OcclusionCullEnable=TRUE & bit1:StencilCullEnable=TRUE + pb_push1(p,NV20_TCL_PRIMITIVE_3D_WAIT_MAKESPACE,0); p+=2; //prepare subprogram call (wait/makespace, will obtain null status) + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PGRAPH_DEBUG_5,NV_PGRAPH_DEBUG_5_ZCULL_SPARE2_ENABLED); p+=3; //set parameters A & B: DoNotCullUncompressed=FALSE (|8 otherwise) + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; //calls subprogID PB_SETOUTER: does VIDEOREG(ParamA)=ParamB + if (VIDEOREG(NV_PBUS_ROM_VERSION)&NV_PBUS_ROM_VERSION_MASK) + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PGRAPH_UNKNOWN_400B80,(0x45EAD10F&~0x18100000)); //RopZCmpAlwaysRead=FALSE (bit27) & RopZRead=FALSE (bit20) + else + pb_push2(p,NV20_TCL_PRIMITIVE_3D_PARAMETER_A,NV_PGRAPH_UNKNOWN_400B80,(0x45EAD10E&~0x18100000)); + p+=3; + pb_push1(p,NV20_TCL_PRIMITIVE_3D_FIRE_INTERRUPT,PB_SETOUTER); p+=2; //calls subprogID PB_SETOUTER: does VIDEOREG(ParamA)=ParamB + pb_end(p); + + + //various intial settings (texture stages states) + p=pb_begin(); + pb_push1(p,0x1b68,0); p+=2; //texture stage 1 BumpEnvMat00=0.0f (stage +1 because no pixel shader used yet) + pb_push1(p,0x1b6c,0); p+=2; //texture stage 1 BumpEnvMat01=0.0f + pb_push1(p,0x1b70,0); p+=2;//texture stage 1 BumpEnvMat11=0.0f + pb_push1(p,0x1b74,0); p+=2; //texture stage 1 BumpEnvMat10=0.0f + pb_push1(p,0x1b78,0); p+=2; //texture stage 1 BumpEnvMatLightScale=0.0f + pb_push1(p,0x1b7c,0); p+=2; //texture stage 1 BumpEnvMatLightOffset=0.0f + pb_push3(p,0x03c0,0,0,0); p+=4; //texture stages 0 TexCoordIndex="passthru" + pb_push1(p,0x1b24,0); p+=2; //texture stage 0 BorderColor=0x000000 + pb_push1(p,0x0ae0,0); p+=2; //texture stage 0 ColorKeyColor=0x000000 + pb_push1(p,0x1ba8,0); p+=2; //texture stage 2 BumpEnvMat00=0.0f (stage +1 because no pixel shader used yet) + pb_push1(p,0x1bac,0); p+=2; //texture stage 2 BumpEnvMat01=0.0f + pb_push1(p,0x1bb0,0); p+=2;//texture stage 2 BumpEnvMat11=0.0f + pb_push1(p,0x1bb4,0); p+=2; //texture stage 2 BumpEnvMat10=0.0f + pb_push1(p,0x1bb8,0); p+=2; //texture stage 2 BumpEnvMatLightScale=0.0f + pb_push1(p,0x1bbc,0); p+=2; //texture stage 2 BumpEnvMatLightOffset=0.0f + pb_push3(p,0x03d0,0,0,0); p+=4; //texture stages 1 TexCoordIndex="passthru" + pb_push1(p,0x1b64,0); p+=2; //texture stage 1 BorderColor=0x000000 + pb_push1(p,0x0ae4,0); p+=2; //texture stage 1 ColorKeyColor=0x000000 + pb_push1(p,0x1be8,0); p+=2; //texture stage 3 BumpEnvMat00=0.0f (stage +1 because no pixel shader used yet) + pb_push1(p,0x1bec,0); p+=2; //texture stage 3 BumpEnvMat01=0.0f + pb_push1(p,0x1bf0,0); p+=2;//texture stage 3 BumpEnvMat11=0.0f + pb_push1(p,0x1bf4,0); p+=2; //texture stage 3 BumpEnvMat10=0.0f + pb_push1(p,0x1bf8,0); p+=2; //texture stage 3 BumpEnvMatLightScale=0.0f + pb_push1(p,0x1bfc,0); p+=2; //texture stage 3 BumpEnvMatLightOffset=0.0f + pb_push3(p,0x03e0,0,0,0); p+=4; //texture stages 2 TexCoordIndex="passthru" + pb_push1(p,0x1ba4,0); p+=2; //texture stage 2 BorderColor=0x000000 + pb_push1(p,0x0ae8,0); p+=2; //texture stage 2 ColorKeyColor=0x000000 + pb_push3(p,0x03f0,0,0,0); p+=4; //texture stages 3 TexCoordIndex="passthru" + pb_push1(p,0x1be4,0); p+=2; //texture stage 3 BorderColor=0x000000 + pb_push1(p,0x0aec,0); p+=2; //texture stage 3 ColorKeyColor=0x000000 + pb_end(p); + + memset((DWORD *)pb_FBAddr[0],0,pb_FBSize); + memset((DWORD *)pb_DSAddr,0,pb_DSSize); + + pb_back_index=1; //frame buffer #1 is the back buffer for now + pb_target_back_buffer(); //tells GPU what is the frame buffer target + + pb_front_index=0; //frame buffer #0 is the front buffer for now + pb_show_front_screen(); //show it + + return 0; +} + + +//enqueues shaders micro-code into push buffer stream +//(not recommended for pixel shader: slow and redundant) +DWORD *pb_push_mcode(DWORD *p,DWORD *mcode) +{ + DWORD size; + + if (((*mcode)&0xFFFF0000)!=0x43210000) //pixel shader registers values + { + //Pixel shader initialization (on xbox it's just registers initialization) + //1-8 stages where (alpha and rgb processed in parallel) + //2x4 inputs redirected to (a,b,c,d) can produce 2x3 outputs (a*b,c*d or a*b+c*d) + //redirected to v0-v1, t0-t3, or r0-r1 (r0=final result at final stage) + pb_push2(p,NV20_TCL_PRIMITIVE_3D_RC_COLOR0,pb_gpu_registers[48],pb_gpu_registers[49]); p+=3; //PSFinalCombinerC0 & C1 + pb_push1(p,NV20_TCL_PRIMITIVE_3D_TX_SHADER_CULL_MODE,pb_gpu_registers[50]); p+=2; //PSCompareMode (0 means fragment killed if r<0 or s<0 or t<0 or q<0, used in clipplane mode) + pb_push1(p,NV20_TCL_PRIMITIVE_3D_TX_SHADER_OP,pb_gpu_registers[51]); p+=2; //PSTextureModes=1 (1<<(stage*5) is project 2D: argb=texture(r/q,s/q) usually q=1.0f) + pb_push1(p,NV20_TCL_PRIMITIVE_3D_TX_SHADER_DOTMAPPING,pb_gpu_registers[52]); p+=2; //PSDotMapping (0 means [0,255]argb from texture=>[0.0,1.0](r,g,b)) + pb_push1(p,NV20_TCL_PRIMITIVE_3D_TX_SHADER_PREVIOUS,pb_gpu_registers[53]); p+=2; //PSInputTextureSource (usual value for 4 stages: 0x00210000, what previous stage each stage uses) + pb_push1(p,NV20_TCL_PRIMITIVE_3D_RC_ENABLE,pb_gpu_registers[54]); p+=2; //PSCombinerCount (stages usage count=1, r0.a LSB controls mux, C0's & C1's may be different) + pb_push(p++,NV20_TCL_PRIMITIVE_3D_RC_IN_ALPHA(0),8); memcpy(p,&pb_gpu_registers[0],8*4); p+=8; //8 PSAlphaInputs + //Inputs: 8x 0xaabbccdd + //0=0 1=c0 2=c1 3=fog.rgb 4=v0 5=v1 8=t0 0xb=t3 0xc=r0 0xd=r1 0x10=x.a default=|0.rgb| + //0x20=1-|x| 0x40=2*max(0,x)-1("_bx2") 0x60=1-2*max(0,x) 0x80=max(0,x)-0.5f("_bias") 0xa0=0.5f-max(0,x) 0xc0=x 0xf0=-x + pb_push(p++,NV20_TCL_PRIMITIVE_3D_RC_OUT_ALPHA(0),8); memcpy(p,&pb_gpu_registers[8],8*4); p+=8; //8 PSAlphaOutputs + pb_push(p++,NV20_TCL_PRIMITIVE_3D_RC_IN_RGB(0),8); memcpy(p,&pb_gpu_registers[16],8*4); p+=8; //8 PSRGBInputs + pb_push(p++,NV20_TCL_PRIMITIVE_3D_RC_OUT_RGB(0),8); memcpy(p,&pb_gpu_registers[24],8*4); p+=8; //8 PSRGBOutputs + //Outputs: 8x 0xFlags+<> <:a*b dest >:c*d dest +:a*b+c*d dest with 0xc=r0 0=discared, i.e no destination + //Flags: 2(ab)/1(cd)="* is replaced with dot product", 4="+ is replaced with (r0.a LSB or MSB not set)?(a*b):(c*d)" + //Flags: 8=-0.5f (then) 0x10=*2.0f 0x20=*4.0f 0x40=*0.5f + //Flags: 0x80(ab)/0x40(cd)=result.b propagates to result.a on rgb side (case of dp3 r0,?n,?n for example) + pb_push(p++,NV20_TCL_PRIMITIVE_3D_RC_CONSTANT_COLOR0(0),16); memcpy(p,&pb_gpu_registers[32],16*4); p+=16; //8 C0's 8 C1's + return p; + } + + //enqueues a vertex shader setup: + size=(*(mcode++))&0xFFFF; + if (size>136*5+96*7+8) + { + debugPrint("pb_push_mcode: Wrong vertex shader size\n"); + return NULL; + } + + memcpy(p,mcode,size*4); p+=size; + + return p; +} + + + + +//converts pseudo-code register into encoded xbox gpu pixel shader input register +static int pb_preg2psreg(struct s_PseudoReg *pReg) +{ + int reg=0xc; //r0 + + switch(pReg->reg) + { + case 8: reg=0xc+pReg->num; break; //r0-r1 (side effect: r2=0(0) r3=fog.rgb r4=v0 r5=v1 r6=v1r0sum(0xe) r7=EFprod(0xf)) + case 9: reg=4+pReg->num; break; //v0-v1 (side effect: v2=v1r0sum(0xe) v3=EFprod(0xf) v4=c0 v5=c1 v6=0 v7=0) + case 0xa: reg=1+pReg->num; //c0-c1 (ps constants Cn are 0xaarrggbb dwords) + //Pseudo code created by psa.exe allows to define C0-C7 but + //NVidia pixel shaders only refers to C0-C1, but they may be different + //at each stage. So there is not only one way to map them. + //Since this function supports only 1 stage, we use only c0-c1 (c2-c3 for 2nd stage, later, eventually) + //thus, we can choose to have c4-c7 match non standard xbox gpu specific registers at any stage + if (pReg->num==4) reg=0; //c4=zero + if (pReg->num==5) reg=3; //c5=fog.rgb + if (pReg->num==6) reg=0xe; //c6=v1r0sum + if (pReg->num==7) reg=0xf; //c7=EFprod (see final combiner comment below) + break; + case 0xb: reg=8+pReg->num; break; //t0-t3 + } + switch(pReg->mod) + { + case 0: reg|=0xc0; break; //x + case 1: reg|=0xe0; break; //-x + case 2: reg|=0x80; break; //x_bias (x-0.5f) + case 3: reg|=0xa0; break; //-x_bias -(x-0.5f) + case 4: reg|=0x40; break; //x_bx2 (|x|*2.0f-1.0f) + case 5: reg|=0x60; break; //-x_bx2 -(|x|*2.0f-1.0f) + case 6: reg|=0x20; break; //1-|x| (0x00=|x|) + case 7: debugPrint("pb_preg2psreg: ?n_x2 modifier is not supported\n"); break; //x_x2 (|x|*2) is not supported + default: debugPrint("pb_preg2psreg: Unrecognized modifier %d\n",pReg->mod); break; + } + return reg; +} + +//reads data from pseudo-code stream and fills in structure +static void pb_read_pregs(DWORD *pcode, struct s_PseudoRegs *pRegs, int n) +{ + DWORD code; + struct s_PseudoReg *pReg; + + pRegs->n=n; + + if (n>=1) //dest + { + code=*(pcode++); + pReg=&pRegs->dest; //ps: 8=r 9=v 0xa=c 0xb=t + pReg->reg=(code>>28)&0xf; //vs: 8=r 0xa=c 0xb=a 0xc=oP(oP0=oPos oP1=oFog oP2=oPts) 0xd=oD 0xe=oT + pReg->num=(code>> 0)&0xf; + pReg->msk=(code>>16)&0xf; //bit0=x/r bit1=y/g bit2=z/b bit3=w/a (need to reverse order for xbox gpu) + pReg->msk=((pReg->msk&8)>>3)|((pReg->msk&4)>>1)|((pReg->msk&2)<<1)|((pReg->msk&1)<<3); + if (pReg->reg==8) pb_tmp_registers[pReg->num]=1; //markup for actually used temporary registers + } + if (n>=2) //src0 + { + code=*(pcode++); + pReg=&pRegs->src0; //ps: 8=r 9=v 0xa=c 0xb=t + pReg->reg=(code>>28)&0xf; //vs: 8=r 9=v 0xa=c 0xb=a + pReg->num=(code>> 0)&0xf; + pReg->mod=(code>>24)&0xf; //0=x 1=-x (ps: 2=x_bias 3=-x_bias 4=x_bx2 5=-x_bx2 6=1-x 7=x_x2(not supported)) + pReg->swz=(code>>16)&0xff; //.p0p1p2p3=>p3p2p1p0 with 00=x/r 01=y/g 10=z/b 11=w/a (need to reverse order for xbox gpu) + pReg->swz=((pReg->swz&0xc0)>>6)|((pReg->swz&0x30)>>2)|((pReg->swz&0xc)<<2)|((pReg->swz&3)<<6); + pReg->idx=(code>>13)&1; //vs: if set, means cn to be replaced with c[a0.x+n] + } + if (n>=3) //src1 + { + code=*(pcode++); + pReg=&pRegs->src1; //ps: 8=r 9=v 0xa=c 0xb=t + pReg->reg=(code>>28)&0xf; //vs: 8=r 9=v 0xa=c 0xb=a + pReg->num=(code>> 0)&0xf; + pReg->mod=(code>>24)&0xf; //0=x 1=-x (ps: 2=x_bias 3=-x_bias 4=x_bx2 5=-x_bx2 6=1-x 7=x_x2(not supported)) + pReg->swz=(code>>16)&0xff; //.p0p1p2p3=>p3p2p1p0 with 00=x/r 01=y/g 10=z/b 11=w/a (need to reverse order for xbox gpu) + pReg->swz=((pReg->swz&0xc0)>>6)|((pReg->swz&0x30)>>2)|((pReg->swz&0xc)<<2)|((pReg->swz&3)<<6); + pReg->idx=(code>>13)&1; //vs: if set, means cn to be replaced with c[a0.x+n] + } + if (n>=4) //src2 + { + code=*(pcode++); + pReg=&pRegs->src2; //ps: 8=r 9=v 0xa=c 0xb=t + pReg->reg=(code>>28)&0xf; //vs: 8=r 9=v 0xa=c 0xb=a + pReg->num=(code>> 0)&0xf; + pReg->mod=(code>>24)&0xf; //0=x 1=-x (ps: 2=x_bias 3=-x_bias 4=x_bx2 5=-x_bx2 6=1-x 7=x_x2(not supported)) + pReg->swz=(code>>16)&0xff; //.p0p1p2p3=>p3p2p1p0 with 00=x/r 01=y/g 10=z/b 11=w/a (need to reverse order for xbox gpu) + pReg->swz=((pReg->swz&0xc0)>>6)|((pReg->swz&0x30)>>2)|((pReg->swz&0xc)<<2)|((pReg->swz&3)<<6); + pReg->idx=(code>>13)&1; //vs: if set, means cn to be replaced with c[a0.x+n] + } +} + +//sets usual parts of vertex shader micro-code (instruction independant parts) +static int pb_set_mcode(DWORD *p,struct s_PseudoRegs *pRegs) +{ +//xbox gpu micro-code format: +//renouveau constants: +//| | | | | | | | | DWORD#0 (0) +//| |scalar#|vector#|(0-95)const_src|inp_src| source0_high | DWORD#1 +//|source0_low| source1 | source2_high | DWORD#2 +//|src2low|vtmpmsk|temp_id|stmpmsk|destmsk|x| (const) dest |p|i| | DWORD#3 +//'x' bit allows to choose a constant as destination. +//Shader must be declared with a special type previously +//in order to get this priviledge and runs much slower. +//x=1 : destination is not a constant register +//x=0 : destination is a constant register (4 bits dest field becomes 8 bits const dest field) + +//The way I describe things (using c,v,r characters): +//| | | | | | | | | DWORD#0 (0) +//| |sc_code|op_code|(0-191) c_numbr|v_numbr|m|source0_swizzle| DWORD#1 (96=>C0 on xbox) +//|r_numbr|cvr|m|source1_swizzle|r_numbr|cvr|m|source2_swizzle|r_n DWORD#2 +//r? dest: +//umbr|cvr|dst_msk|r_numbr|sdstmsk|0 0 0 0|1|1 1 1 1 1 1 1 1|0|i| | DWORD#3 +//o? dest: (o0=oPos o1-2=oT6-7(n/a) o3-4=oD0-1(ff) o5=oFog o6=oPts o7-8=oT4-5(bf) o9-12=oT0-3) +//umbr|cvr|0 0 0 0|0 1 1 1|0 0 0 0|dst_msk|1|0 0 0 0|o_numbr|s|i| | DWORD#3 +//c? dest: (shaders that can write into constants run slower and have special type) +//umbr|cvr|0 0 0 0|0 1 1 1|0 0 0 0|dst_msk|0|(0-191) c_numbr|s|i| | DWORD#3 (96=>C0 on xbox) +//a0 dest: (only allowed in instruction mov a0.x,...) +//| |cvr|0 0 0 0|0 1 1 1|0 0 0 0|0 0 0 0|1 1 1 1 1 1 1 1 1|0|i| | DWORD#3 +//i: 0=cn 1=c[a0.x+n] (if any constant is used as any of the sources) +//s: set if scalar function result is expected in destination +//no c: c_numbr=0 +//no v: v_numbr=0 +//m: 0=x 1=-x +//cvr: (can't set more than 1 c and more than 1 v as src) +//01=r +//10=v +//11=c +//missing src: m=0(x) swizzle=00011011(.xyzw) r_numbr=0(0) cvr=10(v) + + DWORD src0,src1,src2; + + *(p+0)=NV20_VP_INST0_KNOWN; //always 0 + *(p+1)=0; + *(p+2)=0; + *(p+3)=0; + + if (pRegs->n<2) //it's a nop + { //src0, src1 & src2 are missing (set them to v0.xyzw) + *(p+1)|=0x1b; + *(p+2)|=(NV20_VP_SRC_REG_TYPE_INPUT<>NV20_VP_SRC2_HIGH_SHIFT)<dest.reg) //8=r 0xa=c 0xb=a 0xc=oP(oP0=oPos oP1=oFog oP2=oPts) 0xd=oD 0xe=oT + { + case 8 : *(p+3)|=0x00000ff8|(pRegs->dest.msk<dest.num<dest.msk<dest.num<dest.msk<dest.num?(pRegs->dest.num==1?NV20_VP_INST_DEST_FOG:NV20_VP_INST_DEST_PTS):NV20_VP_INST_DEST_POS)<dest.msk<dest.num?NV20_VP_INST_DEST_COL1:NV20_VP_INST_DEST_COL0)<dest.msk<dest.num<4)?NV20_VP_INST_DEST_TC(pRegs->dest.num):((pRegs->dest.num<6)?pRegs->dest.num+3:pRegs->dest.num-5))<src0.mod*NV20_VP_SRC_REG_NEGATE)|(pRegs->src0.swz<src0.reg) //8=r 9=v 0xa=c 0xb=a + { + case 8 : src0|=(NV20_VP_SRC_REG_TYPE_TEMP<src0.num<src0.num<src0.num+96)<>NV20_VP_SRC0_HIGH_SHIFT)<src0.idx*NV20_VP_INST_INDEX_CONST; + + if (pRegs->n==2) + { //src1 & src2 are missing (set them to v0.xyzw) + *(p+2)|=((0x1b<>NV20_VP_SRC2_HIGH_SHIFT)<src1.mod*NV20_VP_SRC_REG_NEGATE)|(pRegs->src1.swz<src1.reg) //8=r 9=v 0xa=c 0xb=a + { + case 8 : src1|=(NV20_VP_SRC_REG_TYPE_TEMP<src1.num<src1.num<src1.num+96)<src1.idx*NV20_VP_INST_INDEX_CONST; + + if (pRegs->n==3) + { //src2 is missing (set it to v0.xyzw) + *(p+2)|=((0x1b<>NV20_VP_SRC2_HIGH_SHIFT)<src2.mod*NV20_VP_SRC_REG_NEGATE)|(pRegs->src2.swz<src2.reg) //8=r 9=v 0xa=c 0xb=a + { + case 8 : src2|=(NV20_VP_SRC_REG_TYPE_TEMP<src2.num<src2.num<src2.num+96)<>NV20_VP_SRC2_HIGH_SHIFT)<src2.idx*NV20_VP_INST_INDEX_CONST; + + return 0; +} + +//converts shaders pseudo-code into xbox gpu micro-code +//(not recommended for pixel shader: slow and incomplete) +DWORD *pb_pcode2mcode(const DWORD *pseudocode) +{ + DWORD *p; + DWORD constant; + DWORD size; + DWORD *pcode; + int i,n; + + struct s_PseudoRegs sRegs; + + pcode=(DWORD *)pseudocode; + + if (pcode==NULL) + { + debugPrint("pb_pcode2mcode: NULL parameter\n"); + return NULL; + } + + //pb_tmp_registers will tell us unused registers. + //this array is updated by pb_read_regs() when tmp registers are detected as destination + memset(pb_tmp_registers,0,sizeof(pb_tmp_registers)); + + if (*pcode==0xffff0101) //ps_1_1 + { + pcode++; + //currently supported (not a lot, but manual ps registers setting is possible): + //- only 1 stage (1 or 2 instructions to set r0, with or without 1 'tex t0' instruction) + //- modifier -?n + //- modifier ?n_bias (-0.5f) + //- modifier ?n_bx2 (*2.0f) + //- modifier 1-|?n| + //- def cn, r, g, b, a + //- nop + //- tex t0 + //- mov r0, ?n (r0=?n) + //- mul r0, ?n, ?n (r0=?n*?n) + //- dp3 r0, ?n, ?n (r0=?n.?n) + //- add r0, ?n, ?n (r0=?n+?n) + //- sub r0, ?n, ?n (r0=?n-n) + //- mad r0, ?n, ?n, ?n (r0=?n*?n+?n) + //- lrp r0, src0, src1, src2 (r0=src0*src1+(1-src0)*src2) + //- cnd r0, r0.a, src1, src2 (r0=(r0.a>0.5f)?src1:src2) (if r0.a MSB is used for mux) + //- coherent destination mask & swizzle (no swizzle or .rgba, .xyzw, .a, .x, .rgb, .xyz for separate rgb/alpha processing) + + p=&pb_gpu_registers[0]; + //It's recommended to learn initializing registers oneself + //in order to avoid resetting most of this -probably useless- default values + memset(&pb_gpu_registers[0],0,sizeof(pb_gpu_registers)); + p[0] =0xd4301010; //PSAlphaInput for stage 0: a.a=v0.a b.a=1.a-|0.a| + p[8] =0x000000c0; //PSAlphaOutput for stage 0: r0.a=a*b + p[16]=0xc4200000; //PSRGBInput for stage 0: a.rgb=v0.rgb b.rgb=1.rgb-|0.rgb| + p[24]=0x000000c0; //PSRGBOutput for stage 0: r0.rgb=a*b + //p[32] //C0's constants + //p[40] //C1's constants + //p[48] //final combiner C0 constant + //p[49] //final combiner C1 constant + //p[50] //PSCompareMode (used only for texture mode clipplane) + //p[51] //PSTextureModes (1 is project 2D: argb=texture(r/q,s/q) usually q=1.0f) + //p[52] //PSDotMapping (0 means [0,255]argb from texture=>[0.0,1.0](r,g,b)) + //p[53] //PSInputTextureSource (most logical value is 0x00210000 when texture stages 2 & 3 are used) + p[54]=0x11101; //PSCombinerCount ("stages usage count" | "C0 & C1 may be different from stage to stage" | "r0.a MSB used for mux") + //These default settings do "mov r0,v0" + + //'final combiner' is an additional invisible (free) stage doing this: + //final pixel.rgb = A * B + (1 - A) * C + D + //final pixel.alpha = G.b or G.a (.a modifier must be used if you want .a) + //Also all values are clamped to 0..1 (negative values become zero) + + //Inner registers NV20_TCL_PRIMITIVE_3D_RC_FINAL0 and following one + //define inputs and modifiers for the 7 parameters A,B,C,D and E,F,G,? (?=0x80, unknown) + //Here are a few useful values depending what you want to do: + //fog on & specular on : 0x130e0300,0x00001c80 (means pixel.rgb=fog.a * (r0.rgb + v1.rgb) + (1 - fog.a) * fog.rgb & pixel.a=r0.a) + //fog on & specular off : 0x130c0300,0x00001c80 (means pixel.rgb=fog.a * r0.rgb + (1 - fog.a) * fog.rgb & pixel.a=r0.a) + //fog off & specular on : 0x0000000e,0x00001c80 (means pixel.rgb=r0.rgb + v1.rgb & pixel.a=r0.a) + //fog off & specular off : 0x0000000c,0x00001c80 (means D=r0.rgb & G=r0.a, so final pixel.rgb=r0.rgb & pixel.a=r0.a) + + //These special read-only registers are also available at final combiner stage (maybe also at any stage?): + //zero = 0 (0x0 is the numeric code for this register, modifier is bits 7-4, mapped to C4) + //fog = fog (0x3, fog.rgb returns the fog color inner register value, mapped to pseudocode C5 -fog.a is fog transparency, coming from fog table, I guess-) + //v1r0sum = r0 + v1 (0xe, I've mapped it to pseudocode C6 in pcode2mcode, useful when specular v1 is to be used) + //EFprod = E * F (0xf, I've mapped it to pseudocode C7 in pcode2mcode, useful for pixel shader optimization, i.e reduce number of stages) + + //Codes for normal registers: + //C0 => 0x1 + //C1 => 0x2 + //v0 => 0x4 + //v1 => 0x5 + //t0 => 0x8 + //t1 => 0x9 + //t2 => 0xa + //t3 => 0xb + //r0 => 0xc + //r1 => 0xd + + //Modifiers (Or it to code above): + //default 0x00=|0.rgb| 0x10=x.a + //0x20=1-|x| 0x40=2*max(0,x)-1("_bx2") 0x60=1-2*max(0,x) 0x80=max(0,x)-0.5f("_bias") 0xa0=0.5f-max(0,x) 0xc0=x 0xf0=-x + + while (*pcode!=0x0000ffff) + { + switch(*(pcode++)) + { + case 0x00000000: //nop + case 0x40000000: //+nop... + break; + + case 0x00000001: //mov r0, ?n (r0=?n) + case 0x40000001: //+mov... + pb_read_pregs(pcode,&sRegs,2); pcode+=2; + if ((sRegs.dest.reg!=8)||(sRegs.dest.num!=0)) { debugPrint("pb_pcode2mcode: Unsupported destination register\n"); return NULL; } + if (sRegs.dest.msk&1) p[0]=0x10301010|(pb_preg2psreg(&sRegs.src0)<<24); //PSAlphaInput for stage 0: a.a=?.a b.a=1-|0.a| + if ((sRegs.dest.msk&0xe)==0xe) p[16]=0x00200000|(pb_preg2psreg(&sRegs.src0)<<24); //PSRGBInput for stage 0: a.rgb=?.rgb b.rgb=1.rgb-|0.rgb| + break; + + case 0x00000002: //add r0, ?n, ?n (r0=?n+?n) + case 0x40000002: //+add... + pb_read_pregs(pcode,&sRegs,3); pcode+=3; + if ((sRegs.dest.reg!=8)||(sRegs.dest.num!=0)) { debugPrint("pb_pcode2mcode: Unsupported destination register\n"); return NULL; } + if (sRegs.dest.msk&1) + { + p[0]=0x10301030|(pb_preg2psreg(&sRegs.src0)<<24)|(pb_preg2psreg(&sRegs.src1)<<8); //PSAlphaInput for stage 0: a.a=?.a b.a=1.a-|0.a| c.a=?.a d=1.a-|0.a| + p[8]=0x00000c00; //PSAlphaOutput for stage 0: r0.a=a*b+c*d + } + if ((sRegs.dest.msk&0xe)==0xe) + { + p[16]=0x00200020|(pb_preg2psreg(&sRegs.src0)<<24)|(pb_preg2psreg(&sRegs.src1)<<8); //PSRGBInput for stage 0: a.rgb=?.rgb b.rgb=1.rgb-|0.rgb| c.rgb=?.rgb d.rgb=1.rgb-|0.rgb| + p[24]=0x00000c00; //PSRGBOutput for stage 0: r0.rgb=a*b+c*d + } + break; + + case 0x00000003: //sub r0, ?n, ?n (r0=?n-?n) + case 0x40000003: //+sub... + pb_read_pregs(pcode,&sRegs,3); pcode+=3; + if ((sRegs.dest.reg!=8)||(sRegs.dest.num!=0)) { debugPrint("pb_pcode2mcode: Unsupported destination register\n"); return NULL; } + if (sRegs.src1.mod<6) + sRegs.src1.mod^=1; //inverts src1 sign + else + { + debugPrint("pb_pcode2mcode: sub not supported if src1 has 1-|x| modifier\n"); + return NULL; + } + if (sRegs.dest.msk&1) + { + p[0]=0x10301030|(pb_preg2psreg(&sRegs.src0)<<24)|(pb_preg2psreg(&sRegs.src1)<<8); //PSAlphaInput for stage 0: a.a=?.a b.a=1.a-|0.a| c.a=?.a d=1.a-|0.a| + p[8]=0x00000c00; //PSAlphaOutput for stage 0: r0.a=a*b+c*d + } + if ((sRegs.dest.msk&0xe)==0xe) + { + p[16]=0x00200020|(pb_preg2psreg(&sRegs.src0)<<24)|(pb_preg2psreg(&sRegs.src1)<<8); //PSRGBInput for stage 0: a.rgb=?.rgb b.rgb=1.rgb-|0.rgb| c.rgb=?.rgb d.rgb=1.rgb-|0.rgb| + p[24]=0x00000c00; //PSRGBOutput for stage 0: r0.rgb=a*b+c*d + } + break; + + case 0x00000004: //mad r0, ?n, ?n, ?n (r0=?n*?n+?n) + case 0x40000004: //+mad... + pb_read_pregs(pcode,&sRegs,4); pcode+=4; + if ((sRegs.dest.reg!=8)||(sRegs.dest.num!=0)) { debugPrint("pb_pcode2mcode: Unsupported destination register\n"); return NULL; } + if (sRegs.dest.msk&1) + { + p[0]=0x10101030|(pb_preg2psreg(&sRegs.src0)<<24)|(pb_preg2psreg(&sRegs.src1)<<16)|(pb_preg2psreg(&sRegs.src2)<<8); //PSAlphaInput for stage 0: a.a=?.a b.a=?.a c.a=?.a d.a=1-|0.a| + p[8]=0x00000c00; //PSAlphaOutput for stage 0: r0.a=a*b+c*d + } + if ((sRegs.dest.msk&0xe)==0xe) + { + p[16]=0x00000020|(pb_preg2psreg(&sRegs.src0)<<24)|(pb_preg2psreg(&sRegs.src1)<<16)|(pb_preg2psreg(&sRegs.src2)<<8); //PSRGBInput for stage 0: a.rgb=?.rgb b.rgb=?.rgb c.rgb=?.rgb d.rgb=1-|0.rgb| + p[24]=0x00000c00; //PSRGBOutput for stage 0: r0.rgb=a*b+c*d + } + break; + + case 0x00000005: //mul r0, ?n, ?n (r0=?n*?n) + case 0x40000005: //+mul... + pb_read_pregs(pcode,&sRegs,3); pcode+=3; + if ((sRegs.dest.reg!=8)||(sRegs.dest.num!=0)) { debugPrint("pb_pcode2mcode: Unsupported destination register\n"); return NULL; } + if (sRegs.dest.msk&1) p[0]=0x10101010|(pb_preg2psreg(&sRegs.src0)<<24)|(pb_preg2psreg(&sRegs.src1)<<16); //PSAlphaInput for stage 0: a.a=?.a b.a=?.a + if ((sRegs.dest.msk&0xe)==0xe) p[16]=0x00000000|(pb_preg2psreg(&sRegs.src0)<<24)|(pb_preg2psreg(&sRegs.src1)<<16); //PSRGBInput for stage 0: a.rgb=?.rgb b.rgb=?.rgb + break; + + case 0x00000008: //dp3 r0, ?n, ?n (r0=?n.?n) + case 0x40000008: //+dp3... + pb_read_pregs(pcode,&sRegs,3); pcode+=3; + if ((sRegs.dest.reg!=8)||(sRegs.dest.num!=0)) { debugPrint("pb_pcode2mcode: Unsupported destination register\n"); return NULL; } + if ((sRegs.dest.msk&0xf)==0xe) //dp3 r0.xyz, ... + { + p[16]=0x00000000|(pb_preg2psreg(&sRegs.src0)<<24)|(pb_preg2psreg(&sRegs.src1)<<16); //PSRGBInput for stage 0: a.rgb=?.rgb b.rgb=?.rgb + p[24]=0x000020c0; //PSRGBOutput for stage 0: r0.rgb=a.b (dot product) + } + if ((sRegs.dest.msk&0xf)==0xf) //dp3 r0, ... + { + p[0]=0x10101010; + p[8]=0x00000000; //PSAlphaOutput for stage 0: discarded (we will use the b->a propagate bit on rgb side) + p[16]=0x00000000|(pb_preg2psreg(&sRegs.src0)<<24)|(pb_preg2psreg(&sRegs.src1)<<16); //PSRGBInput for stage 0: a.rgb=?.rgb b.rgb=?.rgb + p[24]=0x000820c0; //PSRGBOutput for stage 0: r0.rgb=a.b (dot product) (and r0.b propagates to r0.a) + } + break; + + case 0x00000012: //lrp r0, src0, src1, src2 (r0=src0*src1+(1-src0)*src2) + case 0x40000012: //+lrp... + pb_read_pregs(pcode,&sRegs,4); pcode+=4; + if ((sRegs.dest.reg!=8)||(sRegs.dest.num!=0)) { debugPrint("pb_pcode2mcode: Unsupported destination register\n"); return NULL; } + if (sRegs.src0.mod) { debugPrint("pb_pcode2mcode(lrp): Unsupported source 0 modifier\n"); return NULL; } + if (sRegs.dest.msk&1) + { + p[0]=0x10101030|(pb_preg2psreg(&sRegs.src0)<<24)|(pb_preg2psreg(&sRegs.src1)<<16)|(pb_preg2psreg(&sRegs.src2)<<8)|(pb_preg2psreg(&sRegs.src0)&0xf); //PSAlphaInput for stage 0: a.a=src0.a b.a=src1.a c.a=src2.a d.a=1-|src0.a| + p[8]=0x00000c00; //PSAlphaOutput for stage 0: r0.a=a*b+c*d + } + if ((sRegs.dest.msk&0xe)==0xe) + { + p[16]=0x00000020|(pb_preg2psreg(&sRegs.src0)<<24)|(pb_preg2psreg(&sRegs.src1)<<16)|(pb_preg2psreg(&sRegs.src2)<<8)|(pb_preg2psreg(&sRegs.src0)&0xf); //PSRGBInput for stage 0: a.rgb=src0.rgb b.rgb=src1.rgb c.rgb=src2.rgb d.rgb=1-|src0.rgb| + p[24]=0x00000c00; //PSRGBOutput for stage 0: r0.rgb=a*b+c*d + } + break; + + case 0x00000042: //tex t0 + case 0x40000042: //+tex... + //We assume tn has been replaced with texture color + //because of a previous correct texture stage initialization + pb_read_pregs(pcode,&sRegs,1); pcode+=1; + if (sRegs.dest.num) { debugPrint("pb_pcode2mcode: Only 'tex t0' is supported\n"); return NULL; } + p[51]=0x00000001; //PSTextureModes (1<<(stage*5) is project 2D: argb=texture(r/q,s/q) usually q=1.0f) + break; + + case 0x00000050: //cnd r0, r0.a, src1, src2 (r0=(r0.a>0.5f)?src1:src2) (if r0.a MSB used for mux) + case 0x40000050: //+cnd... + pb_read_pregs(pcode,&sRegs,4); pcode+=4; + if ((sRegs.dest.reg!=8)||(sRegs.dest.num!=0)) { debugPrint("pb_pcode2mcode: Unsupported destination register\n"); return NULL; } + if (sRegs.dest.msk&1) + { + p[0]=0x10301030|(pb_preg2psreg(&sRegs.src2)<<24)|(pb_preg2psreg(&sRegs.src1)<<8); //PSAlphaInput for stage 0: a.a=src2.a b.a=1-|0.a| c.a=src1.a d.a=1-|0.a| + p[8]=0x00004c00; //PSAlphaOutput for stage 0: r0.rgb=(r0.a MSB not set)?(a*b):(c*d)=(r0.a<=0.5f)?src2.rgb:src1.rgb + } + if ((sRegs.dest.msk&0xe)==0xe) + { + p[16]=0x00200020|(pb_preg2psreg(&sRegs.src2)<<24)|(pb_preg2psreg(&sRegs.src1)<<8); //PSRGBInput for stage 0: a.rgb=src2.rgb b.rgb=1.rgb-|0.rgb| c.rgb=src1.rgb d.rgb=1.rgb-|0.rgb| + p[24]=0x00004c00; //PSRGBOutput for stage 0: r0.rgb=(r0.a MSB not set)?(a*b):(c*d)=(r0.a<=0.5f)?src2.rgb:src1.rgb + } + break; + + case 0x00000051: //def cn, r, g, b, a + pb_read_pregs(pcode,&sRegs,1); pcode+=1; + //converts 4 floats (r,g,b,a) into 1 dword 0xaarrggbb ([0,1.0f]=>[0,0xff]) + constant=0; + constant|=((DWORD)(255.0f*(*((float *)(pcode+3)))))<<24; + constant|=((DWORD)(255.0f*(*((float *)(pcode+0)))))<<16; + constant|=((DWORD)(255.0f*(*((float *)(pcode+1)))))<<8; + constant|=((DWORD)(255.0f*(*((float *)(pcode+2)))))<<0; + //distribute c0=>c0 stage 0, c1=>c1 stage 0, c2=>c0 stage 1, etc... + p[32+8*(sRegs.dest.num&1)+(sRegs.dest.num>>1)]=constant; + pcode+=4; + break; + + default: + debugPrint("pb_pcode2mcode: Unrecognized ps token #%08x\n",*(pcode-1)); + return NULL; + } + } + return &pb_gpu_registers[0]; + } + + if (*pcode!=0xfffe0101) //vs_1_1 + { + debugPrint("pb_pcode2mcode: Shader version not supported\n"); + return NULL; + } + + //it's a vertex shader! (vs_1_1 should be entirely supported by code below -report any issue-) + pcode++; + + pb_exp_constflag=0; //in order to not set taylor series exp macro constants up more than once + pb_log_constflag=0; //in order to not set taylor series log macro constants up more than once + + n=0; //instructions counter (can't exceed 136 on xbox) + + p=&pb_gpu_programnc[1]; //push buffer compatible sequence setting up program and constants + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_PROGRAM_START_ID,1); *(p++)=0; //set run address of shader + pb_push(p++,NV20_TCL_PRIMITIVE_3D_SHADER_TYPE,2); *(p++)=SHADER_TYPE_EXTERNAL; *(p++)=SHADER_SUBTYPE_REGULAR; //set shader vertex type (external shader, regular: not allowed to write into constants -faster-) + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_FROM_ID,1); *(p++)=0; //set cursor in order to load data into program area + + while(*pcode!=0x0000ffff) + { + if (n==136) { debugPrint("pb_pcode2mcode: Too many instructions: max=136 (including expanded macros)\n"); return NULL; } + + switch(*(pcode++)) + { + //standard pseudo-code: + + case 0x00000000: //nop + case 0x40000000: //+nop + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST0,4); n++; + pb_read_pregs(pcode,&sRegs,0); pcode+=0; + if (pb_set_mcode(p,&sRegs)) { debugPrint("pb_pcode2mcode: Unrecognized token\n"); return NULL; } + *(p+1)|=NV20_VP_INST_OPCODE_NOP<>(NV20_VP_INST_VTEMP_WRITEMASK_SHIFT-NV20_VP_INST_STEMP_WRITEMASK_SHIFT); + *(p+3)&=~NV20_VP_INST_VTEMP_WRITEMASK_MASK; + } + p+=4; + break; + + case 0x00000007: //rsq dest,src0 (scalar 1/sqrt(x) function) + case 0x40000007: //+rsq + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST0,4); n++; + pb_read_pregs(pcode,&sRegs,2); pcode+=2; + //src2 is used instead of src0 in scalar functions + sRegs.n=4; + sRegs.src2=sRegs.src0; + sRegs.src0.reg=9; //v0.xyzw for unused src + sRegs.src0.num=0; + sRegs.src0.mod=0; + sRegs.src0.swz=0x1b; + sRegs.src0.idx=0; + sRegs.src1.reg=9; //v0.xyzw for unused src + sRegs.src1.num=0; + sRegs.src1.mod=0; + sRegs.src1.swz=0x1b; + sRegs.src1.idx=0; + if (pb_set_mcode(p,&sRegs)) { debugPrint("pb_pcode2mcode: Unrecognized token\n"); return NULL; } + *(p+1)|=NV20_VP_INST_OPCODE_RSQ<>(NV20_VP_INST_VTEMP_WRITEMASK_SHIFT-NV20_VP_INST_STEMP_WRITEMASK_SHIFT); + *(p+3)&=~NV20_VP_INST_VTEMP_WRITEMASK_MASK; + } + p+=4; + break; + + case 0x00000008: //dp3 dest,src0,src1 + case 0x40000008: //+dp3 + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST0,4); n++; + pb_read_pregs(pcode,&sRegs,3); pcode+=3; + if (pb_set_mcode(p,&sRegs)) { debugPrint("pb_pcode2mcode: Unrecognized token\n"); return NULL; } + *(p+1)|=NV20_VP_INST_OPCODE_DP3<=src1) + case 0x4000000d: //+sge + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST0,4); n++; + pb_read_pregs(pcode,&sRegs,3); pcode+=3; + if (pb_set_mcode(p,&sRegs)) { debugPrint("pb_pcode2mcode: Unrecognized token\n"); return NULL; } + *(p+1)|=NV20_VP_INST_OPCODE_SGE<>(NV20_VP_INST_VTEMP_WRITEMASK_SHIFT-NV20_VP_INST_STEMP_WRITEMASK_SHIFT); + *(p+3)&=~NV20_VP_INST_VTEMP_WRITEMASK_MASK; + p+=4; + //mov ri.w, C-1.w + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST0,4); n++; if (n==136) { debugPrint("pb_pcode2mcode(exp): Too many instructions: max=136 (including expanded macros)\n"); return NULL; } + sRegs.n=2; + sRegs.dest.msk=1; //.w + sRegs.src0.reg=0xa; //c + sRegs.src0.num=-1; + sRegs.src0.swz=0xff; //.wwww + sRegs.src0.mod=0; + sRegs.src0.idx=0; + if (pb_set_mcode(p,&sRegs)) { debugPrint("pb_pcode2mcode(exp): Unrecognized token\n"); return NULL; } + *(p+1)|=NV20_VP_INST_OPCODE_MOV<>(NV20_VP_INST_VTEMP_WRITEMASK_SHIFT-NV20_VP_INST_STEMP_WRITEMASK_SHIFT); + *(p+3)&=~NV20_VP_INST_VTEMP_WRITEMASK_MASK; + p+=4; + //mul dest, ri.w, ri.x + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST0,4); n++; if (n==136) { debugPrint("pb_pcode2mcode(exp): Too many instructions: max=136 (including expanded macros)\n"); return NULL; } + pb_read_pregs(pcode,&sRegs,2); pcode+=2; //read dest again and preserve it + sRegs.n=3; + sRegs.src0.reg=8; //r + sRegs.src0.num=i; + sRegs.src0.swz=0xff; //.wwww + sRegs.src0.mod=0; + sRegs.src0.idx=0; + sRegs.src1.reg=8; //r + sRegs.src1.num=i; + sRegs.src1.swz=0; //.xxxx + sRegs.src1.mod=0; + sRegs.src1.idx=0; + if (pb_set_mcode(p,&sRegs)) { debugPrint("pb_pcode2mcode(exp): Unrecognized token\n"); return NULL; } + *(p+1)|=NV20_VP_INST_OPCODE_MUL<>(NV20_VP_INST_VTEMP_WRITEMASK_SHIFT-NV20_VP_INST_STEMP_WRITEMASK_SHIFT); + *(p+3)&=~NV20_VP_INST_VTEMP_WRITEMASK_MASK; + p+=4; + //sub ri.x, ri.x, C-5.x (x=y-1) + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST0,4); n++; if (n==136) { debugPrint("pb_pcode2mcode(log): Too many instructions: max=136 (including expanded macros)\n"); return NULL; } + sRegs.n=3; + sRegs.dest.msk=8; //.x + sRegs.src0.reg=8; + sRegs.src0.num=i; + sRegs.src0.swz=0; //.xxxx + sRegs.src0.mod=0; + sRegs.src0.idx=0; + //src2 is used instead of src1 for add + sRegs.n=4; + sRegs.src2.reg=0xa; //c + sRegs.src2.num=-5; + sRegs.src2.swz=0; //.xxxx + sRegs.src2.mod=1; //- + sRegs.src2.idx=0; + sRegs.src1.reg=9; //v0.xyzw for unused src + sRegs.src1.num=0; + sRegs.src1.mod=0; + sRegs.src1.swz=0x1b; + sRegs.src1.idx=0; + if (pb_set_mcode(p,&sRegs)) { debugPrint("pb_pcode2mcode(log): Unrecognized token\n"); return NULL; } + *(p+1)|=NV20_VP_INST_OPCODE_ADD<>(NV20_VP_INST_VTEMP_WRITEMASK_SHIFT-NV20_VP_INST_STEMP_WRITEMASK_SHIFT); + *(p+3)&=~NV20_VP_INST_VTEMP_WRITEMASK_MASK; + } + p+=4; + break; + + case 0x00000011: //dst dest,src0,src1 (calculates distance) + case 0x40000011: //+dst + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST0,4); n++; + pb_read_pregs(pcode,&sRegs,3); pcode+=3; + if (pb_set_mcode(p,&sRegs)) { debugPrint("pb_pcode2mcode: Unrecognized token\n"); return NULL; } + *(p+1)|=NV20_VP_INST_OPCODE_DST<>(NV20_VP_INST_VTEMP_WRITEMASK_SHIFT-NV20_VP_INST_STEMP_WRITEMASK_SHIFT); + *(p+3)&=~NV20_VP_INST_VTEMP_WRITEMASK_MASK; + } + p+=4; + break; + + + case 0x00000014: //m4x4 dest, src0, ?i (matrix multiply) + case 0x40000014: //+m4x4 + //dp4 dest.x, src0, ?i + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST0,4); n++; if (n==136) { debugPrint("pb_pcode2mcode(m4x4): Too many instructions: max=136 (including expanded macros)\n"); return NULL; } + pb_read_pregs(pcode,&sRegs,3); pcode+=3; + if ( (sRegs.src0.swz!=0x1b)|| + (sRegs.src1.swz!=0x1b)|| + (sRegs.src0.mod)|| + (sRegs.src1.mod) ) { debugPrint("pb_pcode2mcode: Modifiers or swizles not allowed in matrices multiplication macros\n"); return NULL; } + sRegs.dest.msk=8; //.x + if (pb_set_mcode(p,&sRegs)) { debugPrint("pb_pcode2mcode: Unrecognized token\n"); return NULL; } + *(p+1)|=NV20_VP_INST_OPCODE_DP4<>(NV20_VP_INST_VTEMP_WRITEMASK_SHIFT-NV20_VP_INST_STEMP_WRITEMASK_SHIFT); + *(p+3)&=~NV20_VP_INST_VTEMP_WRITEMASK_MASK; + } + p+=4; + break; + + case 0x0000004f: //logp dest,src0 (scalar partial precision logarithm function) + case 0x4000004f: //+logp + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST0,4); n++; + pb_read_pregs(pcode,&sRegs,2); pcode+=2; + //src2 is used instead of src0 in scalar functions + sRegs.n=4; + sRegs.src2=sRegs.src0; + sRegs.src0.reg=9; //v0.xyzw for unused src + sRegs.src0.num=0; + sRegs.src0.mod=0; + sRegs.src0.swz=0x1b; + sRegs.src0.idx=0; + sRegs.src1.reg=9; //v0.xyzw for unused src + sRegs.src1.num=0; + sRegs.src1.mod=0; + sRegs.src1.swz=0x1b; + sRegs.src1.idx=0; + if (pb_set_mcode(p,&sRegs)) { debugPrint("pb_pcode2mcode: Unrecognized token\n"); return NULL; } + *(p+1)|=NV20_VP_INST_OPCODE_LOG<>(NV20_VP_INST_VTEMP_WRITEMASK_SHIFT-NV20_VP_INST_STEMP_WRITEMASK_SHIFT); + *(p+3)&=~NV20_VP_INST_VTEMP_WRITEMASK_MASK; + } + p+=4; + break; + + case 0x00000051: //def cn x, y, z, w or def cn r, g, b, a + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_ID,1); *(p++)=((*(pcode++))&0xff)+96; //set cursor in order to load data into Cn + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_CONST_X,4); *(p++)=*(pcode++); *(p++)=*(pcode++); *(p++)=*(pcode++); *(p++)=*(pcode++); + break; + + //non standard pseudo-code: nvidia-specific (vsa.exe won't accept these assembler instructions) + //workaround : use dp4 and rcp, then, in pseudo code, replace 9 with 0x100 and 6 with 0x101 + + case 0x00000100: //dph dest,src0,src1 (homogeneous dot product: same as dp4 but src0.w is seen as 1.0f) + case 0x40000100: //+dph + pb_push(p++,NV20_TCL_PRIMITIVE_3D_VP_UPLOAD_INST0,4); n++; + pb_read_pregs(pcode,&sRegs,3); pcode+=3; + if (pb_set_mcode(p,&sRegs)) { debugPrint("pb_pcode2mcode: Unrecognized token\n"); return NULL; } + *(p+1)|=NV20_VP_INST_OPCODE_DPH<>(NV20_VP_INST_VTEMP_WRITEMASK_SHIFT-NV20_VP_INST_STEMP_WRITEMASK_SHIFT); + *(p+3)&=~NV20_VP_INST_VTEMP_WRITEMASK_MASK; + } + p+=4; + break; + + default: + debugPrint("pb_pcode2mcode: Unrecognized vs token #%08x\n",*(pcode-1)); + return NULL; + } + } + + *(p-1)|=NV20_VP_INST_LAST_INST; //bit 0 of 4th dword means end of shader + + pb_gpu_programnc[0]=p-&pb_gpu_programnc[1]; //size + pb_gpu_programnc[0]|=0x43210000; //personal vs marker + return &pb_gpu_programnc[0]; +} diff --git a/src/libXFX/PBKit/pbKit.h b/src/libXFX/PBKit/pbKit.h new file mode 100644 index 0000000..34c3e20 --- /dev/null +++ b/src/libXFX/PBKit/pbKit.h @@ -0,0 +1,101 @@ +//pbKit header +//see AFL license + +#ifndef _PBKIT_H_ +#define _PBKIT_H_ + +extern "C"{ +#include +} +#include "nv_objects.h" + +//4x4 matrices indexes +#define _11 0 +#define _12 1 +#define _13 2 +#define _14 3 +#define _21 4 +#define _22 5 +#define _23 6 +#define _24 7 +#define _31 8 +#define _32 9 +#define _33 10 +#define _34 11 +#define _41 12 +#define _42 13 +#define _43 14 +#define _44 15 + +//GPU subchannels +#define SUBCH_3D 0 +#define SUBCH_2 2 +#define SUBCH_3 3 +#define SUBCH_4 4 + +//a macro used to build up a valid method +#define EncodeMethod(subchannel,command,nparam) ((nparam<<18)+(subchannel<<13)+command) + +//fastest way to write a method for subchannel 3D (0) +#define pb_push(p,command,nparam) *(p)=((nparam<<18)+command) + +void pb_show_front_screen(void); //shows scene (allows VBL synced screen swapping) +void pb_show_debug_screen(void); //shows debug screen (default openxdk+SDL buffer) +void pb_show_depth_screen(void); //shows depth screen (depth stencil buffer) + +DWORD pb_get_vbl_counter(void); +DWORD pb_wait_for_vbl(void); //waits for VBL, returns VBL counter value as bonus info + //you can avoid calling it and try to draw a lot in advance + //use it if you need strong synchronization with controls + +//ALWAYS use this at beginning of frame or you may lose one third of performance because +//automatic compression algorithm for tile #1 can't afford any garbage left behind... +void pb_erase_depth_stencil_buffer(int x, int y, int w, int h); + +void pb_reset(void); //forces a jump to push buffer head (do it at frame start) +int pb_finished(void); //prepare screen swapping at VBlank (do it at frame end) + //if it returns 1 it failed (too early, just wait & retry) + //that means you can draw more details in your scene + +DWORD *pb_pcode2mcode(const DWORD *pcode); //returns address of static micro-code result array (or NULL) + +DWORD *pb_begin(void); //start a block with this (avoid more than 128 dwords per block) +void pb_push1to(DWORD subchannel, DWORD *p, DWORD command, DWORD param1); //slow functions but with debug messages +void pb_push2to(DWORD subchannel, DWORD *p, DWORD command, DWORD param1, DWORD param2); +void pb_push3to(DWORD subchannel, DWORD *p, DWORD command, DWORD param1, DWORD param2, DWORD param3); +void pb_push4to(DWORD subchannel, DWORD *p, DWORD command, DWORD param1, DWORD param2, DWORD param3, DWORD param4); +void pb_push1(DWORD *p, DWORD command, DWORD param1); //slow functions but with debug messages (targets SUBCH_3D (0)) +void pb_push2(DWORD *p, DWORD command, DWORD param1, DWORD param2); +void pb_push3(DWORD *p, DWORD command, DWORD param1, DWORD param2, DWORD param3); +void pb_push4(DWORD *p, DWORD command, DWORD param1, DWORD param2, DWORD param3, DWORD param4); +void pb_push4f(DWORD *p, DWORD command, float param1, float param2, float param3, float param4); +void pb_push_transposed_matrix(DWORD *p, DWORD command, float *m); +DWORD *pb_push_mcode(DWORD *p, DWORD *mcode);//enqueues micro-code initialization commands +void pb_end(DWORD *pEnd); //end a block with this (triggers the data sending to GPU) + +void pb_extra_buffers(int n);//requests additional back buffers (default is 0) (call it before pb_init) +void pb_size(DWORD size); //sets push buffer size (default is 512Kb) (call it before pb_init) +int pb_init(void); //returns 0 if everything went well (starts Dma engine) +void pb_kill(void); //stops Dma engine and releases push buffer + +void pb_print(char *format, ...); //populates a text screen array +void pb_printat(int row, int col, char *format, ...); //populates a text screen array +void pb_erase_text_screen(void); //clears array +void pb_draw_text_screen(void); //converts array into drawing sequences + +void pb_target_extra_buffer(int n); //to have rendering made into a static extra buffer +void pb_target_back_buffer(void); //to have rendering made into normal rotating back buffer + +DWORD *pb_extra_buffer(int n); //returns a static extra buffer address +DWORD *pb_back_buffer(void); //returns normal rotating back buffer address +DWORD pb_back_buffer_width(void); +DWORD pb_back_buffer_height(void); +DWORD pb_back_buffer_pitch(void); + +void pb_fill(int x,int y,int w,int h, DWORD color); //rectangle fill + +void pb_set_viewport(int dwx,int dwy,int width,int height,float zmin,float zmax); + +int pb_busy(void); + +#endif diff --git a/src/libXFX/PBKit/ps.h b/src/libXFX/PBKit/ps.h new file mode 100644 index 0000000..c9fc244 --- /dev/null +++ b/src/libXFX/PBKit/ps.h @@ -0,0 +1,13 @@ +// +// Generated by Microsoft (R) D3DX9 Shader Assembler +// +// Source: ps.psh +// Flags: /Vd +// + + +const DWORD g_ps11_main[] = +{ + 0xffff0101, 0x00000042, 0xb00f0000, 0x00000001, 0x800f0000, 0xb0e40000, + 0x0000ffff +}; diff --git a/src/libXFX/PBKit/vs.h b/src/libXFX/PBKit/vs.h new file mode 100644 index 0000000..01a66ac --- /dev/null +++ b/src/libXFX/PBKit/vs.h @@ -0,0 +1,14 @@ +// +// Generated by Microsoft (R) D3DX9 Shader Assembler +// +// Source: vs.vsh +// Flags: /Vd +// + + +const DWORD g_vs11_main[] = +{ + 0xfffe0101, 0x00000001, 0xe00f0000, 0x90e40007, 0x00000001, 0x800f0000, + 0xa0e40000, 0x00000004, 0xc00f0000, 0x90e40000, 0x80e40000, 0xa0e40001, + 0x0000ffff +}; diff --git a/src/libXFX/Plane.cpp b/src/libXFX/Plane.cpp new file mode 100644 index 0000000..23eb409 --- /dev/null +++ b/src/libXFX/Plane.cpp @@ -0,0 +1,325 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace System; + +namespace XFX +{ + Plane::Plane(float a, float b, float c, float d) + { + Normal = Vector3(a, b, c); + D = d; + } + + Plane::Plane(Vector3 normal, float d) + { + Normal = normal; + D = d; + } + + Plane::Plane(Vector3 point1, Vector3 point2, Vector3 point3) + { + float x1 = point2.X - point1.X; + float y1 = point2.Y - point1.Y; + float z1 = point2.Z - point1.Z; + float x2 = point3.X - point1.X; + float y2 = point3.Y - point1.Y; + float z2 = point3.Z - point1.Z; + float yz = (y1 * z2) - (z1 * y2); + float xz = (z1 * x2) - (x1 * z2); + float xy = (x1 * y2) - (y1 * x2); + float invPyth = 1.0f / Math::Sqrt((yz * yz) + (xz * xz) + (xy * xy)); + + Normal.X = yz * invPyth; + Normal.Y = xz * invPyth; + Normal.Z = xy * invPyth; + D = -((Normal.X * point1.X) + (Normal.Y * point1.Y) + (Normal.Z * point1.Z)); + } + + Plane::Plane(Vector4 value) + { + Normal = Vector3(value.X, value.Y, value.Z); + D = value.W; + } + + Plane::Plane(const Plane &obj) + { + Normal = obj.Normal; + D = obj.D; + } + + Plane::Plane() + { + Normal = Vector3::Zero; + D = 0; + } + + float Plane::Dot(Vector4 value) + { + return (Normal.X * value.X) + (Normal.Y * value.Y) + (Normal.Z * value.Z) + (D * value.W); + } + + void Plane::Dot(Vector4 value, out float result) + { + result = (Normal.X * value.X) + (Normal.Y * value.Y) + (Normal.Z * value.Z) + (D * value.W); + } + + float Plane::DotCoordinate(Vector3 value) + { + return (Normal.X * value.X) + (Normal.Y * value.Y) + (Normal.Z * value.Z) + D; + } + + void Plane::DotCoordinate(Vector3 value, out float result) + { + result = (Normal.X * value.X) + (Normal.Y * value.Y) + (Normal.Z * value.Z) + D; + } + + float Plane::DotNormal(Vector3 value) + { + return (Normal.X * value.X) + (Normal.Y * value.Y) + (Normal.Z * value.Z); + } + + void Plane::DotNormal(Vector3 value, out float result) + { + result = (Normal.X * value.X) + (Normal.Y * value.Y) + (Normal.Z * value.Z); + } + + bool Plane::Equals(const Plane obj) + { + return ((D == obj.D) && (Normal == obj.Normal)); + } + + int Plane::GetHashCode() + { + return Normal.GetHashCode() ^ (int)D; + } + + PlaneIntersectionType_t Plane::Intersects(BoundingBox boundingbox) + { + Vector3 min; + Vector3 max; + max.X = (Normal.X >= 0.0f) ? boundingbox.Min.X : boundingbox.Max.X; + max.Y = (Normal.Y >= 0.0f) ? boundingbox.Min.Y : boundingbox.Max.Y; + max.Z = (Normal.Z >= 0.0f) ? boundingbox.Min.Z : boundingbox.Max.Z; + min.X = (Normal.X >= 0.0f) ? boundingbox.Max.X : boundingbox.Min.X; + min.Y = (Normal.Y >= 0.0f) ? boundingbox.Max.Y : boundingbox.Min.Y; + min.Z = (Normal.Z >= 0.0f) ? boundingbox.Max.Z : boundingbox.Min.Z; + + float dot = (Normal.X * max.X) + (Normal.Y * max.Y) + (Normal.Z * max.Z); + + if(dot + D > 0.0f) + return PlaneIntersectionType::Front; + + dot = (Normal.X * min.X) + (Normal.Y * min.Y) + (Normal.Z * min.Z); + + if(dot + D < 0.0f) + return PlaneIntersectionType::Back; + + return PlaneIntersectionType::Intersecting; + } + + void Plane::Intersects(BoundingBox boundingbox, out PlaneIntersectionType_t result) + { + Vector3 min; + Vector3 max; + max.X = (Normal.X >= 0.0f) ? boundingbox.Min.X : boundingbox.Max.X; + max.Y = (Normal.Y >= 0.0f) ? boundingbox.Min.Y : boundingbox.Max.Y; + max.Z = (Normal.Z >= 0.0f) ? boundingbox.Min.Z : boundingbox.Max.Z; + min.X = (Normal.X >= 0.0f) ? boundingbox.Max.X : boundingbox.Min.X; + min.Y = (Normal.Y >= 0.0f) ? boundingbox.Max.Y : boundingbox.Min.Y; + min.Z = (Normal.Z >= 0.0f) ? boundingbox.Max.Z : boundingbox.Min.Z; + + float dot = (Normal.X * max.X) + (Normal.Y * max.Y) + (Normal.Z * max.Z); + + if(dot + D > 0.0f) + result = PlaneIntersectionType::Front; + + dot = (Normal.X * min.X) + (Normal.Y * min.Y) + (Normal.Z * min.Z); + + if(dot + D < 0.0f) + result = PlaneIntersectionType::Back; + + result = PlaneIntersectionType::Intersecting; + } + + PlaneIntersectionType_t Plane::Intersects(BoundingSphere sphere) + { + float dot = (sphere.Center.X * Normal.X) + (sphere.Center.Y * Normal.Y) + (sphere.Center.Z * Normal.Z) + D; + + if(dot > sphere.Radius) + return PlaneIntersectionType::Front; + + if(dot < -sphere.Radius) + return PlaneIntersectionType::Back; + + return PlaneIntersectionType::Intersecting; + } + + void Plane::Intersects(BoundingSphere sphere, out PlaneIntersectionType_t result) + { + float dot = (sphere.Center.X * Normal.X) + (sphere.Center.Y * Normal.Y) + (sphere.Center.Z * Normal.Z) + D; + + if(dot > sphere.Radius) + result = PlaneIntersectionType::Front; + + if(dot < -sphere.Radius) + result = PlaneIntersectionType::Back; + + result = PlaneIntersectionType::Intersecting; + } + + void Plane::Normalize() + { + float magnitude = 1.0f / Math::Sqrt((Normal.X * Normal.X) + (Normal.Y * Normal.Y) + (Normal.Z * Normal.Z)); + + Normal.X *= magnitude; + Normal.Y *= magnitude; + Normal.Z *= magnitude; + D *= magnitude; + } + + Plane Plane::Normalize(Plane plane) + { + float magnitude = 1.0f / Math::Sqrt((plane.Normal.X * plane.Normal.X) + (plane.Normal.Y * plane.Normal.Y) + (plane.Normal.Z * plane.Normal.Z)); + + return Plane(plane.Normal.X * magnitude, plane.Normal.Y * magnitude, plane.Normal.Z * magnitude, plane.D * magnitude); + } + + void Plane::Normalize(Plane plane, out Plane result) + { + result = Normalize(plane); + } + + Plane Plane::Transform(Plane plane, Matrix matrix) + { + Plane result; + float x = plane.Normal.X; + float y = plane.Normal.Y; + float z = plane.Normal.Z; + float d = plane.D; + + matrix = Matrix::Invert(matrix); + result.Normal.X = (((x * matrix.M11) + (y * matrix.M12)) + (z * matrix.M13)) + (d * matrix.M14); + result.Normal.Y = (((x * matrix.M21) + (y * matrix.M22)) + (z * matrix.M23)) + (d * matrix.M24); + result.Normal.Z = (((x * matrix.M31) + (y * matrix.M32)) + (z * matrix.M33)) + (d * matrix.M34); + result.D = (((x * matrix.M41) + (y * matrix.M42)) + (z * matrix.M43)) + (d * matrix.M44); + + return result; + } + + void Plane::Transform(Plane plane, Matrix matrix, out Plane result) + { + float x = plane.Normal.X; + float y = plane.Normal.Y; + float z = plane.Normal.Z; + float d = plane.D; + + matrix = Matrix::Invert(matrix); + result.Normal.X = (((x * matrix.M11) + (y * matrix.M12)) + (z * matrix.M13)) + (d * matrix.M14); + result.Normal.Y = (((x * matrix.M21) + (y * matrix.M22)) + (z * matrix.M23)) + (d * matrix.M24); + result.Normal.Z = (((x * matrix.M31) + (y * matrix.M32)) + (z * matrix.M33)) + (d * matrix.M34); + result.D = (((x * matrix.M41) + (y * matrix.M42)) + (z * matrix.M43)) + (d * matrix.M44); + } + + Plane Plane::Transform(Plane plane, Quaternion quaternion) + { + Plane result; + float x2 = quaternion.X + quaternion.X; + float y2 = quaternion.Y + quaternion.Y; + float z2 = quaternion.Z + quaternion.Z; + float wx = quaternion.W * x2; + float wy = quaternion.W * y2; + float wz = quaternion.W * z2; + float xx = quaternion.X * x2; + float xy = quaternion.X * y2; + float xz = quaternion.X * z2; + float yy = quaternion.Y * y2; + float yz = quaternion.Y * z2; + float zz = quaternion.Z * z2; + + float x = plane.Normal.X; + float y = plane.Normal.Y; + float z = plane.Normal.Z; + + result.Normal.X = ((x * ((1.0f - yy) - zz)) + (y * (xy - wz))) + (z * (xz + wy)); + result.Normal.Y = ((x * (xy + wz)) + (y * ((1.0f - xx) - zz))) + (z * (yz - wx)); + result.Normal.Z = ((x * (xz - wy)) + (y * (yz + wx))) + (z * ((1.0f - xx) - yy)); + result.D = plane.D; + return result; + } + + void Plane::Transform(Plane plane, Quaternion quaternion, out Plane result) + { + float x2 = quaternion.X + quaternion.X; + float y2 = quaternion.Y + quaternion.Y; + float z2 = quaternion.Z + quaternion.Z; + float wx = quaternion.W * x2; + float wy = quaternion.W * y2; + float wz = quaternion.W * z2; + float xx = quaternion.X * x2; + float xy = quaternion.X * y2; + float xz = quaternion.X * z2; + float yy = quaternion.Y * y2; + float yz = quaternion.Y * z2; + float zz = quaternion.Z * z2; + + float x = plane.Normal.X; + float y = plane.Normal.Y; + float z = plane.Normal.Z; + + result.Normal.X = ((x * ((1.0f - yy) - zz)) + (y * (xy - wz))) + (z * (xz + wy)); + result.Normal.Y = ((x * (xy + wz)) + (y * ((1.0f - xx) - zz))) + (z * (yz - wx)); + result.Normal.Z = ((x * (xz - wy)) + (y * (yz + wx))) + (z * ((1.0f - xx) - yy)); + result.D = plane.D; + } + + bool Plane::operator==(const Plane other) + { + return Equals(other); + } + + bool Plane::operator!=(const Plane other) + { + return !Equals(other); + } + + Plane Plane::operator=(const Plane other) + { + Normal = other.Normal; + D = other.D; + return *this; + } +} diff --git a/src/libXFX/Point.cpp b/src/libXFX/Point.cpp new file mode 100644 index 0000000..c5f0c11 --- /dev/null +++ b/src/libXFX/Point.cpp @@ -0,0 +1,73 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include "Point.h" + +namespace XFX +{ + const Point Point::Zero = Point(0, 0); + + Point::Point(int x, int y) + { + X = x; + Y = y; + } + + Point::Point(const Point &obj) + { + X = obj.X; + Y = obj.Y; + } + + Point::Point() + { + X = 0; + Y = 0; + } + + int Point::Equals(const Point &obj) + { + return ((X == obj.X) && (Y == obj.Y)); + } + + int Point::operator==(const Point &other) + { + return ((X == other.X) && (Y == other.Y)); + } + + int Point::operator!=(const Point &other) + { + return !((X == other.X) && (Y == other.Y)); + } + + Point &Point::operator=(const Point &other) + { + X = other.X; + Y = other.Y; + return *this; + } +} diff --git a/src/libXFX/PresentationParameters.cpp b/src/libXFX/PresentationParameters.cpp new file mode 100644 index 0000000..6da0703 --- /dev/null +++ b/src/libXFX/PresentationParameters.cpp @@ -0,0 +1,139 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace XFX +{ + namespace Graphics + { + const int PresentationParameters::DefaultPresentRate = 60; + + PresentationParameters::~PresentationParameters() + { + Dispose(false); + } + + PresentationParameters::PresentationParameters() + { + disposed = false; + Clear(); + } + + void PresentationParameters::Clear() + { + AutoDepthStencilFormat = DepthFormat::Unknown; + BackBufferCount = 0; + BackBufferFormat = SurfaceFormat::Unknown; + BackBufferHeight = 0; + BackBufferWidth = 0; +#if !ENABLE_XBOX + DeviceWindowHandle = IntPtr::Zero; +#endif + EnableAutoDepthStencil = false; + FullScreenRefreshRateInHz = 0; + IsFullScreen = false; + MultiSampleQuality = 0; + MultiSampleType_ = MultiSampleType::None; + PresentationInterval = PresentInterval::Default; + PresentOptions_ = PresentOptions::None; + SwapEffect_ = SwapEffect::Default; + } + + PresentationParameters PresentationParameters::Clone() + { + PresentationParameters clone = PresentationParameters(); + clone.AutoDepthStencilFormat = AutoDepthStencilFormat; + clone.BackBufferCount = BackBufferCount; + clone.BackBufferFormat = BackBufferFormat; + clone.BackBufferHeight = BackBufferHeight; + clone.BackBufferWidth = BackBufferWidth; +#if !ENABLE_XBOX + clone.DeviceWindowHandle = DeviceWindowHandle; +#endif + clone.disposed = disposed; + clone.EnableAutoDepthStencil = EnableAutoDepthStencil; + clone.FullScreenRefreshRateInHz = FullScreenRefreshRateInHz; + clone.IsFullScreen = IsFullScreen; + clone.MultiSampleQuality = MultiSampleQuality; + clone.MultiSampleType_ = MultiSampleType_; + clone.PresentationInterval = PresentationInterval; + clone.PresentOptions_ = PresentOptions_; + clone.SwapEffect_ = SwapEffect_; + return clone; + } + + void PresentationParameters::Dispose() + { + Dispose(true); + } + + void PresentationParameters::Dispose(int disposing) + { + if (!disposed) + { + disposed = true; + if (disposing) + { + // Dispose managed resources + } + // Dispose unmanaged resources + } + } + + int PresentationParameters::Equals(PresentationParameters &other) + { + return ((other.AutoDepthStencilFormat == AutoDepthStencilFormat) && + (other.BackBufferCount == BackBufferCount) && + (other.BackBufferFormat == BackBufferFormat) && + (other.BackBufferHeight == BackBufferHeight) && + (other.BackBufferWidth == BackBufferWidth) && +#if !ENABLE_XBOX + (other.DeviceWindowHandle == DeviceWindowHandle) && +#endif + (other.Disposed == Disposed) && + (other.EnableAutoDepthStencil == EnableAutoDepthStencil) && + (other.FullScreenRefreshRateInHz == FullScreenRefreshRateInHz) && + (other.IsFullScreen == IsFullScreen) && + (other.MultiSampleQuality == MultiSampleQuality) && + (other.MultiSampleType_ == MultiSampleType_) && + (other.PresentationInterval == PresentationInterval) && + (other.PresentOptions_ == PresentOptions_) && + (other.SwapEffect_ == SwapEffect_)); + } + + int PresentationParameters::operator!=(PresentationParameters &other) + { + return !Equals(other); + } + + int PresentationParameters::operator==(PresentationParameters &other) + { + return Equals(other); + } + } +} diff --git a/src/libXFX/Quaternion.cpp b/src/libXFX/Quaternion.cpp new file mode 100644 index 0000000..8817a45 --- /dev/null +++ b/src/libXFX/Quaternion.cpp @@ -0,0 +1,682 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include + +using namespace System; + +namespace XFX +{ + const Quaternion Quaternion::Identity = Quaternion(0,0,0,1); + + Quaternion::Quaternion(float x, float y, float z, float w) + { + X = x; + Y = y; + Z = z; + W = w; + } + + Quaternion::Quaternion(Vector3 vectorPart, float scalarPart) + { + X = vectorPart.X; + Y = vectorPart.Y; + Z = vectorPart.Z; + W = scalarPart; + } + + Quaternion::Quaternion(const Quaternion &obj) + { + X = obj.X; + Y = obj.Y; + Z = obj.Z; + W = obj.W; + } + + Quaternion::Quaternion() + { + X = 0; + Y = 0; + Z = 0; + W = 0; + } + + Quaternion Quaternion::Add(Quaternion quaternion1, Quaternion quaternion2) + { + return Quaternion(quaternion1.X + quaternion2.X, + quaternion1.Y + quaternion2.Y, + quaternion1.Z + quaternion2.Z, + quaternion1.W + quaternion2.W); + } + + void Quaternion::Add(Quaternion quaternion1, Quaternion quaternion2, out Quaternion result) + { + result.X = quaternion1.X + quaternion2.X; + result.Y = quaternion1.Y + quaternion2.Y; + result.Z = quaternion1.Z + quaternion2.Z; + result.W = quaternion1.W + quaternion2.W; + } + + Quaternion Quaternion::Concatenate(Quaternion quaternion1, Quaternion quaternion2) + { + Quaternion quaternion; + float rx = quaternion2.X; + float ry = quaternion2.Y; + float rz = quaternion2.Z; + float rw = quaternion2.W; + float lx = quaternion1.X; + float ly = quaternion1.Y; + float lz = quaternion1.Z; + float lw = quaternion1.W; + float yz = (ry * lz) - (rz * ly); + float xz = (rz * lx) - (rx * lz); + float xy = (rx * ly) - (ry * lx); + float lengthSq = ((rx * lx) + (ry * ly)) + (rz * lz); + + quaternion.X = ((rx * lw) + (lx * rw)) + yz; + quaternion.Y = ((ry * lw) + (ly * rw)) + xz; + quaternion.Z = ((rz * lw) + (lz * rw)) + xy; + quaternion.W = (rw * lw) - lengthSq; + + return quaternion; + } + + void Quaternion::Concatenate(Quaternion quaternion1, Quaternion quaternion2, out Quaternion result) + { + float rx = quaternion2.X; + float ry = quaternion2.Y; + float rz = quaternion2.Z; + float rw = quaternion2.W; + float lx = quaternion1.X; + float ly = quaternion1.Y; + float lz = quaternion1.Z; + float lw = quaternion1.W; + float yz = (ry * lz) - (rz * ly); + float xz = (rz * lx) - (rx * lz); + float xy = (rx * ly) - (ry * lx); + float lengthSq = ((rx * lx) + (ry * ly)) + (rz * lz); + + result.X = ((rx * lw) + (lx * rw)) + yz; + result.Y = ((ry * lw) + (ly * rw)) + xz; + result.Z = ((rz * lw) + (lz * rw)) + xy; + result.W = (rw * lw) - lengthSq; + } + + void Quaternion::Conjugate() + { + X = -X; + Y = -Y; + Z = -Z; + } + + Quaternion Quaternion::Conjugate(Quaternion value) + { + Quaternion result; + result.X = -value.X; + result.Y = -value.Y; + result.Z = -value.Z; + result.W = value.W; + return result; + } + + void Quaternion::Conjugate(Quaternion value, out Quaternion result) + { + result.X = -value.X; + result.Y = -value.Y; + result.Z = -value.Z; + result.W = value.W; + } + + Quaternion Quaternion::CreateFromAxisAngle(Vector3 axis, float angle) + { + Quaternion result; + + Vector3::Normalize(axis, axis); + + float half = angle * 0.5f; + float Sin = Math::Sin(half); + float Cos = Math::Cos(half); + + result.X = axis.X * Sin; + result.Y = axis.Y * Sin; + result.Z = axis.Z * Sin; + result.W = Cos; + + return result; + } + + void Quaternion::CreateFromAxisAngle(Vector3 axis, float angle, out Quaternion result) + { + Vector3::Normalize(axis, axis); + + float half = angle * 0.5f; + float Sin = Math::Sin(half); + float Cos = Math::Cos(half); + + result.X = axis.X * Sin; + result.Y = axis.Y * Sin; + result.Z = axis.Z * Sin; + result.W = Cos; + } + + Quaternion Quaternion::CreateFromRotationMatrix(Matrix matrix) + { + Quaternion result; + float scale = matrix.M11 + matrix.M22 + matrix.M33; + + if(scale >0.0f) + { + float Sqrt = Math::Sqrt(scale + 1.0f); + + result.W = Sqrt + 0.5f; + Sqrt = 0.5f / Sqrt; + + result.X = (matrix.M23 - matrix.M32) * Sqrt; + result.Y = (matrix.M31 - matrix.M13) * Sqrt; + result.Z = (matrix.M12 - matrix.M21) * Sqrt; + + return result; + } + + if((matrix.M11 >= matrix.M22) && (matrix.M11 >= matrix.M33)) + { + float Sqrt = Math::Sqrt(1.0f + matrix.M11 - matrix.M22 - matrix.M33); + float half = 0.f / Sqrt; + + result.X = 0.5f * Sqrt; + result.Y = (matrix.M12 + matrix.M21) * half; + result.Z = (matrix.M13 + matrix.M31) * half; + result.W = (matrix.M23 - matrix.M32) * half; + + return result; + } + + if(matrix.M22 > matrix.M33) + { + float Sqrt = Math::Sqrt(1.0f + matrix.M22 - matrix.M11 - matrix.M33); + float half = 0.5f / Sqrt; + + result.X = (matrix.M21 + matrix.M12) * half; + result.Y = 0.5f * Sqrt; + result.Z = (matrix.M32 + matrix.M23) * half; + result.W = (matrix.M31 - matrix.M21) * half; + + return result; + } + + float Sqrt = Math::Sqrt(1.0f + matrix.M33 - matrix.M11 - matrix.M22); + float half = 0.5f / Sqrt; + + result.X = (matrix.M31 + matrix.M13) * half; + result.Y = (matrix.M32 + matrix.M23) * half; + result.Z = 0.5f * Sqrt; + result.W = (matrix.M12 - matrix.M21) * half; + + return result; + } + + void Quaternion::CreateFromRotationMatrix(Matrix matrix, out Quaternion result) + { + float scale = matrix.M11 + matrix.M22 + matrix.M33; + + if(scale >0.0f) + { + float Sqrt = Math::Sqrt(scale + 1.0f); + + result.W = Sqrt + 0.5f; + Sqrt = 0.5f / Sqrt; + + result.X = (matrix.M23 - matrix.M32) * Sqrt; + result.Y = (matrix.M31 - matrix.M13) * Sqrt; + result.Z = (matrix.M12 - matrix.M21) * Sqrt; + return; + } + + if((matrix.M11 >= matrix.M22) && (matrix.M11 >= matrix.M33)) + { + float Sqrt = Math::Sqrt(1.0f + matrix.M11 - matrix.M22 - matrix.M33); + float half = 0.f / Sqrt; + + result.X = 0.5f * Sqrt; + result.Y = (matrix.M12 + matrix.M21) * half; + result.Z = (matrix.M13 + matrix.M31) * half; + result.W = (matrix.M23 - matrix.M32) * half; + return; + } + + if(matrix.M22 > matrix.M33) + { + float Sqrt = Math::Sqrt(1.0f + matrix.M22 - matrix.M11 - matrix.M33); + float half = 0.5f / Sqrt; + + result.X = (matrix.M21 + matrix.M12) * half; + result.Y = 0.5f * Sqrt; + result.Z = (matrix.M32 + matrix.M23) * half; + result.W = (matrix.M31 - matrix.M21) * half; + return; + } + + float Sqrt = Math::Sqrt(1.0f + matrix.M33 - matrix.M11 - matrix.M22); + float half = 0.5f / Sqrt; + + result.X = (matrix.M31 + matrix.M13) * half; + result.Y = (matrix.M32 + matrix.M23) * half; + result.Z = 0.5f * Sqrt; + result.W = (matrix.M12 - matrix.M21) * half; + } + + Quaternion Quaternion::CreateFromYawPitchRoll(float yaw, float pitch, float roll) + { + Quaternion result; + + float halfRoll = roll * 0.5f; + float sinRoll = Math::Sin(halfRoll); + float cosRoll = Math::Cos(halfRoll); + float halfPitch = pitch * 0.5f; + float sinPitch = Math::Sin(halfPitch); + float cosPitch = Math::Cos(halfPitch); + float halfYaw = yaw * 0.5f; + float sinYaw = Math::Sin(halfYaw); + float cosYaw = Math::Cos(halfYaw); + + result.X = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll); + result.Y = (sinYaw * cosPitch * cosRoll) + (cosYaw * sinPitch * sinRoll); + result.Z = (cosYaw * cosPitch * sinRoll) + (sinYaw * sinPitch * cosRoll); + result.W = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll); + + return result; + } + + void Quaternion::CreateFromYawPitchRoll(float yaw, float pitch, float roll, out Quaternion result) + { + float halfRoll = roll * 0.5f; + float sinRoll = Math::Sin(halfRoll); + float cosRoll = Math::Cos(halfRoll); + float halfPitch = pitch * 0.5f; + float sinPitch = Math::Sin(halfPitch); + float cosPitch = Math::Cos(halfPitch); + float halfYaw = yaw * 0.5f; + float sinYaw = Math::Sin(halfYaw); + float cosYaw = Math::Cos(halfYaw); + + result.X = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll); + result.Y = (sinYaw * cosPitch * cosRoll) + (cosYaw * sinPitch * sinRoll); + result.Z = (cosYaw * cosPitch * sinRoll) + (sinYaw * sinPitch * cosRoll); + result.W = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll); + } + + Quaternion Quaternion::Divide(Quaternion quaternion1, Quaternion quaternion2) + { + Quaternion result; + result.X = quaternion1.X / quaternion2.X; + result.Y = quaternion1.Y / quaternion2.Y; + result.Z = quaternion1.Z / quaternion2.Z; + result.W = quaternion1.W / quaternion2.W; + return result; + } + + void Quaternion::Divide(Quaternion quaternion1, Quaternion quaternion2, out Quaternion result) + { + result.X = quaternion1.X / quaternion2.X; + result.Y = quaternion1.Y / quaternion2.Y; + result.Z = quaternion1.Z / quaternion2.Z; + result.W = quaternion1.W / quaternion2.W; + } + + float Quaternion::Dot(Quaternion quaternion1, Quaternion quaternion2) + { + return (quaternion1.X * quaternion2.X) + (quaternion1.Y * quaternion2.Y) + (quaternion1.Z * quaternion2.Z) + (quaternion1.W * quaternion2.W); + } + + void Quaternion::Dot(Quaternion quaternion1, Quaternion quaternion2, out float result) + { + result = (quaternion1.X * quaternion2.X) + (quaternion1.Y * quaternion2.Y) + (quaternion1.Z * quaternion2.Z) + (quaternion1.W * quaternion2.W); + } + + bool Quaternion::Equals(Quaternion obj) + { + return ((X == obj.X) && (Y == obj.Y) && (Z == obj.Z) && (W == obj.W)); + } + + Quaternion Quaternion::Inverse(Quaternion quaternion) + { + Quaternion result; + float lengthSq = 1.0f / ( (quaternion.X * quaternion.X) + (quaternion.Y * quaternion.Y) + (quaternion.Z * quaternion.Z) + (quaternion.W * quaternion.W) ); + result.X = -quaternion.X * lengthSq; + result.Y = -quaternion.Y * lengthSq; + result.Z = -quaternion.Z * lengthSq; + result.W = quaternion.W * lengthSq; + return result; + } + + void Quaternion::Inverse(Quaternion quaternion, out Quaternion result) + { + float lengthSq = 1.0f / ( (quaternion.X * quaternion.X) + (quaternion.Y * quaternion.Y) + (quaternion.Z * quaternion.Z) + (quaternion.W * quaternion.W) ); + result.X = -quaternion.X * lengthSq; + result.Y = -quaternion.Y * lengthSq; + result.Z = -quaternion.Z * lengthSq; + result.W = quaternion.W * lengthSq; + } + + float Quaternion::Length() + { + return Math::Sqrt((X * X) + (Y * Y) + (Z * Z) + (W * W)); + } + + float Quaternion::LengthSquared() + { + return (X * X) + (Y * Y) + (Z * Z) + (W * W); + } + + Quaternion Quaternion::Lerp(Quaternion quaternion1, Quaternion quaternion2, float amount) + { + Quaternion result; + result.X = MathHelper::Lerp(quaternion1.X, quaternion2.X, amount); + result.Y = MathHelper::Lerp(quaternion1.Y, quaternion2.Y, amount); + result.Z = MathHelper::Lerp(quaternion1.Z, quaternion2.Z, amount); + result.W = MathHelper::Lerp(quaternion1.W, quaternion2.W, amount); + return result; + } + + void Quaternion::Lerp(Quaternion quaternion1, Quaternion quaternion2, float amount, out Quaternion result) + { + result.X = MathHelper::Lerp(quaternion1.X, quaternion2.X, amount); + result.Y = MathHelper::Lerp(quaternion1.Y, quaternion2.Y, amount); + result.Z = MathHelper::Lerp(quaternion1.Z, quaternion2.Z, amount); + result.W = MathHelper::Lerp(quaternion1.W, quaternion2.W, amount); + } + + Quaternion Quaternion::Multiply(Quaternion quaternion1, Quaternion quaternion2) + { + Quaternion result; + float rx = quaternion2.X; + float ry = quaternion2.Y; + float rz = quaternion2.Z; + float rw = quaternion2.W; + float lx = quaternion1.X; + float ly = quaternion1.Y; + float lz = quaternion1.Z; + float lw = quaternion1.W; + float yz = (ry * lz) - (rz * ly); + float xz = (rz * lx) - (rx * lz); + float xy = (rx * ly) - (ry * lx); + float lengthSq = ((rx * lx) + (ry * ly)) + (rz * lz); + + result.X = ((rx * lw) + (lx * rw)) + yz; + result.Y = ((ry * lw) + (ly * rw)) + xz; + result.Z = ((rz * lw) + (lz * rw)) + xy; + result.W = (rw * lw) - lengthSq; + + return result; + } + + void Quaternion::Multiply(Quaternion quaternion1, Quaternion quaternion2, out Quaternion result) + { + float rx = quaternion2.X; + float ry = quaternion2.Y; + float rz = quaternion2.Z; + float rw = quaternion2.W; + float lx = quaternion1.X; + float ly = quaternion1.Y; + float lz = quaternion1.Z; + float lw = quaternion1.W; + float yz = (ry * lz) - (rz * ly); + float xz = (rz * lx) - (rx * lz); + float xy = (rx * ly) - (ry * lx); + float lengthSq = ((rx * lx) + (ry * ly)) + (rz * lz); + + result.X = ((rx * lw) + (lx * rw)) + yz; + result.Y = ((ry * lw) + (ly * rw)) + xz; + result.Z = ((rz * lw) + (lz * rw)) + xy; + result.W = (rw * lw) - lengthSq; + } + + Quaternion Quaternion::Multiply(Quaternion quaternion, float scaleFactor) + { + Quaternion result; + result.X = quaternion.X * scaleFactor; + result.Y = quaternion.Y * scaleFactor; + result.Z = quaternion.Z * scaleFactor; + result.W = quaternion.W * scaleFactor; + return result; + } + + void Quaternion::Multiply(Quaternion quaternion, float scaleFactor, out Quaternion result) + { + result.X = quaternion.X * scaleFactor; + result.Y = quaternion.Y * scaleFactor; + result.Z = quaternion.Z * scaleFactor; + result.W = quaternion.W * scaleFactor; + } + + Quaternion Quaternion::Negate(Quaternion quaternion) + { + Quaternion result; + result.X = -quaternion.X; + result.Y = -quaternion.Y; + result.Z = -quaternion.Z; + result.W = -quaternion.W; + return result; + } + + void Quaternion::Negate(Quaternion quaternion, out Quaternion result) + { + result.X = -quaternion.X; + result.Y = -quaternion.Y; + result.Z = -quaternion.Z; + result.W = -quaternion.W; + } + + void Quaternion::Normalize() + { + float length = 1.0f / Length(); + X *= length; + Y *= length; + Z *= length; + W *= length; + } + + Quaternion Quaternion::Slerp(Quaternion quaternion1, Quaternion quaternion2, float amount) + { + Quaternion result; + + float opposite; + float inverse; + float dot = (quaternion1.X * quaternion2.X) + (quaternion1.Y * quaternion2.Y) + (quaternion1.Z * quaternion2.Z) + (quaternion1.W * quaternion2.W); + int flag = false; + + if( dot < 0.0f ) + { + flag = true; + dot = -dot; + } + + if( dot > 0.999999f ) + { + inverse = 1.0f - amount; + opposite = flag ? -amount : amount; + } + else + { + float Acos = Math::Acos(dot); + float invSin = (1.0f / Math::Sin(Acos)); + + inverse = (Math::Sin((1.0f - amount) * Acos)* invSin); + opposite = flag ? ( -Math::Sin(amount * Acos ) * invSin) : (Math::Sin(amount * Acos) * invSin); + } + + result.X = (inverse * quaternion1.X) + (opposite * quaternion2.X); + result.Y = (inverse * quaternion1.Y) + (opposite * quaternion2.Y); + result.Z = (inverse * quaternion1.Z) + (opposite * quaternion2.Z); + result.W = (inverse * quaternion1.W) + (opposite * quaternion2.W); + + return result; + } + + void Quaternion::Slerp(Quaternion quaternion1, Quaternion quaternion2, float amount, out Quaternion result) + { + float opposite; + float inverse; + float dot = (quaternion1.X * quaternion2.X) + (quaternion1.Y * quaternion2.Y) + (quaternion1.Z * quaternion2.Z) + (quaternion1.W * quaternion2.W); + int flag = false; + + if( dot < 0.0f ) + { + flag = true; + dot = -dot; + } + + if( dot > 0.999999f ) + { + inverse = 1.0f - amount; + opposite = flag ? -amount : amount; + } + else + { + float Acos = Math::Acos(dot); + float invSin = (1.0f / Math::Sin(Acos)); + + inverse = (Math::Sin((1.0f - amount) * Acos)* invSin); + opposite = flag ? ( -Math::Sin(amount * Acos ) * invSin) : (Math::Sin(amount * Acos) * invSin); + } + + result.X = (inverse * quaternion1.X) + (opposite * quaternion2.X); + result.Y = (inverse * quaternion1.Y) + (opposite * quaternion2.Y); + result.Z = (inverse * quaternion1.Z) + (opposite * quaternion2.Z); + result.W = (inverse * quaternion1.W) + (opposite * quaternion2.W); + } + + Quaternion Quaternion::Subtract(Quaternion quaternion1, Quaternion quaternion2) + { + return Quaternion(quaternion1.X - quaternion2.X, quaternion1.Y - quaternion2.Y, quaternion1.Z - quaternion2.Z, quaternion1.W - quaternion2.W); + } + + void Quaternion::Subtract(Quaternion quaternion1, Quaternion quaternion2, out Quaternion result) + { + result.X = quaternion1.X - quaternion2.X; + result.Y = quaternion1.Y - quaternion2.Y; + result.Z = quaternion1.Z - quaternion2.Z; + result.W = quaternion1.W - quaternion2.W; + } + + const Quaternion Quaternion::operator+(const Quaternion other) + { + Quaternion result; + result.X = X + other.X; + result.Y = Y + other.Y; + result.Z = Z + other.Z; + result.W = W + other.W; + return result; + } + + const Quaternion Quaternion::operator/(const Quaternion other) + { + Quaternion result; + result.X = X / other.X; + result.Y = Y / other.Y; + result.Z = Z / other.Z; + result.W = W / other.W; + return result; + } + + bool Quaternion::operator==(const Quaternion other) + { + return Equals(other); + } + + bool Quaternion::operator!=(const Quaternion other) + { + return !Equals(other); + } + + const Quaternion Quaternion::operator*(const Quaternion other) + { + Quaternion result; + float rx = other.X; + float ry = other.Y; + float rz = other.Z; + float rw = other.W; + float lx = X; + float ly = Y; + float lz = Z; + float lw = W; + float yz = (ry * lz) - (rz * ly); + float xz = (rz * lx) - (rx * lz); + float xy = (rx * ly) - (ry * lx); + float lengthSq = ((rx * lx) + (ry * ly)) + (rz * lz); + + result.X = ((rx * lw) + (lx * rw)) + yz; + result.Y = ((ry * lw) + (ly * rw)) + xz; + result.Z = ((rz * lw) + (lz * rw)) + xy; + result.W = (rw * lw) - lengthSq; + + return result; + } + + const Quaternion Quaternion::operator*(const float scaleFactor) + { + Quaternion result; + result.X = X * scaleFactor; + result.Y = Y * scaleFactor; + result.Z = Z * scaleFactor; + result.W = W * scaleFactor; + return result; + } + + const Quaternion Quaternion::operator-(const Quaternion other) + { + Quaternion result; + result.X = X - other.X; + result.Y = Y - other.Y; + result.Z = Z - other.Z; + result.W = W - other.W; + return result; + } + + const Quaternion Quaternion::operator-() + { + Quaternion result; + result.X = -X; + result.Y = -Y; + result.Z = -Z; + result.W = -W; + return result; + } + + Quaternion Quaternion::operator=(const Quaternion other) + { + X = other.X; + Y = other.Y; + Z = other.Z; + W = other.W; + return *this; + } +} diff --git a/src/libXFX/Ray.cpp b/src/libXFX/Ray.cpp new file mode 100644 index 0000000..afdc0bf --- /dev/null +++ b/src/libXFX/Ray.cpp @@ -0,0 +1,262 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include +#include + +using namespace System; + +namespace XFX +{ + Ray::Ray(Vector3 direction, Vector3 position) + { + Direction = direction; + Position = position; + } + + Ray::Ray(const Ray &obj) + { + Direction = obj.Direction; + Position = obj.Position; + } + + Ray::Ray() + { + Direction = Vector3::Zero; + Position = Vector3::Zero; + } + + bool Ray::Equals(Ray obj) + { + return ((Direction == obj.Direction) && (Position == obj.Position)); + } + + int Ray::GetHashCode() + { + return (Direction.GetHashCode() ^ Position.GetHashCode()); + } + + float Ray::Intersects(BoundingBox boundingbox) + { + float distance; + float d = 0.0f; + float MAXValue = MAXFLOAT; + + if (Math::Abs( Direction.X ) < 0.0000001) + { + if (Position.X < boundingbox.Min.X || Position.X > boundingbox.Max.X) + { + distance = 0.0f; + return distance; + } + } + else + { + float inv = 1.0f / Direction.X; + float MIN = (boundingbox.Min.X - Position.X) * inv; + float MAX = (boundingbox.Max.X - Position.X) * inv; + + if (MIN > MAX) + { + float temp = MIN; + MIN = MAX; + MAX = temp; + } + + d = Math::Max(MIN, d); + MAXValue = Math::Min(MAX, MAXValue); + + if (d > MAXValue) + { + distance = 0.0f; + return distance; + } + } + + if (Math::Abs(Direction.Y) < 0.0000001) + { + if (Position.Y < boundingbox.Min.Y || Position.Y > boundingbox.Max.Y) + { + distance = 0.0f; + return distance; + } + } + else + { + float inv = 1.0f / Direction.Y; + float MIN = (boundingbox.Min.Y - Position.Y) * inv; + float MAX = (boundingbox.Max.Y - Position.Y) * inv; + + if (MIN > MAX) + { + float temp = MIN; + MIN = MAX; + MAX = temp; + } + + d = Math::Max( MIN, d ); + MAXValue = Math::Min(MAX, MAXValue); + + if( d > MAXValue ) + { + distance = 0.0f; + return distance; + } + } + + if( Math::Abs( Direction.Z ) < 0.0000001 ) + { + if( Position.Z < boundingbox.Min.Z || Position.Z > boundingbox.Max.Z ) + { + distance = 0.0f; + return distance; + } + } + else + { + float inv = 1.0f / Direction.Z; + float MIN = (boundingbox.Min.Z - Position.Z) * inv; + float MAX = (boundingbox.Max.Z - Position.Z) * inv; + + if( MIN > MAX ) + { + float temp = MIN; + MIN = MAX; + MAX = temp; + } + + d = Math::Max( MIN, d ); + MAXValue = Math::Min( MAX, MAXValue ); + + if( d > MAXValue ) + { + distance = 0.0f; + return distance; + } + } + + distance = d; + return distance; + } + + void Ray::Intersects(BoundingBox boundingbox, out float distance) + { + distance = Intersects(boundingbox); + } + + float Ray::Intersects(BoundingSphere sphere) + { + float distance; + float x = sphere.Center.X - Position.X; + float y = sphere.Center.Y - Position.Y; + float z = sphere.Center.Z - Position.Z; + float pyth = (x * x) + (y * y) + (z * z); + float rr = sphere.Radius * sphere.Radius; + + if( pyth <= rr ) + { + distance = 0.0f; + return distance; + } + + float dot = (x * Direction.X) + (y * Direction.Y) + (z * Direction.Z); + if( dot < 0.0f ) + { + distance = 0.0f; + return distance; + } + + float temp = pyth - (dot * dot); + if( temp > rr ) + { + distance = 0.0f; + return distance; + } + + distance = dot - Math::Sqrt(rr - temp); + return distance; + } + + void Ray::Intersects(BoundingSphere sphere, out float distance) + { + distance = Intersects(sphere); + } + + float Ray::Intersects(Plane plane) + { + float dotDirection = (plane.Normal.X * Direction.X) + (plane.Normal.Y * Direction.Y) + (plane.Normal.Z * Direction.Z); + float distance; + + if( Math::Abs( dotDirection ) < 0.000001f ) + { + distance = 0.0f; + return distance; + } + + float dotPosition = (plane.Normal.X * Position.X) + (plane.Normal.Y * Position.Y) + (plane.Normal.Z * Position.Z); + float num = ( -plane.D - dotPosition ) / dotDirection; + + if( num < 0.0f ) + { + if( num < -0.000001f ) + { + distance = 0.0f; + return distance; + } + num = 0.0f; + } + + distance = num; + return distance; + } + + void Ray::Intersects(Plane plane, out float distance) + { + distance = Intersects(plane); + } + + bool Ray::operator==(const Ray other) + { + return Equals(other); + } + + bool Ray::operator!=(const Ray other) + { + return !Equals(other); + } + + Ray Ray::operator=(const Ray other) + { + Direction = other.Direction; + Position = other.Position; + return *this; + } +} diff --git a/src/libXFX/Rectangle.cpp b/src/libXFX/Rectangle.cpp new file mode 100644 index 0000000..28d21d8 --- /dev/null +++ b/src/libXFX/Rectangle.cpp @@ -0,0 +1,160 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include + +namespace XFX +{ + const Rectangle Rectangle::Empty = Rectangle(0, 0, 0, 0); + + Rectangle::Rectangle(int x, int y, int width, int height) + { + X = x; + Y = y; + Width = width; + Height = height; + } + + Rectangle::Rectangle(const Rectangle &obj) + { + X = obj.X; + Y = obj.Y; + Width = obj.Width; + Height = obj.Height; + } + + Rectangle::Rectangle() + { + X = 0; + Y = 0; + Width = 0; + Height = 0; + } + + int Rectangle::Bottom() + { + return Y + Height; + } + + int Rectangle::Left() + { + return X; + } + + int Rectangle::Right() + { + return X + Width; + } + + int Rectangle::Top() + { + return Y; + } + + int Rectangle::Contains(int x, int y) + { + return ((x >= X) && (y >=Y) && (x <= Right()) && (y <= Bottom())); + } + + int Rectangle::Contains(Point pt) + { + return ((pt.X >= X) && (pt.Y >=Y) && (pt.X <= Right()) && (pt.Y <= Bottom())); + } + + void Rectangle::Contains(Point pt, out int result) + { + result = ((pt.X >= X) && (pt.Y >=Y) && (pt.X <= Right()) && (pt.Y <= Bottom())); + } + + int Rectangle::Contains(Rectangle other) + { + return ((other.X >= X) && (other.Y >= Y) && (other.Bottom() <= Bottom()) && (other.Right() <= Right())); + } + + void Rectangle::Contains(Rectangle other, out int result) + { + result = ((other.X >= X) && (other.Y >= Y) && (other.Bottom() <= Bottom()) && (other.Right() <= Right())); + } + + int Rectangle::Equals(const Rectangle obj) + { + return ((X == obj.X) && (Y == obj.Y) && (Width == obj.Width) && (Height == obj.Height)); + } + + int Rectangle::GetHashCode() + { + return X ^ Y ^ Width ^ Height; + } + + void Rectangle::Inflate(int horizontalAmount, int verticalAmount) + { + Width += horizontalAmount; + Height += verticalAmount; + } + + int Rectangle::Intersects(Rectangle other) + { + return ((Contains(other.Left(), other.Top())) || (Contains(other.Left(), other.Bottom())) || (Contains(other.Right(), other.Top())) || (Contains(other.Right(),other.Bottom()))); + } + + void Rectangle::Intersects(Rectangle other, out int result) + { + result = Intersects(other); + } + + void Rectangle::Offset(int x, int y) + { + X += x; + Y += y; + } + + void Rectangle::Offset(Point pt) + { + X += pt.X; + Y += pt.Y; + } + + int Rectangle::operator==(const Rectangle other) + { + return Equals(other); + } + + int Rectangle::operator!=(const Rectangle other) + { + return !Equals(other); + } + + Rectangle &Rectangle::operator=(const Rectangle other) + { + X = other.X; + Y = other.Y; + Width = other.Width; + Height = other.Height; + return *this; + } +} diff --git a/src/libXFX/SpriteBatch.cpp b/src/libXFX/SpriteBatch.cpp new file mode 100644 index 0000000..e3dc5d3 --- /dev/null +++ b/src/libXFX/SpriteBatch.cpp @@ -0,0 +1,325 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace XFX; + +namespace XFX +{ + namespace Graphics + { + SpriteBatch::GraphicsDevice_() + { + return device; + spriteBlendMode = SpriteBlendMode::None + } + + SpriteBatch::IsDisposed() + { + return disposed; + } + + SpriteBatch::~SpriteBatch() + { + Dispose(false); + } + + SpriteBatch::SpriteBatch(GraphicsDevice graphicsDevice) + { + device = graphicsDevice; + } + + void SpriteBatch::Begin() + { + Begin(SpriteBlendMode::AlphaBlend, SpriteSortMode::Deferred, SaveStateMode::None, Matrix::Identity); + } + + void SpriteBatch::Begin(SpriteBlendMode blendMode, SpriteSortMode sortMode, SaveStateMode stateMode) + { + Begin(blendMode, sortMode, stateMode, Matrix::Identity); + } + + void Begin(SpriteBlendMode blendMode, SpriteSortMode sortMode, SaveStateMode stateMode, Matrix transformMatrix) + { + //to respect order Begin/Draw/end + if (isRunning) + return; + + if (stateMode == SaveStateMode::SaveState) + saveState = StateBlock(device); + + spriteBlendMode = blendMode; + this.sortMode = sortMode; + if (sortMode == SpriteSortMode::Immediate) + applyGraphicsDeviceSettings(); + isRunning = true; + } + + void SpriteBatch::Dispose(int disposing) + { + if (!disposed) + { + if (disposing) + { + // Release any managed components + } + disposed = true; + // Release any unmanaged components + } + } + + void SpriteBatch::Dispose() + { + Dispose(true); + } + + void SpriteBatch::Draw(Texture2D &texture, Rectangle &destinationRectangle, Color &color) + { + Draw(texture, destinationRectangle, Rectangle::Zero, color, 0f, Vector2::Zero, SpriteEffects::None, 0f); + } + + void SriteBatch::Draw(Texture2D &texture, Rectangle &destinationRectangle, Rectangle &sourceRectangle, Color &color) + { + Draw(texture, destinationRectangle, sourceRectangle, color, 0f, Vector2::Zero, SpriteEffects::None, 0f); + } + + void SpriteBatch::Draw(Texture2D &texture, Vector2 &position, Color &color) + { + Draw(texture, position, Rectangle::Zero, color); + } + + void SpriteBatch::Draw(Texture2D &texture, Vector2 &position, Rectangle &sourceRectangle, Color &color) + { + Rectangle destination = Rectangle((int)vector.X, (int)vector.Y, texture.Width, texture.Height); + Draw(texture, destination, sourceRectangle, color, 0f, Vector2::Zero, SpriteEffects::None, 0f); + } + + void SpriteBatch::Draw(Texture2D &texture, Vector2 &position, Rectangle &sourceRectangle, Color &color, float rotation, Vector2 &origin, float scale, SpriteEffects_t effects, float layerDepth) + { + int width; + int height; + if (sourceRectangle != Rectangle::Zero) + { + width = (int)(sourceRectangle.Width * scale); + height = (int)(sourceRectangle.Height * scale); + } + else + { + width = (int)(texture.Width * scale); + height = (int)(texture.Height * scale); + } + Rectangle destination = Rectangle((int)vector.X, (int)vector.Y, width, height); + Draw(texture, destination, sourceRectangle, color, rotation, origin, effects, layerDepth); + } + + void SpriteBatch::Draw(Texture2D &texture, Vector2 &position, Rectangle &sourceRectangle, Color &color, float rotation, Vector2 &origin, Vector2 &scale, SpriteEffects_t effects, float layerDepth) + { + int width; + int height; + if (sourceRectangle != Rectangle::Zero) + { + width = (int)(sourceRectangle.Width * scale.X); + height = (int)(sourceRectangle.Height * scale.Y); + } + else + { + width = (int)(texture.Width * scale.X); + height = (int)(texture.Height * scale.Y); + } + Rectangle destination = Rectangle((int)vector.X, (int)vector.Y, width, height); + Draw(texture, destination, sourceRectangle, color, rotation, origin, effects, layerDepth); + } + + void SpriteBatch::Draw(Texture2D &texture, Rectangle &destinationRectangle, Rectangle &sourceRectangle, Color &color, float rotation, Vector2 &origin, SpriteEffects_t &effects, float layerDepth) + { + if (!isRunning) + return; + + Sprite temp = Sprite(texture, (sourceRectangle != Rectangle::Zero) ? sourceRectangle : Rectangle(0, 0, texture.Width, texture.Height), + destinationRectangle, color, rotation, origin, effects, layerDepth); + + spriteList.Add(temp); + + if (sortMode == SpriteSortMode::Immediate) + flush(); + } + + void SpriteBatch::DrawString(SpriteFont &spriteFont, char* text, Vector2 &position, Color &color) + { + if (!spriteFont) + return; + if (!text) + return; + + spriteFont.Draw(text, *this, position, color, 0f, Vector2::Zero, Vector2::One, SpriteEffects::None, 0f); + } + + void SpriteBatch::DrawString(SpriteFont &spriteFont, char* text, Vector2 &position, Color &color, float rotation, Vector2 &origin, float scale, SpriteEffects_t effects, float layerDepth) + { + Vector2 vector; + if (!spriteFont) + return; + if (!text) + return; + + vector.X = scale; + vector.Y = scale; + spriteFont.Draw(text, *this, position, color, rotation, origin, vector, effects, layerDepth); + } + + void SpriteBatch::End() + { + if (!isRunning) + return; + + if (sortMode != SpriteSortMode::Immediate) + { + applyGraphicsDeviceSettings(); + flush(); + } + + glDisable(GL_TEXTURE_2D); + + Gl::glMatrixMode(Gl::GL_PROJECTION); + Gl::glPopMatrix(); + Gl::glMatrixMode(Gl::GL_MODELVIEW); + Gl::glPopMatrix(); + + restoreRenderState(); + isRunning = false; + } + + void SpriteBatch::restoreRenderState() + { + if (stateMode == SaveStateMode::SaveState) + saveState.Apply(); + } + + void SpriteBatch::flush() + { + switch (sortMode) + { + case SpriteSortMode::BackToFront: + spriteList.Sort(BackToFrontSpriteComparer()); + break; + case SpriteSortMode::FrontToBack: + spriteList.Sort(FrontToBackSpriteComparer()); + break; + case SpriteSortMode::Texture: // nothing here? + break; + } + + spriteList.First(); + Sprite temp; + while(spriteList.Next(temp)) + { + // Set the color, bind the texture for drawing and prepare the texture source + if (temp.Color.A <= 0) continue; + Gl::glColor4f((float)temp.Color.R / 255f, (float)temp.Color.G / 255f, (float)temp.Color.B / 255f, (float)temp.Color.A / 255f); + Gl::glBindTexture(Gl::GL_TEXTURE_2D, temp.Texture.textureId); + + // Setup the matrix + Gl::glPushMatrix(); + if ((temp.DestinationRectangle.X != 0) || (temp.DestinationRectangle.Y != 0)) + Gl::glTranslatef(temp.DestinationRectangle.X, temp.DestinationRectangle.Y, 0f); // Position + if (temp.Rotation != 0) + Gl::glRotatef(MathHelper.ToDegrees(temp.Rotation), 0f, 0f, 1f); // Rotation + if ((temp.DestinationRectangle.Width != 0 && temp.Origin.X != 0) || (temp.DestinationRectangle.Height != 0 && temp.Origin.Y != 0)) + Gl::glTranslatef( // Orientation + -temp.Origin.X * (float)temp.DestinationRectangle.Width / (float)temp.SourceRectangle.Width, + -temp.Origin.Y * (float)temp.DestinationRectangle.Height / (float)temp.SourceRectangle.Height, 0f); + + // Calculate the points on the texture + float x = (float)temp.SourceRectangle.X / (float)temp.Texture.Width; + float y = (float)temp.SourceRectangle.Y / (float)temp.Texture.Height; + float twidth = (float)temp.SourceRectangle.Width / (float)temp.Texture.Width; + float theight = (float)temp.SourceRectangle.Height / (float)temp.Texture.Height; + + // Draw + Gl::glBegin(Gl::GL_QUADS); + { + Gl::glTexCoord2f(x,y + theight); + Gl::glVertex2f(0f, temp.DestinationRectangle.Height); + + Gl::glTexCoord2f(x + twidth, y + theight); + Gl::glVertex2f(temp.DestinationRectangle.Width, temp.DestinationRectangle.Height); + + Gl::glTexCoord2f(x + twidth,y); + Gl::glVertex2f(temp.DestinationRectangle.Width, 0f); + + Gl::glTexCoord2f(x,y); + Gl::glVertex2f(0f, 0f); + } + Gl::glEnd(); + Gl::glPopMatrix(); // Finish with the matrix + } + spriteList.Clear(); + } + + void SpriteBatch::applyGraphicsDeviceSettings() + { + // Set the blend mode + switch (spriteBlendMode) + { + case SpriteBlendMode::AlphaBlend: + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + break; + case SpriteBlendMode::Additive: + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + break; + case SpriteBlendMode::None: + glDisable(GL_BLEND); + break; + default: + return; + } + + glEnable(GL_TEXTURE_2D); + + // Reset the projection matrix and use the orthographic matrix + int[] viewPort = new int[4]; + Gl::glGetIntegerv(Gl::GL_VIEWPORT, viewPort); + Gl::glMatrixMode(Gl::GL_PROJECTION); + Gl::glPushMatrix(); + Gl::glLoadIdentity(); + Gl::glOrtho(0, viewPort[2], viewPort[3], 0, -1, 1); // viewPort[2] = width, viewPort[3] = height + Gl::glMatrixMode(Gl::GL_MODELVIEW); + Gl::glPushMatrix(); + Gl::glLoadIdentity(); + } + } +} diff --git a/src/libXFX/StorageContainer.cpp b/src/libXFX/StorageContainer.cpp new file mode 100644 index 0000000..1d3513e --- /dev/null +++ b/src/libXFX/StorageContainer.cpp @@ -0,0 +1,110 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +extern "C" { +#if ENABLE_XBOX +#include +#else +#endif +} + +#include +#include + +namespace XFX +{ + namespace Storage + { + bool StorageContainer::IsDisposed() + { + return isDisposed; + } + + StorageContainer::~StorageContainer() + { + Dispose(false); + } + + void StorageContainer::Delete() + { + containerFolder.Delete(true); + } + + void StorageContainer::Dispose() + { + Dispose(true); + } + + void StorageContainer::Dispose(bool disposing) + { + if (!this._isDisposed) + { + isDisposed = true; + if (disposing && (Disposing != null)) + { + Disposing(this, EventArgs::Empty); + } + } + } + + char* StorageContainer::TitleLocation() + { +#if ENABLE_XBOX + //XBOX returns the XeImageFileName like \device\harddisk0\partition2\apps\default.xbe + // we need to map the partitions, and strip the \default.xbe from this string + + // copy the XeImageFileName to tmp, and strip the \default.xbe + //char *tmp = strncpy(tmp, XeImageFileName->Buffer, XeImageFileName->Length - 12); + + char szTemp[MAX_PATH]; + char cDriveLetter = 0; + + strncpy(szTemp, XeImageFileName->Buffer + 12, XeImageFileName->Length - 12); + szTemp[20] = 0; + GetDrive(szTemp, &cDriveLetter); + + strncpy(szTemp, XeImageFileName->Buffer + 29, XeImageFileName->Length - 29); + szTemp[XeImageFileName->Length - 29] = 0; + + sprintf(szDest, "%c:\\%s", cDriveLetter, szTemp); + return szDest; +#else + GetCurrentDirectory(XBMC_MAX_PATH, szDest); + strcat(szDest, "\\XBMC_PC.exe"); + return szDest; +#endif + } + + char* StorageContainer::TitleName() + { +#if ENABLE_XBOX + //! TODO: Read the Title field from the XBE header +#else +#endif + } + } +} diff --git a/src/libXFX/StorageDevice.cpp b/src/libXFX/StorageDevice.cpp new file mode 100644 index 0000000..d87b6f5 --- /dev/null +++ b/src/libXFX/StorageDevice.cpp @@ -0,0 +1,55 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include + +namespace XFX +{ + namespace Storage + { + long long StorageDevice::FreeSpace() + { + } + + bool StorageDevice::IsConnected() + { + } + + long long StorageDevice::TotalSpace() + { + } + + StorageContainer StorageDevice::OpenContainer(char* titleName) + { + if(String::IsNullOrEmpty(titleName)) + throw ArgumentNullException("Non-null title name required."); + + //return StorageContainer(*this, titleName, _playerSpecified, _playerIndex); + } + } +} diff --git a/src/libXFX/StorageDeviceNotConnectedException.cpp b/src/libXFX/StorageDeviceNotConnectedException.cpp new file mode 100644 index 0000000..61c4421 --- /dev/null +++ b/src/libXFX/StorageDeviceNotConnectedException.cpp @@ -0,0 +1,48 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace XFX +{ + namespace Storage + { + StorageDeviceNotConnectedException::StorageDeviceNotConnectedException() + { + } + + StorageDeviceNotConnectedException::StorageDeviceNotConnectedException(char* message) + : ExternalException(message) + { + } + + StorageDeviceNotConnectedException::StorageDeviceNotConnectedException(char* message, Exception innerException) + : ExternalException(message, innerException) + { + } + } +} diff --git a/src/libXFX/Texture.cpp b/src/libXFX/Texture.cpp new file mode 100644 index 0000000..20bc1af --- /dev/null +++ b/src/libXFX/Texture.cpp @@ -0,0 +1,98 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace XFX; + +namespace XFX +{ + namespace Graphics + { + Texture Texture::FromFile(GraphicsDevice graphicsDevice, char* filename, TextureCreationParameters creationParameters) + { + TextureInformation texinfo = GetTextureInformation(filename); + if (creationParameters.Width == 0) creationParameters.Width = texinfo.Width; + if (creationParameters.Height == 0) creationParameters.Height = texinfo.Height; + if (creationParameters.Depth == 0) creationParameters.Depth = texinfo.Depth; + /*if (texinfo.ResourceType == ResourceType::Texture2D) + { + int ImgID; + Il::ilGenImages(1, out ImgID); + Il::ilBindImage(ImgID); + Il::ilLoadImage(filename); + int width = Il::ilGetInteger(Il::IL_IMAGE_WIDTH); + int height = Il::ilGetInteger(Il::IL_IMAGE_HEIGHT); + int depth = Il::ilGetInteger(Il::IL_IMAGE_DEPTH); + int size = Il::ilGetInteger(Il::IL_IMAGE_SIZE_OF_DATA); + Texture2D tex = Texture2D(graphicsDevice, creationParameters.Width, creationParameters.Height, creationParameters.Depth, TextureUsage::None, SurfaceFormat::Rgb32); + int[] texture = int[1]; + Gl::glGenTextures(1,texture); + tex.textureId = texture[0]; + Gl::glBindTexture(Gl::GL_TEXTURE_2D, tex.textureId); + Gl::glTexImage2D(Gl::GL_TEXTURE_2D, 0, Il::ilGetInteger(Il::IL_IMAGE_BYTES_PER_PIXEL), creationParameters.Width, creationParameters.Height, 0, Gl::GL_RGBA, Gl::GL_UNSIGNED_BYTE, Il::ilGetData()); + Gl::glTexParameteri(Gl::GL_TEXTURE_2D, Gl::GL_TEXTURE_MIN_FILTER, Gl::GL_LINEAR); + Gl::glTexParameteri(Gl::GL_TEXTURE_2D, Gl::GL_TEXTURE_MAG_FILTER, Gl::GL_LINEAR); + Il::ilBindImage(0); + //Il::ilDeleteImage(0); + return tex; + } */ + else if (texinfo.ResourceType_ == ResourceType::Texture3D) { } + else if (texinfo.ResourceType_ == ResourceType::Texture3DVolume) { } //FIXME: Should we handle this here too? + else if (texinfo.ResourceType_ == ResourceType::TextureCube) { } + } + + TextureInformation Texture::GetTextureInformation(char* filename) + { + FileStream FS; + try + { + FS = File::OpenRead(filename); + } + catch(Exception) + { + } + FS.Close(); + + TextureInformation TexInfo; + //TexInfo.Depth = Il::ilGetInteger(Il::IL_IMAGE_DEPTH); + TexInfo.Format = SurfaceFormat::Color; //TODO: Find out how to detect and set properly. + //TexInfo.Height = Il::ilGetInteger(Il::IL_IMAGE_HEIGHT); + //TexInfo.imageFormat = ILimageformat2XNAimageformat(Il::ilGetInteger(Il::IL_IMAGE_FORMAT)); + TexInfo.ResourceType_ = ResourceType::Texture2D; //TODO: Find out how to detect and set properly. + //TexInfo.Width = Il::ilGetInteger(Il::IL_IMAGE_WIDTH); + return TexInfo; + } + } +} diff --git a/src/libXFX/Texture2D.cpp b/src/libXFX/Texture2D.cpp new file mode 100644 index 0000000..41734fe --- /dev/null +++ b/src/libXFX/Texture2D.cpp @@ -0,0 +1,155 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include + +using namespace XFX; + +namespace XFX +{ + namespace Graphics + { + SurfaceFormat_t Texture2D::Format() + { + return _surfaceFormat; + } + + int Texture2D::Height() + { + return _height; + } + + TextureUsage_t Texture2D::TextureUsage_() + { + return _textureUsage; + } + + int Texture2D::Width() + { + return _width; + } + + Texture2D::Texture2D(GraphicsDevice graphicsDevice) + { + textureId = -1; + device = graphicsDevice; + } + + Texture2D::Texture2D(GraphicsDevice graphicsDevice, int width, int height) + { + textureId = -1; + device = graphicsDevice; + _width = width; + _height = height; + } + + Texture2D::Texture2D(GraphicsDevice graphicsDevice, int width, int height, int numberLevels, TextureUsage_t usage, SurfaceFormat_t format) + { + textureId = -1; + device = graphicsDevice; + _width = width; + _height = height; + _numberOfLevels = numberLevels; + _textureUsage = usage; + _surfaceFormat = format; + } + + void Texture2D::Dispose(bool disposing) + { + if(!_isDisposed) + { + try + { + //Gl::glDeleteTextures(1, int[] { textureId }); + } + catch(Exception) + { + + } + if(device.Textures.textures.Contains(this)) + device.Textures.textures.Remove(this); + } + _isDisposed = true; + } + + void Texture2D::Load(byte buffer[]) + { + /*imageId = Il::ilGenImage(); + Il::ilBindImage(imageId); + Il::ilLoadL(Il::IL_JPG, buffer, buffer.Length); + + int[] texture = int[1]; + Gl::glGenTextures(1, texture); + textureId = texture[0]; + Gl::glBindTexture(Gl::GL_TEXTURE_2D, textureId); + Gl::glTexImage2D(Gl::GL_TEXTURE_2D, 0, Il::ilGetInteger(Il::IL_IMAGE_BYTES_PER_PIXEL), _width, _height, 0, Gl::GL_RGBA, Gl::GL_UNSIGNED_BYTE, Il::ilGetData()); + Gl::glTexParameteri(Gl::GL_TEXTURE_2D, Gl::GL_TEXTURE_MIN_FILTER, Gl::GL_LINEAR); + Gl::glTexParameteri(Gl::GL_TEXTURE_2D, Gl::GL_TEXTURE_MAG_FILTER, Gl::GL_LINEAR);*/ + } + + void Texture2D::SetData(T data[]) + { + Rectangle rect; + SetData(0, rect, data, 0, data.Length, SetDataOptions::None); + } + + void Texture2D::SetData(T data[], int startIndex, int elementCount, SetDataOptions_t options) + { + Rectangle rect; + SetData(0, rect, data, startIndex, elementCount, options); + } + + void Texture2D::SetData(int level, Rectangle rect, T data[], int startIndex, int elementCount, SetDataOptions_t options) + { + if (textureId == -1 || options == SetDataOptions::NoOverwrite) + { + int[] texture = new int[1]; + Gl::glGenTextures(1, texture); + textureId = texture[0]; + } + Gl::glBindTexture(Gl::GL_TEXTURE_2D, textureId); + switch (surfaceFormat) + { + case SurfaceFormat::Color: + Gl::glTexImage2D(Gl::GL_TEXTURE_2D, 0, 4, _width, _height, 0, Gl::GL_BGRA, Gl::GL_UNSIGNED_BYTE, data); + break; + case SurfaceFormat::Dxt1: + Gl::glCompressedTexImage2D(Gl::GL_TEXTURE_2D, 0, Gl::GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, _width, _height, 0, elementCount, data); + break; + case SurfaceFormat::Dxt3: + Gl::glCompressedTexImage2D(Gl::GL_TEXTURE_2D, 0, Gl::GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, _width, _height, 0, elementCount, data); + break; + case SurfaceFormat::Dxt5: + Gl::glCompressedTexImage2D(Gl::GL_TEXTURE_2D, 0, Gl::GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, _width, _height, 0, elementCount, data); + break; + } + Gl::glTexParameteri(Gl::GL_TEXTURE_2D, Gl::GL_TEXTURE_MIN_FILTER, Gl::GL_LINEAR); + Gl::glTexParameteri(Gl::GL_TEXTURE_2D, Gl::GL_TEXTURE_MAG_FILTER, Gl::GL_LINEAR); + } + } +} diff --git a/src/libXFX/TextureCreationParameters.cpp b/src/libXFX/TextureCreationParameters.cpp new file mode 100644 index 0000000..c67448d --- /dev/null +++ b/src/libXFX/TextureCreationParameters.cpp @@ -0,0 +1,107 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace XFX +{ + namespace Graphics + { + TextureCreationParameters::TextureCreationParameters(int width, int height, int depth, int mipLevels, SurfaceFormat_t format, + TextureUsage_t textureUsage, Color colorKey, FilterOptions_t filter, FilterOptions_t mipFilter) + { + Width = width; + Height = height; + Depth = depth; + MipLevels = mipLevels; + Format = format; + ColorKey = colorKey; + Filter = filter; + MipFilter = mipFilter; + } + + TextureCreationParameters::TextureCreationParameters(const TextureCreationParameters &obj) + { + Width = obj.width; + Height = obj.height; + Depth = obj.depth; + MipLevels = obj.mipLevels; + Format = obj.format; + ColorKey = obj.colorKey; + Filter = obj.filter; + MipFilter = obj.mipFilter; + } + + TextureCreationParameters::TextureCreationParameters() + { + Default = TextureCreationParameters( + 0, 0, 0, 0, + SurfaceFormat::Unknown, + TextureUsage::None, + Color::TransparentBlack, + FilterOptions::Dither | FilterOptions::Triangle, + FilterOptions::Box); + } + + bool TextureCreationParameters::Equals(TextureCreationParameters other) + { + return ((Width == other.Width) && (Height == other.Height) && + (Depth == other.Depth) && (MipLevels == other.MipLevels) && + (Format == other.Format) && (ColorKey == other.ColorKey) && + (Filter == other.Filter) && (MipFilter == other.MipFilter)); + } + + int TextureCreationParameters::GetHashCode() + { + return (Width ^ Height ^ Depth ^ MipLevels ^ Format ^ Filter ^ MipFilter); + } + // + // Operators + // + bool TextureCreationParameters::operator !=(TextureCreationParameters other) + { + return !Equals(other); + } + + bool TextureCreationParameters::operator ==(TextureCreationParameters other) + { + return Equals(other); + } + + bool TextureCreationParameters::operator =(TextureCreationParameters other) + { + Width = other.Width; + Height = other.Height; + Depth = other.Depth; + MipLevels = other.MipLevels; + Format = other.Format; + ColorKey = other.ColorKey; + Filter = other.Filter; + MipFilter = other.MipFilter; + } + } +} diff --git a/src/libXFX/TextureInformation.cpp b/src/libXFX/TextureInformation.cpp new file mode 100644 index 0000000..c40ac73 --- /dev/null +++ b/src/libXFX/TextureInformation.cpp @@ -0,0 +1,106 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include + +namespace XFX +{ + namespace Graphics + { + TextureInformation::TextureInformation(int width, int height, int depth, int mipLevels, SurfaceFormat_t format) + { + Width = width; + Height = height; + Depth = depth; + MipLevels = mipLevels; + Format = format; + ImageFormat = ImageFileFormat::Jpg; + ResourceType_ = ResourceType::Texture2D; + } + + TextureInformation::TextureInformation(const TextureInformation &obj) + { + Width = obj.Width; + Height = obj.Height; + Depth = obj.Depth; + Format = obj.Format; + MipLevels = obj.MipLevels; + ResourceType_ = obj.ResourceType; + ImageFormat = obj.ImageFormat; + } + + TextureInformation::TextureInformation() + { + ImageFormat = ImageFileFormat::Jpg; + ResourceType_ = ResourceType::Texture2D; + } + + bool TextureInformation::Equals(TextureInformation other) + { + return ((Width = other.Width) && (Height == other.Height) && + (Depth == other.Depth) && (Format == other.Format) && + (ImageFormat == other.ImageFormat) && (MipLevels == other.MipLevels) && + (ResourceType_ == other.ResourceType_)); + } + + int TextureInformation::GetHashCode() + { + return (Width ^ Height ^ Depth ^ Format ^ MipLevels ^ ImageFormat ^ ResourceType_); + } + + char* TextureInformation::ToString() + { + char* buf; + sprintf(buf, "{Width:%d Height:%d Format:%d Depth:%d MipLevels:%d}", Width, Height, Format, Depth, MipLevels); + return buf; + } + // + // Operators + // + bool TextureInformation::operator!=(TextureInformation other) + { + return !Equals(other); + } + + bool TextureInformation::operator==(TextureInformation other) + { + return Equals(other); + } + + TextureInformation TextureInformation::operator =(TextureInformation other) + { + Width = other.Width; + Height = other.Height; + Depth = other.Depth; + Format = other.Format; + MipLevels = other.MipLevels; + ResourceType_ = other.ResourceType; + ImageFormat = other.ImageFormat; + } + } +} diff --git a/src/libXFX/Vector2.cpp b/src/libXFX/Vector2.cpp new file mode 100644 index 0000000..ee8f272 --- /dev/null +++ b/src/libXFX/Vector2.cpp @@ -0,0 +1,526 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace System; + +namespace XFX +{ + const Vector2 Vector2::One = Vector2(1,1); + const Vector2 Vector2::Zero = Vector2(0,0); + + Vector2::Vector2(float x, float y) + { + X = x; + Y = y; + } + + Vector2::Vector2(float value) + { + X = value; + Y = value; + } + + Vector2::Vector2(const Vector2 &obj) + { + X = obj.X; + Y = obj.Y; + } + + Vector2::Vector2() + { + X = 0; + Y = 0; + } + + Vector2 Vector2::Add(Vector2 value1, Vector2 value2) + { + return Vector2(value1.X + value2.X, value1.Y + value2.Y); + } + + void Vector2::Add(Vector2 value1, Vector2 value2, Vector2 result) + { + result.X = value1.X + value2.X; + result.Y = value1.Y + value2.Y; + } + + Vector2 Vector2::Baricentric(Vector2 value1, Vector2 value2, Vector2 value3, float amount1, float amount2) + { + return Vector2(MathHelper::Baricentric(value1.X, value2.X, value3.X, amount1, amount2), + MathHelper::Baricentric(value1.Y, value2.Y, value3.Y, amount1, amount2)); + } + + void Vector2::Baricentric(Vector2 value1, Vector2 value2, Vector2 value3, float amount1, float amount2, out Vector2 result) + { + result.X = MathHelper::Baricentric(value1.X, value2.X, value3.X, amount1, amount2); + result.Y = MathHelper::Baricentric(value1.Y, value2.Y, value3.Y, amount1, amount2); + } + + Vector2 Vector2::CatmullRom(Vector2 value1, Vector2 value2, Vector2 value3, Vector2 value4, float amount) + { + return Vector2(MathHelper::CatmullRom(value1.X, value2.X, value3.X, value4.X, amount), + MathHelper::CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount)); + } + + void Vector2::CatmullRom(Vector2 value1, Vector2 value2, Vector2 value3, Vector2 value4, float amount, out Vector2 result) + { + result.X = MathHelper::CatmullRom(value1.X, value2.X, value3.X, value4.X, amount); + result.Y = MathHelper::CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount); + } + + Vector2 Vector2::Clamp(Vector2 value, Vector2 min, Vector2 max) + { + return Vector2(MathHelper::Clamp(value.X, min.X, max.X), MathHelper::Clamp(value.Y, min.Y, max.Y)); + } + + void Vector2::Clamp(Vector2 value, Vector2 min, Vector2 max, out Vector2 result) + { + result.X = MathHelper::Clamp(value.X, min.X, max.X); + result.Y = MathHelper::Clamp(value.Y, min.Y, max.Y); + } + + float Vector2::Distance(Vector2 value1, Vector2 value2) + { + float x = value1.X - value2.X; + float y = value1.Y - value2.Y; + return Math::Sqrt((x*x) + (y*y)); + } + + void Vector2::Distance(Vector2 value1, Vector2 value2, out float result) + { + float x = value1.X - value2.X; + float y = value1.Y - value2.Y; + result = Math::Sqrt((x*x) + (y*y)); + } + + float Vector2::DistanceSquared(Vector2 value1, Vector2 value2) + { + float x = value1.X - value2.X; + float y = value1.Y - value2.Y; + return (x*x) + (y*y); + } + + void Vector2::DistanceSquared(Vector2 value1, Vector2 value2, out float result) + { + float x = value1.X - value2.X; + float y = value1.Y - value2.Y; + result = (x*x) + (y*y); + } + + float Vector2::Dot(Vector2 value1, Vector2 value2) + { + return (value1.X * value2.X + value1.Y * value2.Y); + } + + void Vector2::Dot(Vector2 value1, Vector2 value2, out float result) + { + result = (value1.X * value2.X + value1.Y * value2.Y); + } + + bool Vector2::Equals(Vector2 other) + { + return ((X == other.X) & (Y == other.Y)); + } + + int Vector2::GetHashCode() + { + return (int)X ^ (int)Y; + } + + Vector2 Vector2::Hermite(Vector2 value1, Vector2 tangent1, Vector2 value2, Vector2 tangent2, float amount) + { + return Vector2(MathHelper::Hermite(value1.X,tangent1.X,value2.X,tangent2.X,amount),MathHelper::Hermite(value1.Y,tangent1.Y,value2.Y,tangent2.Y,amount)); + } + + void Vector2::Hermite(Vector2 value1, Vector2 tangent1, Vector2 value2, Vector2 tangent2, float amount, out Vector2 result) + { + result.X = MathHelper::Hermite(value1.X,tangent1.X,value2.X,tangent2.X,amount); + result.Y = MathHelper::Hermite(value1.Y,tangent1.Y,value2.Y,tangent2.Y,amount); + } + + float Vector2::Length() + { + return Math::Sqrt((X*X) + (Y*Y)); + } + + float Vector2::LengthSquared() + { + return (X*X) + (Y*Y); + } + + Vector2 Vector2::Lerp(Vector2 value1, Vector2 value2, float amount) + { + return Vector2(MathHelper::Lerp(value1.X, value2.X, amount), MathHelper::Lerp(value1.Y, value2.Y, amount)); + } + + void Vector2::Lerp(Vector2 value1, Vector2 value2, float amount, out Vector2 result) + { + result.X = MathHelper::Lerp(value1.X, value2.X, amount); + result.Y = MathHelper::Lerp(value1.Y, value2.Y, amount); + } + + Vector2 Vector2::Max(Vector2 value1, Vector2 value2) + { + return Vector2((value1.X > value2.X) ? value1.X : value2.X,(value1.Y > value2.Y) ? value1.Y : value2.Y); + } + + void Vector2::Max(Vector2 value1, Vector2 value2, out Vector2 result) + { + result.X = (value1.X > value2.X) ? value1.X : value2.X; + result.Y = (value1.Y > value2.Y) ? value1.Y : value2.Y; + } + + Vector2 Vector2::Min(Vector2 value1, Vector2 value2) + { + return Vector2((value1.X < value2.X) ? value1.X : value2.X, (value1.Y < value2.Y) ? value1.Y : value2.Y); + } + + void Vector2::Min(Vector2 value1, Vector2 value2, out Vector2 result) + { + result.X = (value1.X < value2.X) ? value1.X : value2.X; + result.Y = (value1.Y < value2.Y) ? value1.Y : value2.Y; + } + + Vector2 Vector2::Multiply(Vector2 value, float scaleFactor) + { + return Vector2(value.X * scaleFactor, value.Y * scaleFactor); + } + + void Vector2::Multiply(Vector2 value, float scaleFactor, out Vector2 result) + { + result.X = value.X * scaleFactor; + result.Y = value.Y * scaleFactor; + } + + Vector2 Vector2::Multiply(Vector2 value1, Vector2 value2) + { + return Vector2(value1.X * value2.X, value1.Y * value2.Y); + } + + void Vector2::Multiply(Vector2 value1, Vector2 value2, out Vector2 result) + { + result.X = value1.X * value2.X; + result.Y = value1.Y * value2.Y; + } + + Vector2 Vector2::Negate(Vector2 value) + { + return Vector2(-value.X, -value.Y); + } + + void Vector2::Negate(Vector2 value, out Vector2 result) + { + result.X = -value.X; + result.Y = -value.Y; + } + + void Vector2::Normalize() + { + float length = Length(); + if( length == 0 ) + return; + float num = 1 / length; + X *= num; + Y *= num; + } + + Vector2 Vector2::Normalize(Vector2 value) + { + float length = value.Length(); + if( length == 0 ) + return Vector2::Zero; + float num = 1 / length; + return Vector2((value.X *= num), (value.Y *= num)); + } + + void Vector2::Normalize(Vector2 value, out Vector2 result) + { + float length = value.Length(); + if( length == 0 ) + return; + float num = 1 / length; + result.X *= num; + result.Y *= num; + } + + Vector2 Vector2::Reflect(Vector2 vector, Vector2 normal) + { + float dp = Dot(vector, normal); + return Vector2(vector.X - normal.X * dp, vector.Y - normal.Y * dp); + } + + void Vector2::Reflect(Vector2 vector, Vector2 normal, out Vector2 result) + { + float dp = Dot(vector, normal); + result.X = vector.X - normal.X * dp; + result.Y = vector.Y - normal.Y * dp; + } + + Vector2 Vector2::SmoothStep(Vector2 value1, Vector2 value2, float amount) + { + return Vector2( + MathHelper::SmoothStep(value1.X, value2.X, amount), + MathHelper::SmoothStep(value1.Y, value2.Y, amount)); + } + + void Vector2::SmoothStep(Vector2 value1, Vector2 value2, float amount, out Vector2 result) + { + result.X = MathHelper::SmoothStep(value1.X, value2.X, amount); + result.Y = MathHelper::SmoothStep(value1.Y, value2.Y, amount); + } + + Vector2 Vector2::Subtract(Vector2 value1, Vector2 value2) + { + return Vector2(value1.X - value2.X, value1.Y - value2.Y); + } + + void Vector2::Subtract(Vector2 value1, Vector2 value2, out Vector2 result) + { + result.X = value1.X - value2.X; + result.Y = value1.Y - value2.Y; + } + + Vector2 Vector2::Transform(Vector2 position, Matrix matrix) + { + Vector2 result; + Transform(position, matrix, result); + return result; + } + + void Vector2::Transform(Vector2 position, Matrix matrix, out Vector2 result) + { + Vector4 vector; + + vector.X = (vector.X * matrix.M11) + (vector.Y * matrix.M21) + matrix.M41; + vector.Y = (vector.X * matrix.M12) + (vector.Y * matrix.M22) + matrix.M42; + vector.Z = (vector.X * matrix.M13) + (vector.Y * matrix.M23) + matrix.M43; + vector.W = 1 / ((vector.X * matrix.M14) + (vector.Y * matrix.M24) + matrix.M44); + + result.X = vector.X * vector.W; + result.Y = vector.Y * vector.W; + } + + Vector2 Vector2::Transform(Vector2 position, Quaternion rotation) + { + Vector2 result; + Transform(position, rotation, result); + return result; + } + + void Vector2::Transform(Vector2 position, Quaternion rotation, out Vector2 result) + { + Quaternion quat = Quaternion(position.X, position.Y, 0, 0), i, t; + Quaternion::Inverse(rotation, i); + Quaternion::Multiply(rotation, quat, t); + Quaternion::Multiply(t, i, quat); + + result.X = quat.X; + result.Y = quat.Y; + } + + void Vector2::Transform(Vector2 sourceArray[], int sourceIndex, Matrix matrix, Vector2 destinationArray[], int destinationIndex, int length) + { + if (sourceArray == null) + throw ArgumentNullException("sourceArray"); + + if (destinationArray == null) + throw ArgumentNullException("destinationArray"); + + for(int i = sourceIndex, j = destinationIndex; i < (sourceIndex + length); i++, j++) + { + TransformNormal(sourceArray[i], matrix, destinationArray[j]); + } + } + + void Vector2::Transform(Vector2 sourceArray[], int sourceIndex, Quaternion rotation, Vector2 destinationArray[], int destinationIndex, int length) + { + if (sourceArray == null) + throw ArgumentNullException("sourceArray"); + + if (destinationArray == null) + throw ArgumentNullException("destinationArray"); + + for(int i = sourceIndex, j = destinationIndex; i < (sourceIndex + length); i++, j++) + { + Transform(sourceArray[i], rotation, destinationArray[j]); + } + } + + void Vector2::Transform(Vector2 sourceArray[], Matrix matrix, Vector2 destinationArray[]) + { + if (sourceArray == null) + throw ArgumentNullException("sourceArray"); + + if (destinationArray == null) + throw ArgumentNullException("destinationArray"); + + if(Array::Length(destinationArray) < Array::Length(sourceArray)) + throw ArgumentException("destinationArray too small."); + + for(int i = 0; i < Array::Length(sourceArray); i++) + { + Transform(sourceArray[i], matrix, destinationArray[i]); + } + } + + void Vector2::Transform(Vector2 sourceArray[], Quaternion rotation, Vector2 destinationArray[]) + { + if (sourceArray == null) + throw ArgumentNullException("sourceArray"); + + if (destinationArray == null) + throw ArgumentNullException("destinationArray"); + + if(Array::Length(destinationArray) < Array::Length(sourceArray)) + throw ArgumentException("destinationArray too small."); + + for(int i = 0; i < Array::Length(sourceArray); i++) + { + Transform(sourceArray[i], rotation, destinationArray[i]); + } + } + + Vector2 Vector2::TransformNormal(Vector2 normal, Matrix matrix) + { + Vector2 result; + result.X = (normal.X * matrix.M11) + (normal.Y * matrix.M21); + result.Y = (normal.X * matrix.M12) + (normal.Y * matrix.M22); + + return result; + } + + void Vector2::TransformNormal(Vector2 normal, Matrix matrix, out Vector2 result) + { + result.X = (normal.X * matrix.M11) + (normal.Y * matrix.M21); + result.Y = (normal.X * matrix.M12) + (normal.Y * matrix.M22); + } + + void Vector2::TransformNormal(Vector2 sourceArray[], int sourceIndex, Matrix matrix, Vector2 destinationArray[], int destinationIndex, int length) + { + if (sourceArray == null) + throw ArgumentNullException("sourceArray"); + + if (destinationArray == null) + throw ArgumentNullException("destinationArray"); + + for(int i = sourceIndex, j = destinationIndex; i < (sourceIndex + length); i++, j++) + { + TransformNormal(sourceArray[i], matrix, destinationArray[j]); + } + } + + void Vector2::TransformNormal(Vector2 sourceArray[], Matrix matrix, Vector2 destinationArray[]) + { + if (sourceArray == null) + throw ArgumentNullException("sourceArray"); + + if (destinationArray == null) + throw ArgumentNullException("destinationArray"); + + if(Array::Length(destinationArray) < Array::Length(sourceArray)) + throw ArgumentException("destinationArray too small."); + + for(int i = 0; i < Array::Length(sourceArray); i++) + { + TransformNormal(sourceArray[i], matrix, destinationArray[i]); + } + } + + Vector2 Vector2::operator+(const Vector2 other) + { + X += other.X; + Y += other.Y; + return *this; + } + + Vector2 Vector2::operator/(float divider) + { + X /= divider; + Y /= divider; + return *this; + } + + Vector2 Vector2::operator/(const Vector2 other) + { + X /= other.X; + Y /= other.Y; + return *this; + } + + bool Vector2::operator==(const Vector2 other) + { + return Equals(other); + } + + bool Vector2::operator!=(const Vector2 other) + { + return !Equals(other); + } + + Vector2 Vector2::operator*(const float scaleFactor) + { + X *= scaleFactor; + Y *= scaleFactor; + return *this; + } + + Vector2 Vector2::operator*(const Vector2 other) + { + X *= other.X; + Y *= other.Y; + return *this; + } + + Vector2 Vector2::operator-(const Vector2 other) + { + X -= other.X; + Y -= other.Y; + return *this; + } + + Vector2 Vector2::operator-() + { + X = -X; + Y = -Y; + return *this; + } + + Vector2 Vector2::operator=(const Vector2 other) + { + X = other.X; + Y = other.Y; + return *this; + } +} diff --git a/src/libXFX/Vector3.cpp b/src/libXFX/Vector3.cpp new file mode 100644 index 0000000..df7be0a --- /dev/null +++ b/src/libXFX/Vector3.cpp @@ -0,0 +1,672 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace System; + +namespace XFX +{ + const Vector3 Vector3::Backward = Vector3(0, 0, 1); + const Vector3 Vector3::Down = Vector3(0, -1, 0); + const Vector3 Vector3::Forward = Vector3(0, 0, -1); + const Vector3 Vector3::Left = Vector3(-1, 0, 0); + const Vector3 Vector3::One = Vector3(1, 1, 1); + const Vector3 Vector3::Right = Vector3(1, 0, 0); + const Vector3 Vector3::UnitX = Vector3(1, 0, 0); + const Vector3 Vector3::UnitY = Vector3(0, 1, 0); + const Vector3 Vector3::UnitZ = Vector3(0, 0, 1); + const Vector3 Vector3::Up = Vector3(0, 1, 0); + const Vector3 Vector3::Zero = Vector3(0, 0, 0); + + Vector3::Vector3(float value) + { + X = value; + Y = value; + Z = value; + } + + Vector3::Vector3(float x, float y, float z) + { + X = x; + Y = y; + Z = z; + } + + Vector3::Vector3(Vector2 value, float z) + { + X = value.X; + Y = value.Y; + Z = z; + } + + Vector3::Vector3(const Vector3 &obj) + { + X = obj.X; + Y = obj.Y; + Z = obj.Z; + } + + Vector3::Vector3() + { + X = 0; + Y = 0; + Z = 0; + } + + Vector3 Vector3::Add(Vector3 value1, Vector3 value2) + { + return Vector3(value1.X + value2.X, value1.Y + value2.Y, value1.Z + value2.Z); + } + + void Vector3::Add(Vector3 value1, Vector3 value2, out Vector3 result) + { + result.X = value1.X + value2.X; + result.Y = value1.Y + value2.Y; + result.Z = value1.Z + value2.Z; + } + + Vector3 Vector3::Baricentric(Vector3 value1, Vector3 value2, Vector3 value3, float amount1, float amount2) + { + Vector3 result; + result.X = MathHelper::Baricentric(value1.X, value2.X, value3.X, amount1, amount2); + result.Z = MathHelper::Baricentric(value1.X, value2.X, value3.X, amount1, amount2); + result.X = MathHelper::Baricentric(value1.X, value2.X, value3.X, amount1, amount2); + return result; + } + + void Vector3::Baricentric(Vector3 value1, Vector3 value2, Vector3 value3, float amount1, float amount2, out Vector3 result) + { + result.X = MathHelper::Baricentric(value1.X, value2.X, value3.X, amount1, amount2); + result.Z = MathHelper::Baricentric(value1.X, value2.X, value3.X, amount1, amount2); + result.X = MathHelper::Baricentric(value1.X, value2.X, value3.X, amount1, amount2); + } + + Vector3 Vector3::CatmullRom(Vector3 value1, Vector3 value2, Vector3 value3, Vector3 value4, float amount) + { + Vector3 result; + result.X = MathHelper::CatmullRom(value1.X, value2.X, value3.X, value4.X, amount); + result.Y = MathHelper::CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount); + result.Z = MathHelper::CatmullRom(value1.Z, value2.Z, value3.Z, value4.Z, amount); + return result; + } + + void Vector3::CatmullRom(Vector3 value1, Vector3 value2, Vector3 value3, Vector3 value4, float amount, out Vector3 result) + { + result.X = MathHelper::CatmullRom(value1.X, value2.X, value3.X, value4.X, amount); + result.Y = MathHelper::CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount); + result.Z = MathHelper::CatmullRom(value1.Z, value2.Z, value3.Z, value4.Z, amount); + } + + Vector3 Vector3::Clamp(Vector3 value1, Vector3 min, Vector3 max) + { + Vector3 result; + result.X = MathHelper::Clamp(value1.X, min.X, max.X); + result.Y = MathHelper::Clamp(value1.Y, min.Y, max.Y); + result.Z = MathHelper::Clamp(value1.Z, min.Z, max.Z); + return result; + } + + void Vector3::Clamp(Vector3 value1, Vector3 min, Vector3 max, out Vector3 result) + { + result.X = MathHelper::Clamp(value1.X, min.X, max.X); + result.Y = MathHelper::Clamp(value1.Y, min.Y, max.Y); + result.Z = MathHelper::Clamp(value1.Z, min.Z, max.Z); + } + + Vector3 Vector3::Cross(Vector3 vector1, Vector3 vector2) + { + Vector3 result; + result.X = vector1.Y * vector2.Z - vector1.Z * vector2.Y; + result.Y = vector1.Z * vector2.X - vector1.X * vector2.Z; + result.Z = vector1.X * vector2.Y - vector1.Y * vector2.X; + return result; + } + + void Vector3::Cross(Vector3 vector1, Vector3 vector2, out Vector3 result) + { + result.X = vector1.Y * vector2.Z - vector1.Z * vector2.Y; + result.Y = vector1.Z * vector2.X - vector1.X * vector2.Z; + result.Z = vector1.X * vector2.Y - vector1.Y * vector2.X; + } + + float Vector3::Distance(Vector3 value1, Vector3 value2) + { + float x = value1.X - value2.X; + float y = value1.Y - value2.Y; + float z = value1.Z - value2.Z; + + return Math::Sqrt((x*x) + (y*y) + (z*z)); + } + + void Vector3::Distance(Vector3 value1, Vector3 value2, out float result) + { + float x = value1.X - value2.X; + float y = value1.Y - value2.Y; + float z = value1.Z - value2.Z; + + result = Math::Sqrt((x*x) + (y*y) + (z*z)); + } + + float Vector3::DistanceSquared(Vector3 value1, Vector3 value2) + { + float x = value1.X - value2.X; + float y = value1.Y - value2.Y; + float z = value1.Z - value2.Z; + + return (x*x) + (y*y) + (z*z); + } + + void Vector3::DistanceSquared(Vector3 value1, Vector3 value2, out float result) + { + float x = value1.X - value2.X; + float y = value1.Y - value2.Y; + float z = value1.Z - value2.Z; + + result = (x*x) + (y*y) + (z*z); + } + + Vector3 Vector3::Divide(Vector3 value1, float value2) + { + return Vector3(value1.X / value2, value1.Y / value2, value1.Z / value2); + } + + void Vector3::Divide(Vector3 value1, float value2, out Vector3 result) + { + result.X = value1.X / value2; + result.Y = value1.Y / value2; + result.Z = value1.Z / value2; + } + + Vector3 Vector3::Divide(Vector3 value1, Vector3 value2) + { + Vector3 result; + result.X = value1.X / value2.X; + result.Y = value1.Y / value2.Y; + result.Z = value1.Z / value2.Z; + return result; + } + + void Vector3::Divide(Vector3 value1, Vector3 value2, out Vector3 result) + { + result.X = value1.X / value2.X; + result.Y = value1.Y / value2.Y; + result.Z = value1.Z / value2.Z; + } + + float Vector3::Dot(Vector3 value1, Vector3 value2) + { + return (value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z); + } + + void Vector3::Dot(Vector3 value1, Vector3 value2, out float result) + { + result = (value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z); + } + + bool Vector3::Equals(Vector3 obj) + { + return ((X == obj.X) && (Y == obj.Y) && (Z == obj.Z)); + } + + int Vector3::GetHashCode() + { + return ((int)X ^ (int)Y ^ (int)Z); + } + + Vector3 Vector3::Hermite(Vector3 value1, Vector3 tangent1, Vector3 value2, Vector3 tangent2, float amount) + { + Vector3 result; + result.X = MathHelper::Hermite(value1.X, tangent1.X, value2.X, tangent2.X, amount); + result.Y = MathHelper::Hermite(value1.Y, tangent1.Y, value2.Y, tangent2.Y, amount); + result.Z = MathHelper::Hermite(value1.Z, tangent1.Z, value2.Z, tangent2.Z, amount); + return result; + } + + void Vector3::Hermite(Vector3 value1, Vector3 tangent1, Vector3 value2, Vector3 tangent2, float amount, out Vector3 result) + { + result.X = MathHelper::Hermite(value1.X, tangent1.X, value2.X, tangent2.X, amount); + result.Y = MathHelper::Hermite(value1.Y, tangent1.Y, value2.Y, tangent2.Y, amount); + result.Z = MathHelper::Hermite(value1.Z, tangent1.Z, value2.Z, tangent2.Z, amount); + } + + float Vector3::Length() + { + return Math::Sqrt((X * X) + (Y * Y) + (Z * Z)); + } + + float Vector3::LengthSquared() + { + return (X * X) + (Y * Y) + (Z * Z); + } + + Vector3 Vector3::Lerp(Vector3 value1, Vector3 value2, float amount) + { + Vector3 result; + result.X = MathHelper::Lerp(value1.X, value2.X, amount); + result.Y = MathHelper::Lerp(value1.Y, value2.Y, amount); + result.Z = MathHelper::Lerp(value1.Z, value2.Z, amount); + return result; + } + + void Vector3::Lerp(Vector3 value1, Vector3 value2, float amount, out Vector3 result) + { + result.X = MathHelper::Lerp(value1.X, value2.X, amount); + result.Y = MathHelper::Lerp(value1.Y, value2.Y, amount); + result.Z = MathHelper::Lerp(value1.Z, value2.Z, amount); + } + + Vector3 Vector3::Max(Vector3 value1, Vector3 value2) + { + Vector3 result; + result.X = (value1.X > value2.X) ? value1.X : value2.X; + result.Y = (value1.Y > value2.Y) ? value1.Y : value2.Y; + result.Z = (value1.Z > value2.Z) ? value1.Z : value2.Z; + return result; + } + + void Vector3::Max(Vector3 value1, Vector3 value2, out Vector3 result) + { + result.X = (value1.X > value2.X) ? value1.X : value2.X; + result.Y = (value1.Y > value2.Y) ? value1.Y : value2.Y; + result.Z = (value1.Z > value2.Z) ? value1.Z : value2.Z; + } + + Vector3 Vector3::Min(Vector3 value1, Vector3 value2) + { + Vector3 result; + result.X = (value1.X < value2.X) ? value1.X : value2.X; + result.Y = (value1.Y < value2.Y) ? value1.Y : value2.Y; + result.Z = (value1.Z < value2.Z) ? value1.Z : value2.Z; + return result; + } + + void Vector3::Min(Vector3 value1, Vector3 value2, out Vector3 result) + { + result.X = (value1.X < value2.X) ? value1.X : value2.X; + result.Y = (value1.Y < value2.Y) ? value1.Y : value2.Y; + result.Z = (value1.Z < value2.Z) ? value1.Z : value2.Z; + } + + Vector3 Vector3::Multiply(Vector3 value1, float scaleFactor) + { + Vector3 result; + result.X = value1.X * scaleFactor; + result.Y = value1.Y * scaleFactor; + result.Z = value1.Z * scaleFactor; + return result; + } + + void Vector3::Multiply(Vector3 value1, float scaleFactor, out Vector3 result) + { + result.X = value1.X * scaleFactor; + result.Y = value1.Y * scaleFactor; + result.Z = value1.Z * scaleFactor; + } + + Vector3 Vector3::Multiply(Vector3 value1, Vector3 value2) + { + Vector3 result; + result.X = value1.X * value2.X; + result.Y = value1.Y * value2.Y; + result.Z = value1.Z * value2.Z; + return result; + } + + void Multiply(Vector3 value1, Vector3 value2, out Vector3 result) + { + result.X = value1.X * value2.X; + result.Y = value1.Y * value2.Y; + result.Z = value1.Z * value2.Z; + } + + Vector3 Vector3::Negate(Vector3 value) + { + Vector3 result; + result.X = -value.X; + result.Y = -value.Y; + result.Z = -value.Z; + return result; + } + + void Vector3::Negate(Vector3 value, out Vector3 result) + { + result.X = -value.X; + result.Y = -value.Y; + result.Z = -value.Z; + } + + void Vector3::Normalize() + { + float length = Length(); + if(length == 0) + return; + float num = 1 / length; + X *= num; + Y *= num; + Z *= num; + } + + Vector3 Vector3::Normalize(Vector3 value) + { + Vector3 result; + float length = value.Length(); + if(length == 0) + return Vector3::Zero; + float num = 1 / length; + result.X *= num; + result.Y *= num; + result.Z *= num; + return result; + } + + void Vector3::Normalize(Vector3 value, out Vector3 result) + { + float length = value.Length(); + if(length == 0) + return; + float num = 1 / length; + result.X *= num; + result.Y *= num; + result.Z *= num; + } + + Vector3 Vector3::Reflect(Vector3 vector, Vector3 normal) + { + Vector3 result; + float dot = ((vector.X * normal.X) + (vector.Y * normal.Y)) + (vector.Z * normal.Z); + + result.X = vector.X - ((2.0f * dot) * normal.X); + result.Y = vector.Y - ((2.0f * dot) * normal.Y); + result.Z = vector.Z - ((2.0f * dot) * normal.Z); + + return result; + } + + void Vector3::Reflect(Vector3 vector, Vector3 normal, out Vector3 result) + { + float dot = ((vector.X * normal.X) + (vector.Y * normal.Y)) + (vector.Z * normal.Z); + + result.X = vector.X - ((2.0f * dot) * normal.X); + result.Y = vector.Y - ((2.0f * dot) * normal.Y); + result.Z = vector.Z - ((2.0f * dot) * normal.Z); + } + + Vector3 Vector3::SmoothStep(Vector3 value1, Vector3 value2, float amount) + { + Vector3 result; + result.X = MathHelper::SmoothStep(value1.X, value2.X, amount); + result.Y = MathHelper::SmoothStep(value1.Y, value2.Y, amount); + result.Z = MathHelper::SmoothStep(value1.Z, value2.Z, amount); + return result; + } + + void Vector3::SmoothStep(Vector3 value1, Vector3 value2, float amount, out Vector3 result) + { + result.X = MathHelper::SmoothStep(value1.X, value2.X, amount); + result.Y = MathHelper::SmoothStep(value1.Y, value2.Y, amount); + result.Z = MathHelper::SmoothStep(value1.Z, value2.Z, amount); + } + + Vector3 Vector3::Subtract(Vector3 value1, Vector3 value2) + { + Vector3 result; + result.X = value1.X - value2.X; + result.Y = value1.Y - value2.Y; + result.Z = value1.Z - value2.Z; + return result; + } + + void Vector3::Subtract(Vector3 value1, Vector3 value2, out Vector3 result) + { + result.X = value1.X - value2.X; + result.Y = value1.Y - value2.Y; + result.Z = value1.Z - value2.Z; + } + + Vector3 Vector3::Transform(Vector3 position, Matrix matrix) + { + Vector4 vector; + + vector.X = (((vector.X * matrix.M11) + (vector.Y * matrix.M21)) + (vector.Z * matrix.M31)) + matrix.M41; + vector.Y = (((vector.X * matrix.M12) + (vector.Y * matrix.M22)) + (vector.Z * matrix.M32)) + matrix.M42; + vector.Z = (((vector.X * matrix.M13) + (vector.Y * matrix.M23)) + (vector.Z * matrix.M33)) + matrix.M43; + vector.W = 1 / ((((vector.X * matrix.M14) + (vector.Y * matrix.M24)) + (vector.Z * matrix.M34)) + matrix.M44); + + return Vector3( vector.X * vector.W, vector.Y * vector.W, vector.Z * vector.W ); + } + + void Vector3::Transform(Vector3 position, Matrix matrix, out Vector3 result) + { + Vector4 vector; + + vector.X = (((vector.X * matrix.M11) + (vector.Y * matrix.M21)) + (vector.Z * matrix.M31)) + matrix.M41; + vector.Y = (((vector.X * matrix.M12) + (vector.Y * matrix.M22)) + (vector.Z * matrix.M32)) + matrix.M42; + vector.Z = (((vector.X * matrix.M13) + (vector.Y * matrix.M23)) + (vector.Z * matrix.M33)) + matrix.M43; + vector.W = 1 / ((((vector.X * matrix.M14) + (vector.Y * matrix.M24)) + (vector.Z * matrix.M34)) + matrix.M44); + + result.X = vector.X * vector.W; + result.Y = vector.Y * vector.W; + result.Z = vector.Z * vector.W; + } + + Vector3 Vector3::Transform(Vector3 position, Quaternion rotation) + { + Vector3 result; + Transform(position, rotation, result); + return result; + } + + void Vector3::Transform(Vector3 position, Quaternion rotation, out Vector3 result) + { + Vector3 xyz = Vector3(rotation.X,rotation.Y, rotation.Z), temp, temp2; + Cross(xyz, position, temp); + Multiply(position, rotation.W, temp2); + Add(temp, temp2, temp); + Cross(xyz, temp, temp); + Multiply(temp, 2, temp); + Add(position, temp, result); + } + + void Vector3::Transform(Vector3 sourceArray[], int sourceIndex, Matrix matrix, Vector3 destinationArray[], int destinationIndex, int length) + { + if (sourceArray == null) + throw ArgumentNullException("sourceArray"); + + if (destinationArray == null) + throw ArgumentNullException("destinationArray"); + } + + void Vector3::Transform(Vector3 sourceArray[], int sourceIndex, Quaternion rotation, Vector3 destinationArray[], int destinationIndex, int length) + { + if (sourceArray == null) + throw ArgumentNullException("sourceArray"); + + if (destinationArray == null) + throw ArgumentNullException("destinationArray"); + } + + void Vector3::Transform(Vector3 sourceArray[], Matrix matrix, Vector3 destinationArray[]) + { + if (sourceArray == null) + throw ArgumentNullException("sourceArray"); + + if (destinationArray == null) + throw ArgumentNullException("destinationArray"); + + if (Array::Length(destinationArray) < Array::Length(sourceArray)) + throw ArgumentException("destinationArray too small"); + + for(int i = 0; i < Array::Length(sourceArray); i++) + { + Transform(sourceArray[i], matrix, destinationArray[i]); + } + } + + void Vector3::Transform(Vector3 sourceArray[], Quaternion rotation, Vector3 destinationArray[]) + { + if (sourceArray == null) + throw ArgumentNullException("sourceArray"); + + if (destinationArray == null) + throw ArgumentNullException("destinationArray"); + + if (Array::Length(destinationArray) < Array::Length(sourceArray)) + throw ArgumentException("destinationArray too small"); + + for(int i = 0; i < Array::Length(sourceArray); i++) + { + Transform(sourceArray[i], rotation, destinationArray[i]); + } + } + + Vector3 Vector3::TransformNormal(Vector3 normal, Matrix matrix) + { + Vector3 result; + TransformNormal(normal, matrix, result); + return result; + } + + void Vector3::TransformNormal(Vector3 normal, Matrix matrix, out Vector3 result) + { + result.X = ((normal.X * matrix.M11) + (normal.Y * matrix.M21)) + (normal.Z * matrix.M31); + result.Y = ((normal.X * matrix.M12) + (normal.Y * matrix.M22)) + (normal.Z * matrix.M32); + result.Z = ((normal.X * matrix.M13) + (normal.Y * matrix.M23)) + (normal.Z * matrix.M33); + } + + void Vector3::TransformNormal(Vector3 sourceArray[], int sourceIndex, Matrix matrix, Vector3 destinationArray[], int destinationIndex, int length) + { + if (sourceArray == null) + throw ArgumentNullException("sourceArray"); + + if (destinationArray == null) + throw ArgumentNullException("destinationArray"); + + for(int i = sourceIndex, j = destinationIndex; i < (sourceIndex + length); i++, j++) + { + TransformNormal(sourceArray[i], matrix, destinationArray[j]); + } + } + + void Vector3::TransformNormal(Vector3 sourceArray[], Matrix matrix, Vector3 destinationArray[]) + { + if (sourceArray == null) + throw ArgumentNullException("sourceArray"); + + if (destinationArray == null) + throw ArgumentNullException("destinationArray"); + + if (Array::Length(destinationArray) < Array::Length(sourceArray)) + throw ArgumentException("destinationArray too small"); + + for(int i = 0; i < Array::Length(sourceArray); i++) + { + TransformNormal(sourceArray[i], matrix, destinationArray[i]); + } + } + + Vector3 Vector3::operator+(Vector3 other) + { + Vector3 result; + result.X = X + other.X; + result.Y = Y + other.Y; + result.Z = Z + other.Z; + return result; + } + + Vector3 Vector3::operator/(float divider) + { + Vector3 result; + result.X = X / divider; + result.Y = Y / divider; + result.Z = Z / divider; + return result; + } + + Vector3 Vector3::operator/(Vector3 other) + { + Vector3 result; + result.X = X / other.X; + result.Y = Y / other.Y; + result.Z = Z / other.Z; + return result; + } + + bool Vector3::operator==(const Vector3 other) + { + return Equals(other); + } + + bool Vector3::operator!=(const Vector3 other) + { + return !Equals(other); + } + + Vector3 Vector3::operator*(float scaleFactor) + { + Vector3 result; + result.X = X * scaleFactor; + result.Y = Y * scaleFactor; + result.Z = Z * scaleFactor; + return result; + } + + Vector3 Vector3::operator*(Vector3 other) + { + Vector3 result; + result.X = X * other.X; + result.Y = Y * other.Y; + result.Z = Z * other.Z; + return result; + } + + Vector3 Vector3::operator-(Vector3 other) + { + return Vector3(X -= other.X, Y -= other.Y, Z -= other.Z); + } + + Vector3 Vector3::operator-() + { + return Vector3(-X, -Y, -Z); + } + + Vector3 Vector3::operator=(const Vector3 other) + { + X = other.X; + Y = other.Y; + Z = other.Z; + return *this; + } +} diff --git a/src/libXFX/Vector4.cpp b/src/libXFX/Vector4.cpp new file mode 100644 index 0000000..af0780b --- /dev/null +++ b/src/libXFX/Vector4.cpp @@ -0,0 +1,650 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace System; + +namespace XFX +{ + const Vector4 Vector4::One = Vector4(1,1,1,1); + const Vector4 Vector4::UnitW = Vector4(0,0,0,1); + const Vector4 Vector4::UnitX = Vector4(1,0,0,0); + const Vector4 Vector4::UnitY = Vector4(0,1,0,0); + const Vector4 Vector4::UnitZ = Vector4(0,0,1,0); + const Vector4 Vector4::Zero = Vector4(0,0,0,0); + + Vector4::Vector4(float value) + { + W = value; + X = value; + Y = value; + Z = value; + } + + Vector4::Vector4(float x, float y, float z, float w) + { + W = w; + X = x; + Y = y; + Z = z; + } + + Vector4::Vector4(Vector2 value, float z, float w) + { + W = w; + X = value.X; + Y = value.Y; + Z = z; + } + + Vector4::Vector4(Vector3 value, float w) + { + W = w; + X = value.X; + Y = value.Y; + Z = value.Z; + } + + Vector4::Vector4(const Vector4 &obj) + { + W = obj.W; + X = obj.X; + Y = obj.Y; + Z = obj.Z; + } + + Vector4::Vector4() + { + W = 0; + X = 0; + Y = 0; + Z = 0; + } + + Vector4 Vector4::Add(Vector4 vector1, Vector4 vector2) + { + return Vector4(vector1.X + vector2.X, + vector1.Y + vector2.Y, + vector1.Z + vector2.Z, + vector1.W + vector2.W); + } + + void Vector4::Add(Vector4 vector1, Vector4 vector2, out Vector4 result) + { + result.W = vector1.W + vector2.W; + result.X = vector1.X + vector2.X; + result.Y = vector1.Y + vector2.Y; + result.Z = vector1.Z + vector2.Z; + } + + Vector4 Vector4::Baricentric(Vector4 value1, Vector4 value2, Vector4 value3, float amount1, float amount2) + { + Vector4 result; + result.X = MathHelper::Baricentric(value1.X, value2.X, value3.X, amount1, amount2); + result.Y = MathHelper::Baricentric(value1.Y, value2.Y, value3.Y, amount1, amount2); + result.Z = MathHelper::Baricentric(value1.Z, value2.Z, value3.Z, amount1, amount2); + result.W = MathHelper::Baricentric(value1.W, value2.W, value3.W, amount1, amount2); + return result; + } + + void Vector4::Baricentric(Vector4 value1, Vector4 value2, Vector4 value3, float amount1, float amount2, out Vector4 result) + { + result.X = MathHelper::Baricentric(value1.X, value2.X, value3.X, amount1, amount2); + result.Y = MathHelper::Baricentric(value1.Y, value2.Y, value3.Y, amount1, amount2); + result.Z = MathHelper::Baricentric(value1.Z, value2.Z, value3.Z, amount1, amount2); + result.W = MathHelper::Baricentric(value1.W, value2.W, value3.W, amount1, amount2); + } + + Vector4 Vector4::CatmullRom(Vector4 value1, Vector4 value2, Vector4 value3, Vector4 value4, float amount) + { + Vector4 result; + result.X = MathHelper::CatmullRom(value1.X, value2.X, value3.X, value4.X, amount); + result.Y = MathHelper::CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount); + result.Z = MathHelper::CatmullRom(value1.Z, value2.Z, value3.Z, value4.Z, amount); + result.W = MathHelper::CatmullRom(value1.W, value2.W, value3.W, value4.W, amount); + return result; + } + + void CatmullRom(Vector4 value1, Vector4 value2, Vector4 value3, Vector4 value4, float amount, out Vector4 result) + { + result.X = MathHelper::CatmullRom(value1.X, value2.X, value3.X, value4.X, amount); + result.Y = MathHelper::CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount); + result.Z = MathHelper::CatmullRom(value1.Z, value2.Z, value3.Z, value4.Z, amount); + result.W = MathHelper::CatmullRom(value1.W, value2.W, value3.W, value4.W, amount); + } + + Vector4 Vector4::Clamp(Vector4 value1, Vector4 min, Vector4 max) + { + Vector4 result; + Clamp(value1, min, max, result); + return result; + } + + void Vector4::Clamp(Vector4 value1, Vector4 min, Vector4 max, out Vector4 result) + { + result = Vector4( + MathHelper::Clamp(value1.X, min.X, max.X), + MathHelper::Clamp(value1.Y, min.Y, max.Y), + MathHelper::Clamp(value1.Z, min.Z, max.Z), + MathHelper::Clamp(value1.W, min.W, max.W)); + } + + float Vector4::Distance(Vector4 value1, Vector4 value2) + { + return Math::Sqrt(DistanceSquared(value1, value2)); + } + + void Vector4::Distance(Vector4 value1, Vector4 value2, out float result) + { + result = Math::Sqrt(DistanceSquared(value1, value2)); + } + + float Vector4::DistanceSquared(Vector4 value1, Vector4 value2) + { + float result = (value1.W - value2.W) * (value1.W - value2.W) + + (value1.X - value2.X) * (value1.X - value2.X) + + (value1.Y - value2.Y) * (value1.Y - value2.Y) + + (value1.Z - value2.Z) * (value1.Z - value2.Z); + return result; + } + + void Vector4::DistanceSquared(Vector4 value1, Vector4 value2, out float result) + { + result = (value1.W - value2.W) * (value1.W - value2.W) + + (value1.X - value2.X) * (value1.X - value2.X) + + (value1.Y - value2.Y) * (value1.Y - value2.Y) + + (value1.Z - value2.Z) * (value1.Z - value2.Z); + } + + Vector4 Vector4::Divide(Vector4 value, float scale) + { + return Vector4(value.X / scale, value.Y / scale, value.Z / scale, value.W / scale); + } + + void Vector4::Divide(Vector4 value, float scale, out Vector4 result) + { + result.W = value.W / scale; + result.X = value.X / scale; + result.Y = value.Y / scale; + result.Z = value.Z / scale; + } + + Vector4 Vector4::Divide(Vector4 vector1, Vector4 vector2) + { + return Vector4(vector1.X / vector2.X, vector1.Y / vector2.Y, vector1.Z / vector2.Z, vector1.W / vector2.W); + } + + void Vector4::Divide(Vector4 vector1, Vector4 vector2, out Vector4 result) + { + result.W = vector1.W / vector2.W; + result.X = vector1.X / vector2.X; + result.Y = vector1.Y / vector2.Y; + result.Z = vector1.Z / vector2.Z; + } + + bool Vector4::Equals(Vector4 obj) + { + return ((W == obj.W) && (X == obj.X) && (Y == obj.Y) && (Z == obj.Z)); + } + + int Vector4::GetHashCode() + { + return ((int)X ^ (int)Y ^ (int)Z ^ (int)W); + } + + Vector4 Vector4::Hermite(Vector4 value1, Vector4 tangent1, Vector4 value2, Vector4 tangent2, float amount) + { + Vector4 result; + Hermite(value1, tangent1, value2, tangent2, amount, result); + return result; + } + + void Hermite(Vector4 value1, Vector4 tangent1, Vector4 value2, Vector4 tangent2, float amount, out Vector4 result) + { + result.W = MathHelper::Hermite(value1.W, tangent1.W, value2.W, tangent2.W, amount); + result.X = MathHelper::Hermite(value1.X, tangent1.X, value2.X, tangent2.X, amount); + result.Y = MathHelper::Hermite(value1.Y, tangent1.Y, value2.Y, tangent2.Y, amount); + result.Z = MathHelper::Hermite(value1.Z, tangent1.Z, value2.Z, tangent2.Z, amount); + } + + float Vector4::Length() + { + return Math::Sqrt((X * X) + (Y * Y) + (Z * Z) + (W * W)); + } + + float Vector4::LengthSquared() + { + return (X * X) + (Y * Y) + (Z * Z) + (W * W); + } + + Vector4 Vector4::Lerp(Vector4 value1, Vector4 value2, float amount) + { + Vector4 result; + Lerp(value1, value2, amount, result); + return result; + } + + void Vector4::Lerp(Vector4 value1, Vector4 value2, float amount, out Vector4 result) + { + result = Vector4( + MathHelper::Lerp(value1.X, value2.X, amount), + MathHelper::Lerp(value1.Y, value2.Y, amount), + MathHelper::Lerp(value1.Z, value2.Z, amount), + MathHelper::Lerp(value1.W, value2.W, amount)); + } + + Vector4 Vector4::Max(Vector4 value1, Vector4 value2) + { + Vector4 result; + Max(value1, value2, result); + return result; + } + + void Vector4::Max(Vector4 value1, Vector4 value2, out Vector4 result) + { + result = Vector4( + MathHelper::Max(value1.X, value2.X), + MathHelper::Max(value1.Y, value2.Y), + MathHelper::Max(value1.Z, value2.Z), + MathHelper::Max(value1.W, value2.W)); + } + + Vector4 Vector4::Min(Vector4 value1, Vector4 value2) + { + Vector4 result; + Min(value1, value2, result); + return result; + } + + void Vector4::Min(Vector4 value1, Vector4 value2, out Vector4 result) + { + result = Vector4( + MathHelper::Min(value1.X, value2.X), + MathHelper::Min(value1.Y, value2.Y), + MathHelper::Min(value1.Z, value2.Z), + MathHelper::Min(value1.W, value2.W)); + } + + Vector4 Vector4::Multiply(Vector4 value1, float scaleFactor) + { + Vector4 result; + Multiply(value1, scaleFactor, result); + return result; + } + + void Vector4::Multiply(Vector4 value1, float scaleFactor, out Vector4 result) + { + result.X = value1.X * scaleFactor; + result.Y = value1.Y * scaleFactor; + result.Z = value1.Z * scaleFactor; + result.W = value1.W * scaleFactor; + } + + Vector4 Vector4::Multiply(Vector4 value1, Vector4 value2) + { + Vector4 result; + Multiply(value1, value2, result); + return result; + } + + void Vector4::Multiply(Vector4 value1, Vector4 value2, out Vector4 result) + { + result.W = value1.W * value2.W; + result.X = value1.X * value2.X; + result.Y = value1.Y * value2.Y; + result.Z = value1.Z * value2.Z; + } + + Vector4 Vector4::Negate(Vector4 value) + { + Vector4 result; + Negate(value, result); + return result; + } + + void Vector4::Negate(Vector4 value, out Vector4 result) + { + result = Vector4(-value.X, -value.Y, -value.Z, -value.W); + } + + void Vector4::Normalize() + { + float length = Length(); + if( length == 0 ) + return; + float num = 1 / length; + X *= num; + Y *= num; + Z *= num; + W *= num; + } + + Vector4 Vector4::Normalize(Vector4 value) + { + Normalize(value, value); + return value; + } + + void Vector4::Normalize(Vector4 value, out Vector4 result) + { + float factor; + float length = value.Length(); + factor = 1.0f / length; + + result.W = value.W * factor; + result.X = value.X * factor; + result.Y = value.Y * factor; + result.Z = value.Z * factor; + } + + Vector4 Vector4::SmoothStep(Vector4 value1, Vector4 value2, float amount) + { + return Vector4( + MathHelper::SmoothStep(value1.X, value2.X, amount), + MathHelper::SmoothStep(value1.Y, value2.Y, amount), + MathHelper::SmoothStep(value1.Z, value2.Z, amount), + MathHelper::SmoothStep(value1.W, value2.W, amount)); + } + + void Vector4::SmoothStep(Vector4 value1, Vector4 value2, float amount, out Vector4 result) + { + result = Vector4( + MathHelper::SmoothStep(value1.X, value2.X, amount), + MathHelper::SmoothStep(value1.Y, value2.Y, amount), + MathHelper::SmoothStep(value1.Z, value2.Z, amount), + MathHelper::SmoothStep(value1.W, value2.W, amount)); + } + + Vector4 Vector4::Subtract(Vector4 vector1, Vector4 vector2) + { + vector1.X -= vector2.X; + vector1.Y -= vector2.Y; + vector1.Z -= vector2.Z; + vector1.W -= vector2.W; + return vector1; + } + + void Vector4::Subtract(Vector4 vector1, Vector4 vector2, out Vector4 result) + { + result.X = vector1.X - vector2.X; + result.Y = vector1.Y - vector2.Y; + result.Z = vector1.Z - vector2.Z; + result.W = vector1.W - vector2.W; + } + + void Vector4::Transform(Vector4 sourceArray[], Quaternion rotation, Vector4 destinationArray[]) + { + if(Array::Length(destinationArray) < Array::Length(sourceArray)) + throw ArgumentException("destinationArray too small"); + + for(int i = 0; i < Array::Length(sourceArray)-1; i++) + { + Transform(sourceArray[i], rotation, destinationArray[i]); + } + } + + void Vector4::Transform(Vector4 sourceArray[], int sourceIndex, Quaternion rotation, Vector4 destinationArray[], int destinationIndex, int length) + { + for(int i = sourceIndex, j = destinationIndex; i < (sourceIndex + length); i++, j++) + { + Transform(sourceArray[i], rotation, destinationArray[j]); + } + } + + void Vector4::Transform(Vector4 sourceArray[], Matrix matrix, Vector4 destinationArray[]) + { + if(Array::Length(destinationArray) < Array::Length(sourceArray)) + throw ArgumentException("destinationArray too small"); + + for(int i = 0; i < Array::Length(sourceArray)-1; i++) + { + Transform(sourceArray[i], matrix, destinationArray[i]); + } + } + + void Vector4::Transform(Vector4 sourceArray[], int sourceIndex, Matrix matrix, Vector4 destinationArray[], int destinationIndex, int length) + { + for(int i = sourceIndex, j = destinationIndex; i < (sourceIndex + length); i++, j++) + { + Transform(sourceArray[i], matrix, destinationArray[i]); + } + } + + Vector4 Vector4::Transform(Vector4 vector, Quaternion rotation) + { + Vector4 result; + Transform(vector, rotation, result); + return result; + } + + void Vector4::Transform(Vector4 vector, Quaternion rotation, out Vector4 result) + { + float x = rotation.X + rotation.X; + float y = rotation.Y + rotation.Y; + float z = rotation.Z + rotation.Z; + float wx = rotation.W * x; + float wy = rotation.W * y; + float wz = rotation.W * z; + float xx = rotation.X * x; + float xy = rotation.X * y; + float xz = rotation.X * z; + float yy = rotation.Y * y; + float yz = rotation.Y * z; + float zz = rotation.Z * z; + result.X = ((vector.X * ((1.0f - yy) - zz)) + (vector.Y * (xy - wz))) + (vector.Z * (xz + wy)); + result.Y = ((vector.X * (xy + wz)) + (vector.Y * ((1.0f - xx) - zz))) + (vector.Z * (yz - wx)); + result.Z = ((vector.X * (xz - wy)) + (vector.Y * (yz + wx))) + (vector.Z * ((1.0f - xx) - yy)); + result.W = vector.W; + } + + Vector4 Vector4::Transform(Vector3 vector, Quaternion rotation) + { + Vector4 result; + Transform(vector, rotation, result); + return result; + } + + void Vector4::Transform(Vector3 vector, Quaternion rotation, out Vector4 result) + { + float x = rotation.X + rotation.X; + float y = rotation.Y + rotation.Y; + float z = rotation.Z + rotation.Z; + float wx = rotation.W * x; + float wy = rotation.W * y; + float wz = rotation.W * z; + float xx = rotation.X * x; + float xy = rotation.X * y; + float xz = rotation.X * z; + float yy = rotation.Y * y; + float yz = rotation.Y * z; + float zz = rotation.Z * z; + result.X = ((vector.X * ((1.0f - yy) - zz)) + (vector.Y * (xy - wz))) + (vector.Z * (xz + wy)); + result.Y = ((vector.X * (xy + wz)) + (vector.Y * ((1.0f - xx) - zz))) + (vector.Z * (yz - wx)); + result.Z = ((vector.X * (xz - wy)) + (vector.Y * (yz + wx))) + (vector.Z * ((1.0f - xx) - yy)); + result.W = 1.0f; + } + + Vector4 Vector4::Transform(Vector2 vector, Quaternion rotation) + { + Vector4 result; + Transform(vector, rotation, result); + return result; + } + + void Vector4::Transform(Vector2 vector, Quaternion rotation, out Vector4 result) + { + float x = rotation.X + rotation.X; + float y = rotation.Y + rotation.Y; + float z = rotation.Z + rotation.Z; + float wx = rotation.W * x; + float wy = rotation.W * y; + float wz = rotation.W * z; + float xx = rotation.X * x; + float xy = rotation.X * y; + float xz = rotation.X * z; + float yy = rotation.Y * y; + float yz = rotation.Y * z; + float zz = rotation.Z * z; + result.X = ((vector.X * ((1.0f - yy) - zz)) + (vector.Y * (xy - wz))); + result.Y = ((vector.X * (xy + wz)) + (vector.Y * ((1.0f - xx) - zz))); + result.Z = ((vector.X * (xz - wy)) + (vector.Y * (yz + wx))); + result.W = 1.0f; + } + + Vector4 Vector4::Transform(Vector4 vector, Matrix matrix) + { + Transform(vector, matrix, vector); + return vector; + } + + void Vector4::Transform(Vector4 vector, Matrix matrix, Vector4 result) + { + result = Vector4((vector.X * matrix.M11) + (vector.Y * matrix.M21) + (vector.Z * matrix.M31) + (vector.W * matrix.M41), + (vector.X * matrix.M12) + (vector.Y * matrix.M22) + (vector.Z * matrix.M32) + (vector.W * matrix.M42), + (vector.X * matrix.M13) + (vector.Y * matrix.M23) + (vector.Z * matrix.M33) + (vector.W * matrix.M43), + (vector.X * matrix.M14) + (vector.Y * matrix.M24) + (vector.Z * matrix.M34) + (vector.W * matrix.M44)); + } + + Vector4 Vector4::Transform(Vector3 vector, Matrix matrix) + { + Vector4 result; + Transform(vector, matrix, result); + return result; + } + + void Vector4::Transform(Vector3 vector, Matrix matrix, out Vector4 result) + { + result = Vector4((vector.X * matrix.M11) + (vector.Y * matrix.M21) + (vector.Z * matrix.M31) + matrix.M41, + (vector.X * matrix.M12) + (vector.Y * matrix.M22) + (vector.Z * matrix.M32) + matrix.M42, + (vector.X * matrix.M13) + (vector.Y * matrix.M23) + (vector.Z * matrix.M33) + matrix.M43, + (vector.X * matrix.M14) + (vector.Y * matrix.M24) + (vector.Z * matrix.M34) + matrix.M44); + } + + Vector4 Vector4::Transform(Vector2 vector, Matrix matrix) + { + Vector4 result; + Transform(vector, matrix, result); + return result; + } + + void Vector4::Transform(Vector2 vector, Matrix matrix, out Vector4 result) + { + result = Vector4((vector.X * matrix.M11) + (vector.Y * matrix.M21) + matrix.M41, + (vector.X * matrix.M12) + (vector.Y * matrix.M22) + matrix.M42, + (vector.X * matrix.M13) + (vector.Y * matrix.M23) + matrix.M43, + (vector.X * matrix.M14) + (vector.Y * matrix.M24) + matrix.M44); + } + // + // Operators + // + const Vector4 Vector4::operator-(const Vector4 other) + { + X -= other.X; + Y -= other.Y; + Z -= other.Z; + W -= other.W; + return *this; + } + + const Vector4 Vector4::operator-() + { + return Vector4(-X, -Y, -Z, -W); + } + + bool Vector4::operator!=(const Vector4 other) + { + return !Equals(other); + } + + const Vector4 Vector4::operator*(const float scaleFactor) + { + W *= scaleFactor; + X *= scaleFactor; + Y *= scaleFactor; + Z *= scaleFactor; + return *this; + } + + const Vector4 Vector4::operator*(const Vector4 other) + { + W *= other.W; + X *= other.X; + Y *= other.Y; + Z *= other.Z; + return *this; + } + + const Vector4 Vector4::operator/(const float scaleFactor) + { + W /= scaleFactor; + X /= scaleFactor; + Y /= scaleFactor; + X /= scaleFactor; + return *this; + } + + const Vector4 Vector4::operator/(const Vector4 other) + { + W /= other.W; + X /= other.X; + Y /= other.Y; + Z /= other.Z; + return *this; + } + + const Vector4 Vector4::operator+(const Vector4 other) + { + X += other.X; + Y += other.Y; + Z += other.Z; + W += other.W; + return *this; + } + + bool Vector4::operator==(const Vector4 other) + { + return Equals(other); + } + + Vector4 Vector4::operator=(const Vector4 other) + { + X = other.X; + Y = other.Y; + Z = other.Z; + W = other.W; + return *this; + } +} diff --git a/src/libXFX/VertexElement.cpp b/src/libXFX/VertexElement.cpp new file mode 100644 index 0000000..7e1071e --- /dev/null +++ b/src/libXFX/VertexElement.cpp @@ -0,0 +1,65 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace XFX +{ + namespace Graphics + { + VertexElement::VertexElement(short stream, short offset, VertexElementFormat_t elementFormat, VertexElementMethod_t elementMethod, VertexElementUsage_t elementUsage, BYTE usageIndex) + { + Stream = stream; + Offset = offset; + VertexElementFormat_ = elementFormat; + VertexElementMethod_ = elementMethod; + VertexElementUsage_ = elementUsage; + UsageIndex = usageIndex; + } + + int VertexElement::Equals(const VertexElement &other) + { + return ((Offset == other.Offset) && (Stream == other.Stream) && (VertexElementFormat_ == other.VertexElementFormat_) && + (VertexElementMethod_ == other.VertexElementMethod_) && (VertexElementUsage_ == other.VertexElementUsage_) && (UsageIndex == other.UsageIndex)); + } + + int VertexElement::GetHashCode() + { + return (Stream ^ Offset ^ UsageIndex); + } + + int VertexElement::operator!=(const VertexElement &other) + { + return !Equals(other); + } + + int VertexElement::operator==(const VertexElement &other) + { + return Equals(other); + } + } +} diff --git a/src/libXFX/VertexPositionNormalTexture.cpp b/src/libXFX/VertexPositionNormalTexture.cpp new file mode 100644 index 0000000..4a4c96c --- /dev/null +++ b/src/libXFX/VertexPositionNormalTexture.cpp @@ -0,0 +1,66 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace XFX +{ + namespace Graphics + { + VertexPositionNormalTexture::VertexPositionNormalTexture(Vector3 &position, Vector3 &normal, Vector2 &textureCoordinate) + { + Position = position; + Normal = normal; + TextureCoordinate = textureCoordinate; + } + + int VertexPositionNormalTexture::SizeInBytes() + { + return (sizeof(float) * 5); + } + + int VertexPositionNormalTexture::Equals(const VertexPositionNormalTexture &other) + { + return ((Normal == other.Normal) && (Position == other.Position) && (TextureCoordinate == other.TextureCoordinate)); + } + + int VertexPositionNormalTexture::GetHashCode() + { + return Normal.GetHashCode() ^ Position.GetHashCode() ^ TextureCoordinate.GetHashCode(); + } + + int VertexPositionNormalTexture::operator!=(const VertexPositionNormalTexture &other) + { + return !Equals(other); + } + + int VertexPositionNormalTexture::operator==(const VertexPositionNormalTexture &other) + { + return Equals(other); + } + } +} diff --git a/src/libXFX/VertexPositionTexture.cpp b/src/libXFX/VertexPositionTexture.cpp new file mode 100644 index 0000000..4bcb083 --- /dev/null +++ b/src/libXFX/VertexPositionTexture.cpp @@ -0,0 +1,68 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include + +namespace XFX +{ + namespace Graphics + { + VertexPositionTexture::VertexPositionTexture(Vector3 &position, Vector2 &textureCoordinate) + { + Position = position; + TextureCoordinate = textureCoordinate; + } + + int VertexPositionTexture::SizeInBytes() + { + return (sizeof(float) * 5); + } + + int VertexPositionTexture::Equals(const VertexPositionTexture &other) + { + return ((Position == other.Position) && (TextureCoordinate == other.TextureCoordinate)); + } + + int VertexPositionTexture::GetHashCode() + { + return Position.GetHashCode() ^ TextureCoordinate.GetHashCode(); + } + + int VertexPositionTexture::operator!=(const VertexPositionTexture &other) + { + return !Equals(other); + } + + int VertexPositionTexture::operator==(const VertexPositionTexture &other) + { + return Equals(other); + } + } +} diff --git a/src/libXFX/VideoPlayer.cpp b/src/libXFX/VideoPlayer.cpp new file mode 100644 index 0000000..3328482 --- /dev/null +++ b/src/libXFX/VideoPlayer.cpp @@ -0,0 +1,58 @@ +#include +#include +#include + +namespace XFX +{ + namespace Media + { + int VideoPlayer::IsDisposed() + { + } + + TimeSpan VideoPlayer::PlayPosition() + { + } + + MediaState_t State() + { + } + + Video VideoPlayer::Video_() + { + } + + VideoPlayer::VideoPlayer() + { + } + + void VideoPlayer::Dispose() + { + Dispose(true); + } + + void VideoPlayer::Dispose(bool disposing) + { + } + + Texture2D VideoPlayer::GetTexture() + { + } + + void VideoPlayer::Pause() + { + } + + void VideoPlayer::Play(Video &video) + { + } + + void VideoPlayer::Resume() + { + } + + void VideoPlayer::Stop() + { + } + } +} diff --git a/src/libXFX/Viewport.cpp b/src/libXFX/Viewport.cpp new file mode 100644 index 0000000..e23706f --- /dev/null +++ b/src/libXFX/Viewport.cpp @@ -0,0 +1,82 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include + +namespace XFX +{ + namespace Graphics + { + float Viewport::AspectRatio() + { + if ((this._height != 0) && (this._width != 0)) + { + return (((float) this._width) / ((float) this._height)); + } + return 0.0f; + } + + bool Viewport::WithinEpsilon(float a, float b) + { + float num = a - b; + return ((-1.401298E-45f <= num) && (num <= 1.401298E-45f)); + } + + Vector3 Viewport::Project(Vector3 source, Matrix projection, Matrix view, Matrix world) + { + Matrix matrix = Matrix::Multiply(Matrix::Multiply(world, view), projection); + Vector3 vector = Vector3::Transform(source, matrix); + float a = (((source.X * matrix.M14) + (source.Y * matrix.M24)) + (source.Z * matrix.M34)) + matrix.M44; + if (!WithinEpsilon(a, 1f)) + { + vector = (Vector3) (vector / a); + } + vector.X = (((vector.X + 1f) * 0.5f) * Width) + X; + vector.Y = (((-vector.Y + 1f) * 0.5f) * Height) + Y; + vector.Z = (vector.Z * (MaxDepth - MinDepth)) + MinDepth; + return vector; + } + + Vector3 Viewport::Unproject(Vector3 source, Matrix projection, Matrix view, Matrix world) + { + Vector3 position = Vector3(); + Matrix matrix = Matrix::Invert(Matrix::Multiply(Matrix::Multiply(world, view), projection)); + position.X = (((source.X - X) / ((float) Width)) * 2f) - 1f; + position.Y = -((((source.Y - Y) / ((float) Height)) * 2f) - 1f); + position.Z = (source.Z - MinDepth) / (MaxDepth - MinDepth); + position = Vector3.Transform(position, matrix); + float a = (((source.X * matrix.M14) + (source.Y * matrix.M24)) + (source.Z * matrix.M34)) + matrix.M44; + if (!WithinEpsilon(a, 1f)) + { + position = (Vector3) (position / a); + } + return position; + } + } +} diff --git a/src/libXFX/libXFX.vcproj b/src/libXFX/libXFX.vcproj new file mode 100644 index 0000000..c8b0b4d --- /dev/null +++ b/src/libXFX/libXFX.vcproj @@ -0,0 +1,629 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/libXFX/makefile b/src/libXFX/makefile new file mode 100644 index 0000000..1ea1fd8 --- /dev/null +++ b/src/libXFX/makefile @@ -0,0 +1,65 @@ +# +# update this variable to wherever you installed the OpenXDK libraries +# +######################################################################### +# +# The ENABLE_XBOX definition is there because of intentions to eventually +# support Linux as well +# +PREFIX = /usr/local/openxdk +XFX_PREFIX = /cygdrive/j/XFX + +CC = gcc +CCAS = gcc +CPP = g++ +AR = ar rcu +RANLIB = ranlib +CXBE = $(PREFIX)/bin/cxbe + +SDLFLAGS = -DENABLE_XBOX +CC_FLAGS = -c -g -std=gnu99 -ffreestanding -nostdlib -fno-builtin -fno-exceptions -mno-cygwin -march=i386 $(SDLFLAGS) +CCAS_FLAGS = -g -O2 +CPP_FLAGS = -c -O2 -Wall -nostdlib -fno-builtin -mno-cygwin -march=i386 -mmmx -msse -mfpmath=sse $(SDLFLAGS) +INCLUDE = -I$(PREFIX)/i386-pc-xbox/include -I$(PREFIX)/include -I$(PREFIX)/include/SDL -I$(XFX_PREFIX)/include + +CLINK = -nostdlib +ALIGN = -Wl,--file-alignment,0x20 -Wl,--section-alignment,0x20 +SHARED = -shared +ENTRYPOINT = -Wl,--entry,_WinMainCRTStartup +STRIP = -Wl,--strip-all +LD_FLAGS = $(CLINK) $(ALIGN) $(SHARED) $(ENTRYPOINT) $(STRIP) +LD_DIRS = -L$(PREFIX)/i386-pc-xbox/lib -L$(PREFIX)/lib +LD_LIBS = $(LD_DIRS) -lmscorlib -lm -lopenxdk -lhal -lc -lusb -lc -lxboxkrnl -lc -lhal -lxboxkrnl -lhal -lopenxdk -lc -lstdc++ -lgcc + +OBJS = BoundingBox.o BoundingFrustrum.o BoundingSphere.o MathHelper.o Matrix.o Plane.o Point.o Quaternion.o Ray.o Rectangle.o Vector2.o Vector3.o Vector4.o +AUDIO_OBJS = +CONTENT_OBJS = ContentManager.o ContentReader.o +GAMERSERVICES_OBJS = +GRAPHICS_OBJS = Color.o DisplayMode.o GraphicsAdapter.o GraphicsDevice.o GraphicsDeviceManager.o PBKit/pbKit.o Texture.o Texture2D.o TextureCollection.o TextureCreationParameters.o VertexElement.o VertexPositionNormalTexture.o VertexPositionTexture.o Viewport.o +INPUT_OBJS = GamePad.o usb/hub.o Keyboard.o Mouse.o usb/ohci.o usb/pad.o usb/xinput.o +MEDIA_OBJS = VideoPlayer.o +NET_OBJS = +STORAGE_OBJS = StorageContainer.o StorageDevice.o StorageDeviceNotConnectedException.o + +OBJS1 = $(OBJS) $(CONTENT_OBJS) $(GRAPHICS_OBJS) $(INPUT_OBJS) $(MEDIA_OBJS) $(STORAGE_OBJS) + +all: libXFX.a + +rebuild: clean libXFX.a + +libXFX.a: $(OBJS1) + $(AR) $@ $(OBJS1) + $(RANLIB) $@ + +.c.o: + $(CC) -c $< $(CC_FLAGS) $(INCLUDE) + +.cpp.o: + $(CPP) -c $< $(CPP_FLAGS) $(INCLUDE) + +.s.o: + $(CCAS) -c $< $(CCAS_FLAGS) + +clean: + rm -f *.o *.exe *.dll *.xbe *.cxbe *.lib *.a + \ No newline at end of file diff --git a/src/libXFX/usb/hub.cpp b/src/libXFX/usb/hub.cpp new file mode 100644 index 0000000..bbe2f8a --- /dev/null +++ b/src/libXFX/usb/hub.cpp @@ -0,0 +1,1199 @@ +/******************************************************************************/ +/* */ +/* File: hub.cpp */ +/* bkenwright@xbdev.net - www.xbdev.net */ +/* */ +/******************************************************************************/ + +#include "hub.h" +#include "misc.h" + + + +extern unsigned int eds[176 + 0x100 + 0x100]; // ohci.cpp +extern unsigned int EDA; +extern s_Endpointdescripor * ED; + + + +//#define USB_DEBUG +//#define USB_DEBUG_ERROR + + +/******************************************************************************/ + +/******************************************************************************/ + +/******************************************************************************/ + + +// Offset Field Size Value Desc +// 0 bmRequestType 1 Bitmap D7: Direction +// 0 = Host-to-device +// 1 = Device-to-host +// D6..5: Type +// 0 = Standard +// 1 = Class +// 2 = Vendor +// 3 = Reserved +// D4..0: Recipient +// 0 = Device +// 1 = Interface +// 2 = Endpoint +// 3 = Other +// 4..31 = Reserved +// 1 bRequest 1 Value Specific request (9-3) +// 2 wValue 2 Value Varies +// 4 wIndex 2 Index/Offset Varies +// 6 wLength 2 Count Bytes for data +/* +struct devrequest +{ + unsigned char requesttype; // 1 byte + unsigned char request; // 1 byte + unsigned short value; // 2 bytes + unsigned short index; // 2 bytes + unsigned short length; // 2 bytes +}; // Total = 8 bytes +*/ + + + +int get_control_msg(ohci_t * ohci, + unsigned char Addr, + unsigned char request, // 0x06 + unsigned char requesttype, // 0x80 + unsigned short value, + unsigned short index, + unsigned short size, + unsigned char *data ) +{ + + // First, lets desribe what type of message this is! + devrequest cmd; + + + cmd.requesttype = requesttype; //0x80; + cmd.request = request; //0x06; + cmd.value = value; //(0x29<<8); + cmd.index = index; + cmd.length = ((unsigned short) size); + + + xMmLockUnlockBufferPages( (unsigned int)&cmd, 0x8, 0); + unsigned int real_pcmd = xMmGetPhysicalAddress( (unsigned int)&cmd); + + + unsigned char Descriptors[256] = {0}; + xMmLockUnlockBufferPages( (unsigned int)Descriptors, 256, 0 ); + unsigned int real_pDescriptors = xMmGetPhysicalAddress( (unsigned int)Descriptors ); + + + //unsigned int uTD = (unsigned int)pTD; + //uTD += (unsigned int)0x10; + //uTD &= 0xfffffff0; + + s_Transferdescriptor *TD; + TD = (s_Transferdescriptor *)(((unsigned int *)ED) + 20); + unsigned int TDA = EDA + 80; + unsigned int realTDA = xMmGetPhysicalAddress( (unsigned int)TDA ); + + + +//////////////////////////////////////////////////////////////////////// +// --Transfer Descriptor TD-- +// Offset Field Size Value Desc +// 0 4 0..17 reserved +// +// 18 R - bufferRounding +// 19..20 DP - Direction/PID +// 00b SETUP +// 01b OUT +// 10b IN +// 11b reserved +// 21..23 DI - DelayInterrupt +// 24..25 T - DataToggle +// 26..27 EC - ErrorCount +// 28..31 CC - ConditionCode +// 4 4 CurrentBufferPoinnter (CBP) +// 8 4 0..3 Zero +// 4..31 Next TD (NextTD) +// 12 4 Buffer End (BE) +// +//(Total Size 16 bytes or 4 dwords) +// +//////////////////////////////////////////////////////////////////////// + + unsigned int v_format = 0; + v_format |= (0xE<<28); // 1110b - CC + v_format |= (0x0<<26); // 00b - EC + v_format |= (0x2<<24); // 10b - T + // E2 + v_format |= (0x0<<21); // 000b - DelayInterrupt + v_format |= (0x0<<19); // 00b - DR (SETUP) + v_format |= (0x0<<18); // 0b - bufferRound (NO) + v_format |= (0x0<<16); // 00b - reserved + // 00 + v_format |= 0x50CA; // reserved + // 50CA + + + TD[0].Format = 0xE20050CA; // Get Descriptor + TD[0].Buffer = real_pcmd; + TD[0].NextTD = realTDA + 16; + TD[0].BufferEnd = real_pcmd + 7; + + TD[1].Format = 0xE31450CB; // Receive Start of Descriptor + TD[1].Buffer = real_pDescriptors; + TD[1].NextTD = realTDA + 32; + TD[1].BufferEnd = real_pDescriptors + 7; + + + //------------------------------------------------------------- + + TD[2].Format = 0xE21450CC; // Receive Rest of Descriptor + TD[2].Buffer = real_pDescriptors + 8; + TD[2].NextTD = realTDA + 48; + TD[2].BufferEnd = 0; + + TD[3].Format = 0xE30050CD; // Queue END + TD[3].Buffer = 0; + TD[3].NextTD = 0; + TD[3].BufferEnd = 0; + +//////////////////////////////////////////////////////////////////////// +// --EndPoint Descriptor ED-- +// Offset Field Size Value Desc +// 0 4 Bitmap +// 0..6 FA - Function Address +// +// 7..10 EN - EndpointNumber +// 11..12 D - Direction +// 00b GetDir From TD +// 01b OUT +// 10b IN +// 11b GetDir From TD +// 13 S - Speed (Full Speed=0) +// 14 K - sKip +// 15 F - Format +// 0 - Control/Bulk/Int +// 1 - Isochronous +// 16..26 MPS MaximumPacketSize +// 27..31 reserved +// 4 4 Bitmap +// 0..3 Zero Aligment +// 4..31 TD Queue Tail Pointer (TailP) +// 8 4 Bitmap +// 0 H - Halted +// 1 C - toggleCarry +// 2..3 reserved +// 4..31 TD Queue Head Pointer (HeadP) +// 12 4 Bitmap +// 0..3 Zero Aligment +// 4..31 Next Endpoint Descriptor (NextED) +// +//(Total Size 16 bytes or 4 dwords) +// +//////////////////////////////////////////////////////////////////////// + + ED[1].Headptr = realTDA; + ED[1].Tailptr = realTDA + 32; + ED[1].Format &= 0xFFFFFF00; // Clear old address + ED[1].Format += Addr; // Insert new address + + + TD[1].BufferEnd = real_pDescriptors + size - 1; + + + ohci->regs->cmdstatus |= 2; // CommandStatus + ohci->regs->control = 0x90; // set CLE + ohci->regs->intrstatus = ohci->regs->intrstatus; // clear all Interruptflags + + +#ifdef USB_DEBUG + // wait for execution + dbg("waiting for execution\n"); +#endif //USB_DEBUG + do + { + + }while( (ohci->regs->intrstatus & 2)== 0 ); + + xSleep(10); + + // ERRORS? + ohci_hcca *hcca = (ohci_hcca*)ohci->hcca; // HCCA + hcca->done_head &= 0xfffffffe; // DoneHead in HCCA + + if( (hcca->done_head>>28) !=0 ) + { +#ifdef USB_DEBUG + dbg("\nError Occured\n"); +#endif //USB_DEBUG + return 1; + } + + //------------------------------------------------------------------ + + // Where all done and finished now, so we set our ED's to our + // Queue END where they behave and wait. + ED[1].Headptr = realTDA + 48; + ED[1].Tailptr = realTDA + 64; + + if( Descriptors[0] < size) size = Descriptors[0]; + + + xSleep(10); + + xmemcpy( data, Descriptors, size); + +#ifdef USB_DEBUG + // Few debug lines + #define OHCI_TD_GET_EC(x) (((x) >> 26) & 3) + #define OHCI_TD_GET_CC(x) ((x) >> 28) + + unsigned int ErrorCount = OHCI_TD_GET_EC( TD[0].Format ); + unsigned int ConditionCode = OHCI_TD_GET_CC( TD[0].Format ); + + sprintf(buf, "TD[0]:ErrorCount: %d\n", ErrorCount); dbg(buf); + sprintf(buf, "TD[0]:ConditionCode: %d\n", ConditionCode); dbg(buf); + + ErrorCount = OHCI_TD_GET_EC( TD[1].Format ); + ConditionCode = OHCI_TD_GET_CC( TD[1].Format ); + + sprintf(buf, "TD[1]:ErrorCount: %d\n", ErrorCount); dbg(buf); + sprintf(buf, "TD[1]:ConditionCode: %d\n", ConditionCode); dbg(buf); +#endif //USB_DEBUG + + return 0; +}// End of get_control_msg(..) + + +/******************************************************************************/ + + + + + + + +/******************************************************************************/ + +int set_control_msg(ohci_t * ohci, + unsigned char Addr, + unsigned char request, // 0x06 + unsigned char requesttype, // 0x80 + unsigned short value, + unsigned short index, + unsigned short size, + unsigned char *data ) +{ + // First, lets desribe what type of message this is! + devrequest cmd; + + + cmd.requesttype = requesttype; //0x80; + cmd.request = request; //0x06; + cmd.value = value; //(0x29<<8); + cmd.index = index; + cmd.length = ((unsigned short) size); + + + xMmLockUnlockBufferPages( (unsigned int)&cmd, 0x8, 0); + unsigned int real_pcmd = xMmGetPhysicalAddress( (unsigned int)&cmd); + + + s_Transferdescriptor *TD; + + + TD = (s_Transferdescriptor *) (((unsigned int *)ED) +20 ); + unsigned int TDA = EDA + 80; + + unsigned int realTDA = xMmGetPhysicalAddress( (unsigned int)TDA ); + + TD[0].Format = 0xE20050C7; // Set Configuration + TD[0].Buffer = real_pcmd; + TD[0].NextTD = realTDA + 16; + TD[0].BufferEnd = real_pcmd + 7; + TD[1].Format = 0xE30050C8; + TD[1].Buffer = 0; + TD[1].NextTD = 0; + TD[1].BufferEnd = 0; + + ED[1].Headptr = realTDA; + ED[1].Tailptr = realTDA + 16; + ED[1].Format &= 0xFFFFFF00; + ED[1].Format += Addr; + + + // set CLF + ohci->regs->cmdstatus |= 2; // CommandStatus + + ohci->regs->control = 0x90; // set CLE + + ohci->regs->intrstatus = ohci->regs->intrstatus; // clear all Interruptflags + +#ifdef USB_DEBUG_ERROR + // wait for execution + dbg("waiting for execution\n"); +#endif //USB_DEBUG + + + + //xSleep(250); + + do + { + + }while( (ohci->regs->intrstatus & 2)== 0 ); + + xSleep(10); + + + // ERRORS? + ohci_hcca *hcca = (ohci_hcca*)ohci->hcca; // HCCA + hcca->done_head &= 0xfffffffe; // DoneHead in HCCA + + if( (hcca->done_head>>28) !=0 ) + { +#ifdef USB_DEBUG + dbg("\nError Occured in set_control_msg(..)\n"); +#endif //USB_DEBUG + return 1; + } + + return 0; + +}// End of set_control_msg(..) + + + + + + +/******************************************************************************/ + +/* +int usb_get_device_descriptor(ohci_t * ohci, unsigned char Addr, int size, void *buf) +{ + unsigned char type = USB_DT_DEVICE; + unsigned char index = 0; + + int ret = get_control_msg(ohci, Addr, + USB_REQ_GET_DESCRIPTOR, USB_DIR_IN, + (type << 8) + index, 0, size, (unsigned char*)buf ); + return ret; + +}// End of usb_get_device_descriptor(..) +*/ + +/******************************************************************************/ +/* +int usb_get_hub_descriptor(ohci_t * ohci, unsigned char Addr, int size, void *buf) +{ + + int ret = get_control_msg(ohci, Addr, + USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB, + (USB_DT_HUB << 8), 0, size, (unsigned char*)buf ); + + return ret; +}// End of usb_get_hub_descriptor(..) +*/ +/******************************************************************************/ + + + +/******************************************************************************/ + + +int usb_set_configuration(ohci_t * ohci, unsigned char Addr, int configuration) +{ + int ret=0; + + ret = set_control_msg(ohci, Addr, + USB_REQ_SET_CONFIGURATION, 0, configuration, 0, 0, NULL); + + + if( ret < 0 ) + return ret; + + return 0; +}// End of usb_set_configuration(..) + + +/******************************************************************************/ + + +void DebugHubDescriptor( usb_hub_descriptor * pDes ) +{ +#ifdef USB_DEBUG + sprintf(buf, "\n@HUB Descriptor@\n"); dbg(buf); + + sprintf(buf, "HubDes.bLength: 0x%02X\n", pDes->bLength ); dbg(buf); + sprintf(buf, "HubDes.bDescriptorType: 0x%02X\n", pDes->bDescriptorType ); dbg(buf); + sprintf(buf, "HubDes.bNbrPorts: 0x%02X\n", pDes->bNbrPorts ); dbg(buf); + sprintf(buf, "HubDes.wHubCharacteristics: 0x%02X\n",pDes->wHubCharacteristics); dbg(buf); + sprintf(buf, "HubDes.bPwrOn2PwrGood: 0x%02X\n", pDes->bPwrOn2PwrGood ); dbg(buf); + sprintf(buf, "HubDes.bHubContrCurrent: 0x%02X\n", pDes->bHubContrCurrent ); dbg(buf); + sprintf(buf, "HubDes.DeviceRemovable: 0x%02X\n", pDes->DeviceRemovable ); dbg(buf); + sprintf(buf, "HubDes.PortPowerCtrlMask: 0x%02X\n", pDes->PortPowerCtrlMask ); dbg(buf); +#endif //USB_DEBUG + +}// End of DebugHubDescriptor + + + +#define UDESC_HUB 0x29 + + +/******************************************************************************/ + +//#define USETW2(w,h,l) (((unsigned char*)(w))[0] = (unsigned char)(l), ((unsigned char*)(w))[1] = (unsigned char)(h)) +unsigned short USETW2(unsigned short v) +{ + unsigned short a = 0;; + a |= (0xff00&(v<<8)); + a |= (0x00ff&(v>>8)); + + return a; +} + +#define UGETW(w) (*(unsigned short *)(w)) +#define USETW(w,v) (*(unsigned short *)(w) = (v)) +#define UGETDW(w) (*(unsigned int *)(w)) +#define USETDW(w,v) (*(unsigned int *)(w) = (v)) + + + +int usbd_do_request(usbd_device * dev, devrequest *req, void *data) +{ + return get_control_msg(dev->p_ohci, + dev->address, + req->request, + req->requesttype, + req->value, + req->index, + req->length, // e.g. size buffer + (unsigned char*)data ); + +}// End of usbd_do_request(..) + + +int usbd_get_hub_descriptor(usbd_device * dev, void * data) +{ + /* Get hub descriptor. */ + devrequest req = {0}; + req.requesttype = UT_READ_CLASS_DEVICE; + req.request = UR_GET_DESCRIPTOR; + req.value = USETW2(USB_DT_HUB); + req.index = 0; + req.length = USB_HUB_DESCRIPTOR_SIZE; + + return usbd_do_request(dev, &req, data); +} + + +int usbd_set_port_feature(usbd_device * dev, int port, int sel) +{ + devrequest req; + + req.requesttype = UT_WRITE_CLASS_OTHER; + req.request = UR_SET_FEATURE; + req.value = sel; + req.index = port; + req.length = 0; + return usbd_do_request(dev, &req, 0); +} + + + +#define UHD_NOT_REMOV(desc, i) \ + (((desc)->DeviceRemovable[(i)/8] >> ((i) % 8)) & 1) + +#define UHF_PORT_POWER 8 + + +int usbd_get_port_status(usbd_device * dev, int port, void *data) +{ + + devrequest req; + + req.requesttype = UT_READ_CLASS_OTHER; + req.request = UR_GET_STATUS; + req.value = 0; + req.index = port; + req.length = sizeof(usb_port_status ); + return usbd_do_request(dev, &req, data); + +}// End of usb_get_port_status(..) + + +#define UPS_C_CONNECT_STATUS 0x0001 +#define UPS_C_PORT_ENABLED 0x0002 +#define UPS_C_SUSPEND 0x0004 +#define UPS_C_OVERCURRENT_INDICATOR 0x0008 +#define UPS_C_PORT_RESET 0x0010 + + +/* BUG~~~~~ this functino needs to be looked at...usb_do_req..should be set*/ +int usbd_clear_port_feature(usbd_device * dev, int port, int sel) +{ + devrequest req; + + req.requesttype = UT_WRITE_CLASS_OTHER; + req.request = UR_CLEAR_FEATURE; + req.value = sel; + req.index = port; + req.length = 0; + return usbd_do_request(dev, &req, 0); +} + +/* Hub features */ +#define UHF_C_HUB_LOCAL_POWER 0 +#define UHF_C_HUB_OVER_CURRENT 1 +#define UHF_PORT_CONNECTION 0 +#define UHF_PORT_ENABLE 1 +#define UHF_PORT_SUSPEND 2 +#define UHF_PORT_OVER_CURRENT 3 +#define UHF_PORT_RESET 4 +#define UHF_PORT_POWER 8 +#define UHF_PORT_LOW_SPEED 9 +#define UHF_C_PORT_CONNECTION 16 +#define UHF_C_PORT_ENABLE 17 +#define UHF_C_PORT_SUSPEND 18 +#define UHF_C_PORT_OVER_CURRENT 19 +#define UHF_C_PORT_RESET 20 +#define UHF_PORT_TEST 21 +#define UHF_PORT_INDICATOR 22 + + +int usbd_reset_port(usbd_device * dev, int port, usb_port_status *ps) +{ + devrequest req; + + int n; + + req.requesttype = UT_WRITE_CLASS_OTHER; + req.request = UR_SET_FEATURE; + req.value = UHF_PORT_RESET; + req.index = port; + req.length = 0; + usbd_do_request(dev, &req, 0); + +#ifdef USB_DEBUG + sprintf(buf, "usbd_reset_port: port %d reset done\n",port); dbg(buf); +#endif //USB_DEBUG + + n = 10; + do { + /* Wait for device to recover from reset. */ + #define USB_PORT_RESET_DELAY 50 + xSleep(USB_PORT_RESET_DELAY); + + usbd_get_port_status(dev, port, ps); + + /* If the device disappeared, just give up. */ + #define UPS_CURRENT_CONNECT_STATUS 0x0001 + if (!((ps->wPortStatus) & UPS_CURRENT_CONNECT_STATUS)) + { +#ifdef USB_DEBUG + dbg("The device disappeared so we give up reset!\n"); +#endif //USB_DEBUG + return 0; + } + } while ( ((ps->wPortChange) & UPS_C_PORT_RESET) == 0 && (--n > 0) ); + + if (n == 0) + { +#ifdef USB_DEBUG + dbg("Timout error in 'usbd_reset_port(..)'\n"); +#endif //USB_DEBUG + return 0; + } + + usbd_clear_port_feature(dev, port, UHF_C_PORT_RESET); + +#ifdef USB_DEBUG + dbg("usbd_reset_port: clear port\n"); +#endif //USB_DEBUG + + /* Wait for the device to recover from reset. */ + #define USB_PORT_RESET_RECOVERY 250 + xSleep(USB_PORT_RESET_RECOVERY); + + return 1; +} + + +//#define USETW2XXX(w,h,l) (((unsigned char*)(w))[0] = (unsigned char)(l), ((unsigned char*)(w))[1] = (unsigned char)(h)) + +int usbd_get_desc(usbd_device * dev, int type, int index, int len, void *desc) +{ + devrequest req = {0}; + +#ifdef USB_DEBUG + sprintf( buf, "usbd_get_desc: type=%d, index=%d, len=%d\n",type, index, len); + dbg(buf); +#endif //USB_DEBUG + + + req.requesttype = UT_READ_DEVICE; + req.request = UR_GET_DESCRIPTOR; + //USETW2XXX(req.value, type, index); + req.value = 0; + req.value |= (0x00ff & index); + req.value |= (0xff00 & (type<<8)); + + req.index = 0; + req.length = len; + + return (usbd_do_request(dev, &req, desc)); +} + + +int usbd_set_address(usbd_device * dev, int addr) +{ + devrequest req = {0}; + + req.requesttype = UT_WRITE_DEVICE; + req.request = UR_SET_ADDRESS; + req.value = addr; + req.index = 0; + req.length = 0; + return usbd_do_request(dev, &req, 0); +} + + +int usbd_set_config(usbd_device * dev, int conf) +{ + devrequest req; + + req.requesttype = UT_WRITE_DEVICE; + req.request = UR_SET_CONFIG; + req.value = conf; + req.index = 0; + req.length = 0; + return usbd_do_request(dev, &req, 0); +} + + + +int usbd_set_config_index(usbd_device * dev, int index, int msg /*1*/) +{ + + s_USB_Configurationdescriptor cd, *cdp; + unsigned char buffer[256]; + cdp = (s_USB_Configurationdescriptor*)buffer; + + #define UDESC_CONFIG 0x02 + #define USB_CONFIG_DESCRIPTOR_SIZE 9 + + + /* Get the short descriptor. */ + usbd_get_desc(dev, UDESC_CONFIG, index, USB_CONFIG_DESCRIPTOR_SIZE, &cd); + + + /* Get the full descriptor. */ + usbd_get_desc(dev, UDESC_CONFIG, index, cd.TotalLength, buffer); + + /* Set the actual configuration value. */ +#ifdef USB_DEBUG + sprintf(buf, "usbd_set_config_index: set config %d\n",cdp->ConfigValue); + dbg(buf); +#endif //USB_DEBUG + usbd_set_config(dev, cdp->ConfigValue); + + + return 1; +} + + +/* +* Called when a new device has been put in the powered state, +* but not yet in the addressed state. +* Get initial descriptor, set the address, get full descriptor, +* and attach a driver. +*/ +extern unsigned char found; + +int usbd_new_device(usbd_device * parent, int b, int depth, + int speed, int port, usb_port_status * ps) +{ +#ifdef USB_DEBUG + sprintf(buf, "usbd_new_device port=%d depth=%d speed=%d\n",port, depth, speed); + dbg(buf); +#endif //USB_DEBUG + + usbd_device dev; + dev.p_ohci = parent->p_ohci; + dev.address = 0; + + found++; + int addr = found; + + s_USB_Devicedescriptor dd = {0}; + /* Try a few times in case the device is slow (i.e. outside specs.) */ + //for (int i = 0; i < 15; i++) + //{ + #define USB_MAX_IPACKET 8 /* maximum size of the initial packet */ + + /* Get the first 8 bytes of the device descriptor. */ + usbd_get_desc(&dev, UDESC_DEVICE, 0, USB_MAX_IPACKET, &dd); + + Sleep(100); + + // if ((i & 3) == 3) + // usbd_reset_port(parent, port, ps); + + //} + + /* Set the address */ +#ifdef USB_DEBUG + sprintf(buf, "****usbd_new_device: adding unit addr= %d *****\n", addr ); dbg(buf); +#endif //USB_DEBUG + + usbd_set_address(&dev, addr); + +#ifdef USB_DEBUG + sprintf(buf, "usbd_new_device: setting device address=%d\n", addr); dbg(buf); +#endif //USB_DEBUG + + /* Allow device time to set new address */ + #define USB_SET_ADDRESS_SETTLE 10 /* ms */ + xSleep(USB_SET_ADDRESS_SETTLE); + + dev.address = addr; + + /* Get full descriptor */ + #define USB_DEVICE_DESCRIPTOR_SIZE 18 + usbd_get_desc(&dev, UDESC_DEVICE, 0, USB_DEVICE_DESCRIPTOR_SIZE, &dd); + +#ifdef USB_DEBUG + DebugDescriptor( &dd ); +#endif //USB_DEBUG + + for (int confi = 0; confi < dd.ConfigNumber; confi++) + { +#ifdef USB_DEBUG + sprintf(buf,"usbd_probe_and_attach: trying config idx=%d\n",confi); dbg(buf); +#endif //USB_DEBUG + + usbd_set_config_index(&dev, confi, 1); + + //usb_set_configuration(dev.p_ohci, dev.address, confi); + } + + Sleep(40); + + do_hub_work(&dev); + + return 1; +} + +int do_hub_work(usbd_device * dev) +{ + unsigned char buffer[256] = {0}; + usb_hub_descriptor hubdesc = {0}; + + int port, nremov=0; + + /* Get hub descriptor. */ +#ifdef USB_DEBUG + dbg("usb_init_hub: getting hub descriptor\n\n"); +#endif //USB_DEBUG + usbd_get_hub_descriptor(dev, (void*)&hubdesc); + +#ifdef USB_DEBUG + DebugHubDescriptor( (usb_hub_descriptor * )&hubdesc ); + dbg("\n\n"); +#endif //USB_DEBUG + + int nports = hubdesc.bNbrPorts; + + //for (nremov = 0, port = 1; port <= nports; port++) + // if (!UHD_NOT_REMOV((&hubdesc), port)) + // nremov++; + + for (port = 1; port <= nports; port++) + { + /* Turn the power on. */ + usbd_set_port_feature(dev, port, UHF_PORT_POWER); +#ifdef USB_DEBUG + sprintf(buf, "usb_init_port: turn on port %d power\n", port); dbg(buf); +#endif //USB_DEBUG + + /* Wait for stable power. */ + Sleep(50); + }// End for loop + +#ifdef USB_DEBUG + dbg("\n\n"); +#endif //USB_DEBUG + + for (port = 1; port <= nports; port++) + { + usb_port_status ps = {0}; + + usbd_get_port_status(dev, port, &ps); + + unsigned short status = ps.wPortStatus; + unsigned short change = ps.wPortChange; + +#ifdef USB_DEBUG + sprintf(buf, "uhub_explore: port %d status 0x%04x 0x%04x\n",port, status, change); + dbg(buf); +#endif //USB_DEBUG + } + + // Wahooo...we have results!....we know whats plugged into our xbox + // first simple step! + /* + Well if you've made it here...XBOX GAMEPAD...well this is what we notice... + we can detect which gamepads are plugged in + gamepad_1 -> port 3 + gamepad_2 -> port 4 + gamepad_3 -> port 1 + gamepad_4 -> port 2 + */ + +#ifdef USB_DEBUG + dbg("\n\n"); +#endif //USB_DEBUG + + for(port = 1; port <= nports; port++) + { + usb_port_status ps = {0}; + + usbd_get_port_status(dev, port, &ps); + + unsigned short status = ps.wPortStatus; + unsigned short change = ps.wPortChange; + +#ifdef USB_DEBUG + sprintf(buf, "uhub_explore: port %d status 0x%04x 0x%04x\n",port, status, change); + dbg(buf); +#endif //USB_DEBUG + +#ifdef USB_DEBUG + if (change & UPS_C_PORT_ENABLED) + dbg("uhub_explore: C_PORT_ENABLED\n"); +#endif //USB_DEBUG + + /* + if (!(change & UPS_C_CONNECT_STATUS)) + { + sprintf(buf, "uhub_explore: port=%d !C_CONNECT_STATUS\n", port); dbg(buf); + + #define UPS_CURRENT_CONNECT_STATUS 0x0001 + if( (status & UPS_CURRENT_CONNECT_STATUS) ) + { + sprintf(buf, "\t\tconnected device\n"); dbg(buf); + } + + //No status change, just do recursive explore + continue; + } + */ + + // Not exactly correct...no change in status...but...just stay with me + // on this + + /* We have a connect status change, handle it. */ +#ifdef USB_DEBUG + sprintf(buf, "uhub_explore: status change hub=%d port=%d\n", dev->address, port); + dbg(buf); +#endif //USB_DEBUG + + usbd_clear_port_feature(dev, port, UHF_C_PORT_CONNECTION); + /*usbd_clear_port_feature(dev, port, UHF_C_PORT_ENABLE);*/ + /* + * If there is already a device on the port the change status + * must mean that is has disconnected. Looking at the + * current connect status is not enough to figure this out + * since a new unit may have been connected before we handle + * the disconnect. + */ + + #define UPS_CURRENT_CONNECT_STATUS 0x0001 + + if (!(status & UPS_CURRENT_CONNECT_STATUS)) + { + /* Nothing connected, just ignore it. */ +#ifdef USB_DEBUG + sprintf(buf, "uhub_explore: port=%d !CURRENT_CONNECT_STATUS\n", port); dbg(buf); +#endif //USB_DEBUG + continue; + } + + /* Connected */ + +#ifdef USB_DEBUG + #define UPS_PORT_POWER 0x0100 + if (!(status & UPS_PORT_POWER)) + { + sprintf(buf, "<>strange, connected port %d has no power\n",port); dbg(buf); + } +#endif //USB_DEBUG + + /* Wait for maximum device power up time. */ + Sleep(50); + + /* Reset port, which implies enabling it. */ + usbd_reset_port(dev, port, &ps); + + /* Get port status again, it might have changed during reset */ + usbd_get_port_status(dev, port, &ps); + + status = ps.wPortStatus; + change = ps.wPortChange; + +#ifdef USB_DEBUG + sprintf(buf, "uhub_explore: port %d status 0x%04x 0x%04x\n",port, status, change); + dbg(buf); +#endif //USB_DEBUG + + #define USB_SPEED_LOW 1 + #define USB_SPEED_FULL 2 + #define USB_SPEED_HIGH 3 + #define UPS_LOW_SPEED 0x0200 + #define UPS_HIGH_SPEED 0x0400 + + int speed; + /* Figure out device speed */ + if (status & UPS_HIGH_SPEED) + speed = USB_SPEED_HIGH; + else if (status & UPS_LOW_SPEED) + speed = USB_SPEED_LOW; + else + speed = USB_SPEED_FULL; // The gamepad is a full speed! + + /* Get device info and set its address. */ + usbd_new_device(dev, 0, 1, speed, port, &ps); + +#ifdef USB_DEBUG + dbg("****************\n"); +#endif //USB_DEBUG + + }// End for loop + + return 1; +}// End of do_hub_work(..) + +int get_control_msg_for_xpad(ohci_t * ohci, + unsigned char Addr, + unsigned char request, // 0x06 + unsigned char requesttype, // 0x80 + unsigned short value, + unsigned short index, + unsigned short size, + unsigned char *data ) +{ + // First, lets desribe what type of message this is! + devrequest cmd; + + cmd.requesttype = requesttype; //0x80; + cmd.request = request; //0x06; + cmd.value = value; //(0x29<<8); + cmd.index = index; + cmd.length = ((unsigned short) size); + + MmLockUnlockBufferPages( (unsigned int)&cmd, 0x8, 0); + unsigned int real_pcmd = MmGetPhysicalAddress( (unsigned int)&cmd); + + unsigned char Descriptors[256] = {0}; + MmLockUnlockBufferPages( (unsigned int)Descriptors, 256, 0 ); + unsigned int real_pDescriptors = MmGetPhysicalAddress( (unsigned int)Descriptors ); + + //unsigned int uTD = (unsigned int)pTD; + //uTD += (unsigned int)0x10; + //uTD &= 0xfffffff0; + + s_Transferdescriptor *TD; + TD = (s_Transferdescriptor *)(((unsigned int *)ED) + 20); + unsigned int TDA = EDA + 80; + unsigned int realTDA = MmGetPhysicalAddress( (unsigned int)TDA ); + +//////////////////////////////////////////////////////////////////////// +// --Transfer Descriptor TD-- +// Offset Field Size Value Desc +// 0 4 0..17 reserved +// +// 18 R - bufferRounding +// 19..20 DP - Direction/PID +// 00b SETUP +// 01b OUT +// 10b IN +// 11b reserved +// 21..23 DI - DelayInterrupt +// 24..25 T - DataToggle +// 26..27 EC - ErrorCount +// 28..31 CC - ConditionCode +// 4 4 CurrentBufferPoinnter (CBP) +// 8 4 0..3 Zero +// 4..31 Next TD (NextTD) +// 12 4 Buffer End (BE) +// +//(Total Size 16 bytes or 4 dwords) +// +//////////////////////////////////////////////////////////////////////// + + unsigned int v_format = 0; + v_format |= (0xE<<28); // 1110b - CC + v_format |= (0x0<<26); // 00b - EC + v_format |= (0x2<<24); // 10b - T + // E2 + v_format |= (0x0<<21); // 000b - DelayInterrupt + v_format |= (0x0<<19); // 00b - DR (SETUP) + v_format |= (0x0<<18); // 0b - bufferRound (NO) + v_format |= (0x0<<16); // 00b - reserved + // 00 + v_format |= 0x50CA; // reserved + // 50CA + + TD[0].Format = 0xE20050CA; // Get Descriptor + TD[0].Buffer = real_pcmd; + TD[0].NextTD = realTDA + 16; + TD[0].BufferEnd = real_pcmd + 7; + + TD[1].Format = 0xE31450CB; // Receive Start of Descriptor + TD[1].Buffer = real_pDescriptors; + TD[1].NextTD = realTDA + 32; + TD[1].BufferEnd = real_pDescriptors + 7; + + //------------------------------------------------------------- + + TD[2].Format = 0xE21450CC; // Receive Rest of Descriptor + TD[2].Buffer = real_pDescriptors + 8; + TD[2].NextTD = realTDA + 48; + TD[2].BufferEnd = 0; + + TD[3].Format = 0xE30050CD; // Queue END + TD[3].Buffer = 0; + TD[3].NextTD = 0; + TD[3].BufferEnd = 0; + +//////////////////////////////////////////////////////////////////////// +// --EndPoint Descriptor ED-- +// Offset Field Size Value Desc +// 0 4 Bitmap +// 0..6 FA - Function Address +// +// 7..10 EN - EndpointNumber +// 11..12 D - Direction +// 00b GetDir From TD +// 01b OUT +// 10b IN +// 11b GetDir From TD +// 13 S - Speed (Full Speed=0) +// 14 K - sKip +// 15 F - Format +// 0 - Control/Bulk/Int +// 1 - Isochronous +// 16..26 MPS MaximumPacketSize +// 27..31 reserved +// 4 4 Bitmap +// 0..3 Zero Aligment +// 4..31 TD Queue Tail Pointer (TailP) +// 8 4 Bitmap +// 0 H - Halted +// 1 C - toggleCarry +// 2..3 reserved +// 4..31 TD Queue Head Pointer (HeadP) +// 12 4 Bitmap +// 0..3 Zero Aligment +// 4..31 Next Endpoint Descriptor (NextED) +// +//(Total Size 16 bytes or 4 dwords) +// +//////////////////////////////////////////////////////////////////////// + + //0x00081801 + + //unsigned int format = 0x00401801; + unsigned int format = 0x00401800; + ED[1].Format = format; + + ED[1].Headptr = realTDA; + ED[1].Tailptr = realTDA + 32; + ED[1].Format &= 0xFFFFFF00; // Clear old address + ED[1].Format += Addr; // Insert new address + + // ED[i].Format = AUTOIO | 0x402000; // AUTOIO 0x1800L + + TD[1].BufferEnd = real_pDescriptors + size - 1; + + ohci->regs->cmdstatus |= 2; // CommandStatus + ohci->regs->control = 0x90; // set CLE + ohci->regs->intrstatus = ohci->regs->intrstatus; // clear all Interruptflags + + // wait for execution + //dbg("waiting for execution\n"); + do + { + + }while( (ohci->regs->intrstatus & 2)== 0 ); + + Sleep(10); + + // ERRORS? + ohci_hcca *hcca = (ohci_hcca*)ohci->hcca; // HCCA + hcca->done_head &= 0xfffffffe; // DoneHead in HCCA + + if( (hcca->done_head>>28) !=0 ) + { + +#ifdef USB_DEBUG + dbg("\nError Occured\n"); +#endif //USB_DEBUG + + return 1; + } + + //------------------------------------------------------------------ + + // Where all done and finished now, so we set our ED's to our + // Queue END where they behave and wait. + ED[1].Headptr = realTDA + 48; + ED[1].Tailptr = realTDA + 64; + + if( Descriptors[0] < size) size = Descriptors[0]; + +#ifdef USB_DEBUG + // Few debug lines + #define OHCI_TD_GET_EC(x) (((x) >> 26) & 3) + #define OHCI_TD_GET_CC(x) ((x) >> 28) + + unsigned int ErrorCount = OHCI_TD_GET_EC( TD[0].Format ); + unsigned int ConditionCode = OHCI_TD_GET_CC( TD[0].Format ); + + sprintf(buf, "TD[0]:ErrorCount: %d\n", ErrorCount); dbg(buf); + sprintf(buf, "TD[0]:ConditionCode: %d\n", ConditionCode); dbg(buf); + + ErrorCount = OHCI_TD_GET_EC( TD[1].Format ); + ConditionCode = OHCI_TD_GET_CC( TD[1].Format ); + + sprintf(buf, "TD[1]:ErrorCount: %d\n", ErrorCount); dbg(buf); + sprintf(buf, "TD[1]:ConditionCode: %d\n", ConditionCode); dbg(buf); +#endif //USB_DEBUG + + Sleep(10); + + memcpy( data, Descriptors, size); + + ED[1].Format = 0x00081801; + + return 0; +} + +int usbd_do_request_big_packet(usbd_device * dev, devrequest *req, void *data) +{ + return get_control_msg_for_xpad(dev->p_ohci, + dev->address, + req->request, + req->requesttype, + req->value, + req->index, + req->length, // e.g. size buffer + (unsigned char*)data ); + +}// End of usbd_do_request(..) diff --git a/src/libXFX/usb/hub.h b/src/libXFX/usb/hub.h new file mode 100644 index 0000000..278454e --- /dev/null +++ b/src/libXFX/usb/hub.h @@ -0,0 +1,406 @@ +/******************************************************************************/ +/* */ +/* File: hub.h */ +/* bkenwright@xbdev.net - www.xbdev.net */ +/* */ +/******************************************************************************/ + +#pragma once + +#include "ohci.h" + + + +/******************************************************************************/ +/* USB CONSTANTS */ +/******************************************************************************/ + +/* + * Device and/or Interface Class codes + */ +#define USB_CLASS_PER_INTERFACE 0 /* for DeviceClass */ +#define USB_CLASS_AUDIO 1 +#define USB_CLASS_COMM 2 +#define USB_CLASS_HID 3 +#define USB_CLASS_PRINTER 7 +#define USB_CLASS_MASS_STORAGE 8 +#define USB_CLASS_HUB 9 +#define USB_CLASS_DATA 10 +#define USB_CLASS_VENDOR_SPEC 0xff + +/* + * Descriptor types + */ +#define USB_DT_DEVICE 0x01 +#define USB_DT_CONFIG 0x02 +#define USB_DT_STRING 0x03 +#define USB_DT_INTERFACE 0x04 +#define USB_DT_ENDPOINT 0x05 + +#define USB_DT_HUB 0x29 +#define USB_DT_HID 0x21 +#define USB_DT_REPORT 0x22 +#define USB_DT_PHYSICAL 0x23 + +/* + * Descriptor sizes per descriptor type + */ +#define USB_DT_DEVICE_SIZE 18 +#define USB_DT_CONFIG_SIZE 9 +#define USB_DT_INTERFACE_SIZE 9 +#define USB_DT_ENDPOINT_SIZE 7 +#define USB_DT_ENDPOINT_AUDIO_SIZE 9 /* Audio extension */ +#define USB_DT_HUB_NONVAR_SIZE 7 + +/* + * USB Request Type and Endpoint Directions + */ +#define USB_DIR_OUT 0 +#define USB_DIR_IN 0x80 + +#define USB_ENDPOINT_NUMBER_MASK 0x0f /* in bEndpointAddress */ +#define USB_ENDPOINT_DIR_MASK 0x80 + +#define USB_ENDPOINT_XFERTYPE_MASK 0x03 /* in bmAttributes */ +#define USB_ENDPOINT_XFER_CONTROL 0 +#define USB_ENDPOINT_XFER_ISOC 1 +#define USB_ENDPOINT_XFER_BULK 2 +#define USB_ENDPOINT_XFER_INT 3 + +/* + * USB Packet IDs (PIDs) + */ +#define USB_PID_OUT 0xe1 +#define USB_PID_IN 0x69 +#define USB_PID_SETUP 0x2d + +/* + * Standard requests + */ +#define USB_REQ_GET_STATUS 0x00 +#define USB_REQ_CLEAR_FEATURE 0x01 +/* 0x02 is reserved */ +#define USB_REQ_SET_FEATURE 0x03 +/* 0x04 is reserved */ +#define USB_REQ_SET_ADDRESS 0x05 +#define USB_REQ_GET_DESCRIPTOR 0x06 +#define USB_REQ_SET_DESCRIPTOR 0x07 +#define USB_REQ_GET_CONFIGURATION 0x08 +#define USB_REQ_SET_CONFIGURATION 0x09 +#define USB_REQ_GET_INTERFACE 0x0A +#define USB_REQ_SET_INTERFACE 0x0B +#define USB_REQ_SYNCH_FRAME 0x0C + +/* + * HIDD requests + */ +#define USB_REQ_GET_REPORT 0x01 +#define USB_REQ_GET_IDLE 0x02 +#define USB_REQ_GET_PROTOCOL 0x03 +#define USB_REQ_SET_REPORT 0x09 +#define USB_REQ_SET_IDLE 0x0A +#define USB_REQ_SET_PROTOCOL 0x0B + +#define USB_TYPE_STANDARD (0x00 << 5) +#define USB_TYPE_CLASS (0x01 << 5) +#define USB_TYPE_VENDOR (0x02 << 5) +#define USB_TYPE_RESERVED (0x03 << 5) + +#define USB_RECIP_DEVICE 0x00 +#define USB_RECIP_INTERFACE 0x01 +#define USB_RECIP_ENDPOINT 0x02 +#define USB_RECIP_OTHER 0x03 + +#define USB_HID_RPT_INPUT 0x01 +#define USB_HID_RPT_OUTPUT 0x02 +#define USB_HID_RPT_FEATURE 0x03 + +/* + * Request target types. + */ +#define USB_RT_DEVICE 0x00 +#define USB_RT_INTERFACE 0x01 +#define USB_RT_ENDPOINT 0x02 + +#define USB_RT_HUB (USB_TYPE_CLASS | USB_RECIP_DEVICE) +#define USB_RT_PORT (USB_TYPE_CLASS | USB_RECIP_OTHER) + +#define USB_RT_HIDD (USB_TYPE_CLASS | USB_RECIP_INTERFACE) + + +/******************************************************************************/ +/* HUB CONTANTS */ +/******************************************************************************/ + + + + +/* + * Hub Class feature numbers + */ +#define C_HUB_LOCAL_POWER 0 +#define C_HUB_OVER_CURRENT 1 + +/* + * Port feature numbers + */ +#define USB_PORT_FEAT_CONNECTION 0 +#define USB_PORT_FEAT_ENABLE 1 +#define USB_PORT_FEAT_SUSPEND 2 +#define USB_PORT_FEAT_OVER_CURRENT 3 +#define USB_PORT_FEAT_RESET 4 +#define USB_PORT_FEAT_POWER 8 +#define USB_PORT_FEAT_LOWSPEED 9 +#define USB_PORT_FEAT_C_CONNECTION 16 +#define USB_PORT_FEAT_C_ENABLE 17 +#define USB_PORT_FEAT_C_SUSPEND 18 +#define USB_PORT_FEAT_C_OVER_CURRENT 19 +#define USB_PORT_FEAT_C_RESET 20 + + +#pragma pack( push, 1 ) +struct usb_port_status +{ + __u16 wPortStatus; + __u16 wPortChange; +}; +#pragma pack( pop ) + + +/* wPortStatus bits */ +#define USB_PORT_STAT_CONNECTION 0x0001 +#define USB_PORT_STAT_ENABLE 0x0002 +#define USB_PORT_STAT_SUSPEND 0x0004 +#define USB_PORT_STAT_OVERCURRENT 0x0008 +#define USB_PORT_STAT_RESET 0x0010 +#define USB_PORT_STAT_POWER 0x0100 +#define USB_PORT_STAT_LOW_SPEED 0x0200 + +/* wPortChange bits */ +#define USB_PORT_STAT_C_CONNECTION 0x0001 +#define USB_PORT_STAT_C_ENABLE 0x0002 +#define USB_PORT_STAT_C_SUSPEND 0x0004 +#define USB_PORT_STAT_C_OVERCURRENT 0x0008 +#define USB_PORT_STAT_C_RESET 0x0010 + +/* wHubCharacteristics (masks) */ +#define HUB_CHAR_LPSM 0x0003 +#define HUB_CHAR_COMPOUND 0x0004 +#define HUB_CHAR_OCPM 0x0018 + +#pragma pack( push, 1 ) +struct usb_hub_status +{ + __u16 wHubStatus; + __u16 wHubChange; +}; +#pragma pack( pop ) + +/* + *Hub Status & Hub Change bit masks + */ +#define HUB_STATUS_LOCAL_POWER 0x0001 +#define HUB_STATUS_OVERCURRENT 0x0002 + +#define HUB_CHANGE_LOCAL_POWER 0x0001 +#define HUB_CHANGE_OVERCURRENT 0x0002 + +/* Hub descriptor */ +#pragma pack( push, 1 ) +struct usb_hub_descriptor +{ + __u8 bLength; + __u8 bDescriptorType; + __u8 bNbrPorts; + __u16 wHubCharacteristics; + __u8 bPwrOn2PwrGood; + __u8 bHubContrCurrent; + __u8 DeviceRemovable; + __u8 PortPowerCtrlMask; +}; +#pragma pack( pop ) + +/* +struct usb_hub_descriptor_t +{ + __u8 bDescLength; + __u8 bDescriptorType; + __u8 bNbrPorts; + __u16 wHubCharacteristics; + #define UHD_PWR 0x0003 + #define UHD_PWR_GANGED 0x0000 + #define UHD_PWR_INDIVIDUAL 0x0001 + #define UHD_PWR_NO_SWITCH 0x0002 + #define UHD_COMPOUND 0x0004 + #define UHD_OC 0x0018 + #define UHD_OC_GLOBAL 0x0000 + #define UHD_OC_INDIVIDUAL 0x0008 + #define UHD_OC_NONE 0x0010 + #define UHD_TT_THINK 0x0060 + #define UHD_TT_THINK_8 0x0000 + #define UHD_TT_THINK_16 0x0020 + #define UHD_TT_THINK_24 0x0040 + #define UHD_TT_THINK_32 0x0060 + #define UHD_PORT_IND 0x0080 + + __u8 bPwrOn2PwrGood; // delay in 2 ms units + #define UHD_PWRON_FACTOR 2 + + __u8 bHubContrCurrent; + __u8 DeviceRemovable[32]; //max 255 ports + + #define UHD_NOT_REMOV(desc, i) \ + (((desc)->DeviceRemovable[(i)/8] >> ((i) % 8)) & 1) + __u8 PortPowerCtrlMask[1]; // deprecated + }; +*/ +#define USB_HUB_DESCRIPTOR_SIZE 9 /* includes deprecated PortPowerCtrlMask */ + + +/******************************************************************************/ +/******************************************************************************/ +/******************************************************************************/ + +int get_control_msg(ohci_t * ohci, + __u8 Addr, + __u8 request, // 0x06 + __u8 requesttype, // 0x80 + __u16 value, + __u16 index, + __u16 size, + __u8 * data ); + + + + +int set_control_msg(ohci_t * ohci, + __u8 Addr, + __u8 request, + __u8 requesttype, + __u16 value, + __u16 index, + __u16 size, + __u8 * data ); + + + +//int usb_get_device_descriptor(ohci_t * ohci, __u8 Addr, int size, void *buf); + + +//int usb_get_hub_descriptor(ohci_t * ohci, __u8 Addr, int size, void *buf); + + + + +int usb_set_configuration(ohci_t * ohci, __u8 Addr, int configuration); + + +void DebugHubDescriptor( usb_hub_descriptor * pDes ); + + + +/***********************************************************************************/ + + +#define UT_WRITE 0x00 +#define UT_READ 0x80 +#define UT_STANDARD 0x00 +#define UT_CLASS 0x20 +#define UT_VENDOR 0x40 +#define UT_DEVICE 0x00 +#define UT_INTERFACE 0x01 +#define UT_ENDPOINT 0x02 +#define UT_OTHER 0x03 + +#define UT_READ_DEVICE (UT_READ | UT_STANDARD | UT_DEVICE) +#define UT_READ_INTERFACE (UT_READ | UT_STANDARD | UT_INTERFACE) +#define UT_READ_ENDPOINT (UT_READ | UT_STANDARD | UT_ENDPOINT) +#define UT_WRITE_DEVICE (UT_WRITE | UT_STANDARD | UT_DEVICE) +#define UT_WRITE_INTERFACE (UT_WRITE | UT_STANDARD | UT_INTERFACE) +#define UT_WRITE_ENDPOINT (UT_WRITE | UT_STANDARD | UT_ENDPOINT) +#define UT_READ_CLASS_DEVICE (UT_READ | UT_CLASS | UT_DEVICE) +#define UT_READ_CLASS_INTERFACE (UT_READ | UT_CLASS | UT_INTERFACE) +#define UT_READ_CLASS_OTHER (UT_READ | UT_CLASS | UT_OTHER) +#define UT_READ_CLASS_ENDPOINT (UT_READ | UT_CLASS | UT_ENDPOINT) +#define UT_WRITE_CLASS_DEVICE (UT_WRITE | UT_CLASS | UT_DEVICE) +#define UT_WRITE_CLASS_INTERFACE (UT_WRITE | UT_CLASS | UT_INTERFACE) +#define UT_WRITE_CLASS_OTHER (UT_WRITE | UT_CLASS | UT_OTHER) +#define UT_WRITE_CLASS_ENDPOINT (UT_WRITE | UT_CLASS | UT_ENDPOINT) +#define UT_READ_VENDOR_DEVICE (UT_READ | UT_VENDOR | UT_DEVICE) +#define UT_READ_VENDOR_INTERFACE (UT_READ | UT_VENDOR | UT_INTERFACE) +#define UT_READ_VENDOR_OTHER (UT_READ | UT_VENDOR | UT_OTHER) +#define UT_READ_VENDOR_ENDPOINT (UT_READ | UT_VENDOR | UT_ENDPOINT) +#define UT_WRITE_VENDOR_DEVICE (UT_WRITE | UT_VENDOR | UT_DEVICE) +#define UT_WRITE_VENDOR_INTERFACE (UT_WRITE | UT_VENDOR | UT_INTERFACE) +#define UT_WRITE_VENDOR_OTHER (UT_WRITE | UT_VENDOR | UT_OTHER) +#define UT_WRITE_VENDOR_ENDPOINT (UT_WRITE | UT_VENDOR | UT_ENDPOINT) + +/* Requests */ +#define UR_GET_STATUS 0x00 +#define UR_CLEAR_FEATURE 0x01 +#define UR_SET_FEATURE 0x03 +#define UR_SET_ADDRESS 0x05 +#define UR_GET_DESCRIPTOR 0x06 +#define UDESC_DEVICE 0x01 +#define UDESC_CONFIG 0x02 +#define UDESC_STRING 0x03 +#define UDESC_INTERFACE 0x04 +#define UDESC_ENDPOINT 0x05 +#define UDESC_DEVICE_QUALIFIER 0x06 +#define UDESC_OTHER_SPEED_CONFIGURATION 0x07 +#define UDESC_INTERFACE_POWER 0x08 +#define UDESC_OTG 0x09 +#define UDESC_CS_DEVICE 0x21 /* class specific */ +#define UDESC_CS_CONFIG 0x22 +#define UDESC_CS_STRING 0x23 +#define UDESC_CS_INTERFACE 0x24 +#define UDESC_CS_ENDPOINT 0x25 +#define UDESC_HUB 0x29 +#define UR_SET_DESCRIPTOR 0x07 +#define UR_GET_CONFIG 0x08 +#define UR_SET_CONFIG 0x09 +#define UR_GET_INTERFACE 0x0a +#define UR_SET_INTERFACE 0x0b +#define UR_SYNCH_FRAME 0x0c + + + +/***********************************************************************************/ + +struct devrequest +{ + unsigned char requesttype; // 1 byte + unsigned char request; // 1 byte + unsigned short value; // 2 bytes + unsigned short index; // 2 bytes + unsigned short length; // 2 bytes +};// end devrequest // Total = 8 bytes + + +struct usbd_device +{ + ohci_t * p_ohci; /* our ohci stuff */ + __u8 address; /* device addess */ +};// end usbd_device + + + +int usbd_get_desc(usbd_device * dev, int type, int index, int len, void *desc); + +int usbd_do_request(usbd_device * dev, devrequest *req, void *data); + + +int usbd_get_hub_descriptor(usbd_device * dev, void * data); + + +int do_hub_work(usbd_device * dev); + + +int usbd_do_request_big_packet(usbd_device * dev, devrequest *req, void *data); + + + + + + + diff --git a/src/libXFX/usb/ohci.cpp b/src/libXFX/usb/ohci.cpp new file mode 100644 index 0000000..4bbdf65 --- /dev/null +++ b/src/libXFX/usb/ohci.cpp @@ -0,0 +1,733 @@ +/******************************************************************************/ +/* */ +/* File: ohci.cpp */ +/* */ +/* Details: Original File & Design: Thomas Frei */ +/* (modifications for xbox openxdk by bkenwright) */ +/* (bkenwright@xbdev.net) www.xbdev.net */ +/* and Halofreak1990 (halofreak_1990@hotmail.com) */ +/* */ +/******************************************************************************/ + +//#define USB_DEBUG + +#include "misc.h" + +#ifdef USB_DEBUG +#include // sprintf(..) +#endif //USB_DEBUG + +#include "ohci.h" + +/******************************************************************************/ +/* */ +/* Globals */ +/* */ +/******************************************************************************/ + +unsigned int eds[176 + 0x100 + 0x100]; +unsigned int EDA; +s_Endpointdescripor * ED; +unsigned char found = 0; + +/******************************************************************************/ +int FindOHC(ohci_t * ohci, void *regbase) +{ + // STI and CLI can be used to enable/disable interrupts + /* + __asm + { + cli + } + */ + + void *hcca; + + memset(ohci,0,sizeof(ohci_t)); + + ohci->regs = (ohci_regs*)regbase; + + // This is where we align or hcca so its 256byte aligned + hcca = malloc(0x10000+0x100); + memset(hcca,0,0x10000+0x100); + ohci->hcca = (ohci_hcca *)((unsigned int)(unsigned int(hcca) + 0x100) & 0xffffff00); + + MmLockUnlockBufferPages( (unsigned int)hcca, 0x10000+0x100, 0); + + MmLockUnlockBufferPages( (unsigned int)eds, 0x100, 0); + + // Just make sure our memory for ED's is aligned + EDA = (unsigned int)eds; + EDA += 0x100; + EDA &= 0xfffff00; // e.g was 0x0002ED20, but is now 0x0002EE00, so its + // 16 bit memory aligned + ED = (s_Endpointdescripor*)EDA; + + unsigned int realEDA = MmGetPhysicalAddress( (unsigned int)EDA ); + + unsigned int * pHCCA = (unsigned int*)ohci->hcca; + for(int i=0; i<32; i++) pHCCA[i] = realEDA; //EDA; + pHCCA[32] = 0; + pHCCA[33] = 0; + + for( i=0; i<5; i++ ) + { + ED[i].Format = AUTOIO | 0x402000; // AUTOIO 0x1800L + ED[i].NextED = realEDA + (16*(i+1)); //EDA + (16*(i+1)); + ED[i].Headptr = 0; + ED[i].Tailptr = 0; + } + + ED[0].Format = 0x4000; // Should really explain whats happening + ED[0].NextED = 0; // here, ED[0] is going to be the bulkhead descriptor. + ED[1].NextED = 0; // It is setup, but never used - as you'll always see + ED[4].NextED = 0; // ED[1] being set with values in this demo code. + // As ED's are all 16bit aligned this way. + // init the hardware + + // what state is the hardware in at the moment? (usually reset state) + switch( ohci->regs->control & 0xc0 ) + { + case 0x0: // in reset: a cold boot + ohci->regs->roothub.a = 0x10000204; + ohci->regs->roothub.b = 0x00020002; + ohci->regs->fminterval = (4096<<16)|(11999); + ohci->regs->control = ((ohci->regs->control) & (~0xc0))|0x80; + break; + + case 0x80: // operational already + break; + + case 0x40: // resume + case 0xc0: // suspend + ohci->regs->control = ((ohci->regs->control)&(~0xc0))|0x40; + Sleep(50000); + break; + } + + unsigned int fminterval = ohci->regs->fminterval; // stash interval + ohci->regs->cmdstatus = 1; // host controller reset + + Sleep(20); // should only take 10us max to reset + + ohci->regs->fminterval = fminterval; // restore our saved interval + + unsigned int realhcca = MmGetPhysicalAddress( (unsigned int)ohci->hcca ); + //ohci->regs->hcca = (unsigned int)ohci->hcca; + ohci->regs->hcca = realhcca; + + //ohci->regs->intrdisable = ~0x0; // Not sure about this...but turn off any interrupts? + + ohci->regs->intrenable = 0xC000007B; // set HcInterruptEnable + + ohci->regs->control = 0x00000080; // HC operational + + Sleep(50); + +#ifdef USB_DEBUG + // HCFS - usb state (00,01,10,11->reset,resume,operational,suspend) + // bits 6 and 7 in the control register + sprintf( buf, "USBOPERATIONAL : %s\n", ( ((ohci->regs->control>>6) & 0x3) == 0x2) ? "yes":"no" ); dbg(buf); + sprintf( buf, "USBOPERATIONAL : 0x%02X\n", ( (ohci->regs->control>>6) & 0x3)); dbg(buf); +#endif // USB_DEBUG + + ohci->regs->fminterval |= 0x27780000; // set FSLargestDataPacket + + unsigned int temp = ohci->regs->fminterval & 0xffff; + temp /= 10; + ohci->regs->periodicstart = temp; // set HcPeriodicStart to 10% of HcFmInterval + + // Global power on + ohci->regs->roothub.status = 0x10000; + + unsigned int tt = ohci->regs->intrstatus; // clear interrupts + ohci->regs->intrstatus = tt; + +#ifdef USB_DEBUG + DebugFile( ohci ); +#endif // USB_DEBUG + + //ohci->regs->ed_bulkhead = EDA; // BulkHead + + //unsigned int realEDA = MmGetPhysicalAddress( (unsigned int)EDA ); + ohci->regs->ed_bulkhead = realEDA; + + // link ED's in Queue + //ohci->regs->ed_controlhead = EDA+16; // ControlHead + ohci->regs->ed_controlhead = realEDA + 16; + + // NDP + int NDP = (ohci->regs->roothub.a & 0xFF); + + // disable all devices + for( int i=0; i<4; i++ ) + { + ohci->regs->roothub.portstatus[i] = 0x11; + } + + return NDP; +}// End FindOHC(..) + +/******************************************************************************/ +int FindDev(ohci_t * ohci, int Port) +{ + unsigned int TDA; + int Speed=0; + + s_USB_Devicedescriptor DD; + s_USB_Devicedescriptor * pDD = ⅅ + memset(pDD, 0, sizeof(DD) ); + + s_Transferdescriptor * TD; + + unsigned int GetDescr[2] = { 0x01000680, 0x00080000 }; + unsigned int WG = (unsigned int)GetDescr; + MmLockUnlockBufferPages( WG, 0x8, 0); + unsigned int DDA = (unsigned int)pDD; + MmLockUnlockBufferPages( DDA, 0x32, 0); + + TD = (s_Transferdescriptor*) (((unsigned int*)ED)+20); // Same as saying TD = EDA+80 ;) + TDA = EDA + 80; + + unsigned int realTDA = MmGetPhysicalAddress( (unsigned int)TDA ); + + TD[0].Format = 0xE20050C0; // Get DeviceDescriptor + TD[0].Buffer = MmGetPhysicalAddress(WG); + //TD[0].NextTD = TDA + 16; + TD[0].NextTD = realTDA + 16; + TD[0].BufferEnd = MmGetPhysicalAddress(WG+7); + TD[1].Format = 0xE31050C1; // Receive first 8 bytes of DeviceDescriptor + TD[1].Buffer = MmGetPhysicalAddress(DDA); + TD[1].NextTD = realTDA + 32; + TD[1].BufferEnd = MmGetPhysicalAddress(DDA + 7); + TD[2].Format = 0xE20050C2; // Queue END + TD[2].Buffer = 0; + TD[2].NextTD = 0; + TD[2].BufferEnd = 0; + + // Power on + Enable Ports + ohci->regs->roothub.portstatus[ Port ] = 0x100; + Sleep(2); + + if( (ohci->regs->roothub.portstatus[ Port] & 1) == 0 ) + return 0; // No device + + if( ohci->regs->roothub.portstatus[ Port] & 0x200) // lowspeed device? + Speed = 1; + else + Speed = 2; + + if( ohci->regs->roothub.portstatus[ Port ] & 0x10000 ) // Port Power changed? + { + ohci->regs->roothub.portstatus[ Port ] = 0x10000; // Port power Ack + } + + // Port Reset + // We will try and do this 4 times + ohci->regs->roothub.portstatus[ Port ] = 0x10; + Sleep(40); + for(int i=0; i<4; i++) + { + if( (ohci->regs->roothub.portstatus[ Port ] & 0x10) == 0 ) + break; + +#ifdef USB_DEBUG + sprintf(buf, "\tport: %d, reset failed %d times\n", Port, i); + dbg(buf); +#endif //USB_DEBUG + + Sleep(100); + } + + ohci->regs->roothub.portstatus[ Port ] = 0x100000; + + if( (ohci->regs->roothub.portstatus[ Port ] & 7) != 3 ) // Port disabled? + { + ohci->regs->roothub.portstatus[ Port ] = 2; + } + + // Configure Endpointdescriptor + if(Speed==2) + ED[1].Format &= 0xFFFFDFFF; + else + ED[1].Format |= 0x2000; + + // determine MPS + ED[1].Headptr = realTDA; + ED[1].Tailptr = realTDA + 32; + ED[1].Format &= 0xffffff00; + + // set CLF + ohci->regs->cmdstatus |= 2; // CommandStatus + + ohci->regs->control = 0x90; // set CLE + + unsigned int tt = ohci->regs->intrstatus; // clear all Interruptflags + ohci->regs->intrstatus = tt; + +#ifdef USB_DEBUG + DebugFile( ohci ); +#endif // USB_DEBUG + +#ifdef USB_DEBUG + // wait for execution + dbg("waiting for execution\n"); +#endif // USB_DEBUG + do + { + ohci->regs->intrstatus = 0x4; // SOF + + }while( (ohci->regs->intrstatus & 2)== 0 ); + + Sleep(10); + + // Errors? + ohci_hcca *hcca = (ohci_hcca*)ohci->hcca; // HCCA + hcca->done_head &= 0xfffffffe; // DoneHead in HCCA + + if( (hcca->done_head>>28)==0 ) + { + ED[1].Format &= 0xF800FFFF; + ED[1].Format |= (((unsigned int)DD.MaxPacketSize) << 16); + found++; + } + else + return 0; + +#ifdef USB_DEBUG + sprintf(buf, "\nDescriptor.Length: 0x%x\n", DD.Length ); dbg(buf); + sprintf(buf, "Descriptor.DescriptorType: 0x%02X\n", DD.DescriptorType ); dbg(buf); + sprintf(buf, "Descriptor.USB: 0x%04X\n", DD.USB ); dbg(buf); + sprintf(buf, "Descriptor.DeviceClass: 0x%04X\n", DD.DeviceClass ); dbg(buf); + sprintf(buf, "Descriptor.DeviceSubClass: 0x%04X\n", DD.DeviceSubClass ); dbg(buf); + sprintf(buf, "Descriptor.DeviceProtocol: 0x%04X\n", DD.DeviceProtocol ); dbg(buf); + sprintf(buf, "Descriptor.MaxPacketSize: 0x%04X\n", DD.MaxPacketSize ); dbg(buf); + sprintf(buf, "Descriptor.Vendor: 0x%04X\n", DD.Vendor ); dbg(buf); + sprintf(buf, "Descriptor.ProductID: 0x%04X\n", DD.ProductID ); dbg(buf); + sprintf(buf, "Descriptor.Manufacturer: 0x%04X\n", DD.Manufacturer ); dbg(buf); + sprintf(buf, "Descriptor.ProductIndex: 0x%04X\n", DD.ProductIndex ); dbg(buf); + sprintf(buf, "Descriptor.SerialNumber: 0x%04X\n", DD.SerialNumber ); dbg(buf); + sprintf(buf, "Descriptor.ConfigNumber: 0x%04X\n", DD.ConfigNumber ); dbg(buf); +#endif // USB_DEBUG + + return (Speed); +}// End FindDev(..) + +/******************************************************************************/ +int ResetPort(ohci_t * ohci, int Port) +{ + ohci->regs->roothub.portstatus[ Port*4 ] = 0x10; + Sleep(40); + + ohci->regs->roothub.portstatus[ Port*4 ] = 0x100000; + + return 0; +}// End ResetPort(..) + +/******************************************************************************/ +int SetAddres(ohci_t * ohci, int Port, unsigned char AddrNew) +{ + unsigned int SetAddr[2] = {0x00000500, 0 }; + unsigned int WS = (unsigned int)SetAddr; + + s_Transferdescriptor *TD; + unsigned char P = Port; + + if( P==0 ) P = found; + + SetAddr[0] |= (((unsigned int)AddrNew)<<16); + + MmLockUnlockBufferPages( WS, 0x8, 0); + + unsigned int TDA; + + //TD = (s_Transferdescriptor* ) new int[0x1000]; + //TD = (s_Transferdescriptor*) ((((unsigned int)TD)+0x100)&0xfffff00); + //memset(TD, 0, sizeof(s_Transferdescriptor)*4 ); + + ///TD = (s_Transferdescriptor *) (((unsigned int *)ED)+20); + TD = (s_Transferdescriptor *)(EDA+80); + TDA = EDA+80; + + unsigned int realTDA = MmGetPhysicalAddress( (unsigned int)TDA ); + + TD[0].Format = 0xE20050C4; // Set Address + TD[0].Buffer = MmGetPhysicalAddress(WS); + TD[0].NextTD = realTDA + 16; // (unsigned int)(&TD[1]); //TDA + 16; + TD[0].BufferEnd = MmGetPhysicalAddress(WS + 7); + TD[1].Format = 0xE31050C5; // Receive Acknowledge + TD[1].Buffer = 0; + TD[1].NextTD = realTDA + 32; // (unsigned int)(&TD[2]); //TDA + 32; + TD[1].BufferEnd = 0; + TD[2].Format = 0xE20050C6; // End Queue + TD[2].Buffer = 0; + TD[2].NextTD = 0; + TD[2].BufferEnd = 0; + + //ED[1].Headptr = (unsigned int)(&(TD[0])); // TDA; + //ED[1].Tailptr = (unsigned int)(&(TD[2])); // TDA + 32; + + ED[1].Headptr = realTDA; + ED[1].Tailptr = realTDA + 32; + + // set CLF + ohci->regs->cmdstatus |= 2; // CommandStatus + + ohci->regs->control = 0x90; // set CLE + + ohci->regs->intrstatus = ohci->regs->intrstatus; // clear all Interruptflags + + DebugFile( ohci ); + +#ifdef USB_DEBUG + // wait for execution + dbg("waiting for execution\n"); +#endif // USB_DEBUG + do + { + + }while( (ohci->regs->intrstatus & 2)== 0 ); + + Sleep(10); + + // ERRORS? + ohci_hcca *hcca = (ohci_hcca*)ohci->hcca; // HCCA + hcca->done_head &= 0xfffffffe; // DoneHead in HCCA + + if( (hcca->done_head>>28) !=0 ) + return 1; + + ED[1].Format &= 0xFFFFFF00; + ED[1].Format += AddrNew; + + return 0; +}// End SetAddr(..) + +/******************************************************************************/ +int SetConfigur(ohci_t * ohci, unsigned char Addr, unsigned char Config) +{ + unsigned int SetConfig[2] = {0x00000900, 0 }; + + unsigned int WC = (unsigned int)SetConfig; + + s_Transferdescriptor *TD; + + SetConfig[0] |= (((unsigned int)Config)<<16); + + MmLockUnlockBufferPages( WC, 0x8, 0); + + unsigned int TDA; + + TD = (s_Transferdescriptor *) (((unsigned int *)ED) +20 ); + TDA = EDA + 80; + + unsigned int realTDA = MmGetPhysicalAddress( (unsigned int)TDA ); + + TD[0].Format = 0xE20050C7; // Set Configuration + TD[0].Buffer = MmGetPhysicalAddress(WC); + TD[0].NextTD = realTDA + 16;//TDA + 16; + TD[0].BufferEnd = MmGetPhysicalAddress(WC + 7); + TD[1].Format = 0xE30050C8; + TD[1].Buffer = 0; + TD[1].NextTD = 0; + TD[1].BufferEnd = 0; + + ED[1].Headptr = realTDA; //TDA; + ED[1].Tailptr = realTDA + 16; //TDA + 16; + ED[1].Format &= 0xFFFFFF00; + ED[1].Format += Addr; + + // set CLF + ohci->regs->cmdstatus |= 2; // CommandStatus + + ohci->regs->control = 0x90; // set CLE + + ohci->regs->intrstatus = ohci->regs->intrstatus; // clear all Interruptflags + +#ifdef USB_DEBUG + // wait for execution + dbg("waiting for execution\n"); +#endif //USB_DEBUG + do + { + + }while( (ohci->regs->intrstatus & 2)== 0 ); + + Sleep(10); + + // ERRORS? + //ohci_hcca *hcca = (ohci_hcca*)ohci->regs->hcca; // HCCA + ohci_hcca *hcca = (ohci_hcca*)ohci->hcca; + hcca->done_head &= 0xfffffffe; // DoneHead in HCCA + + if( (hcca->done_head>>28) !=0 ) + return 1; + + return 0; +}// End SetConfig(..) + +/******************************************************************************/ +int GetDesc(ohci_t * ohci, unsigned char Addr, unsigned char DescrType, unsigned char Index, unsigned char Count, unsigned char *DBuffer) +{ + unsigned int TDA; + + unsigned char Descriptors[256]; + unsigned int GetDescr[2] = {0x00000680, 0x0 }; + unsigned int WG = (unsigned int)GetDescr; + unsigned int DA = (unsigned int)Descriptors; + + MmLockUnlockBufferPages( WG, 0x8, 0); + MmLockUnlockBufferPages( DA, 256, 0); + + unsigned int realDA = MmGetPhysicalAddress(DA); + + unsigned char lCount = Count; + + GetDescr[0] |= (((unsigned int) DescrType) << 24 ); + GetDescr[0] |= (((unsigned int) Index ) << 16 ); + + s_Transferdescriptor *TD; + + TD = (s_Transferdescriptor *)(((unsigned int *)ED) + 20); + TDA = EDA + 80; + + unsigned int realTDA = MmGetPhysicalAddress( (unsigned int)TDA ); + + TD[0].Format = 0xE20050CA; // Get Descriptor + TD[0].Buffer = MmGetPhysicalAddress(WG); + TD[0].NextTD = realTDA + 16; //TDA + 16; + TD[0].BufferEnd = MmGetPhysicalAddress(WG+7); + TD[1].Format = 0xE31450CB; // Receive Start of Descriptor + TD[1].Buffer = realDA; //DA; + TD[1].NextTD = realTDA+32; //TDA+32; + TD[1].BufferEnd = realDA + 7; //DA + 7; + + //------------------------------------------------------------- + + TD[2].Format = 0xE21450CC; // Receive Rest of Descriptor + TD[2].Buffer = realDA + 8;//DA + 8; + TD[2].NextTD = realTDA + 48; //TDA + 48; + TD[2].BufferEnd = 0; + TD[3].Format = 0xE30050CD; // Queue END + TD[3].Buffer = 0; + TD[3].NextTD = 0; + TD[3].BufferEnd = 0; + + GetDescr[1] = ((unsigned int) lCount) << 16 ; + ED[1].Headptr = realTDA; //TDA; + ED[1].Tailptr = realTDA + 32; //TDA + 32; + ED[1].Format &= 0xFFFFFF00; + ED[1].Format += Addr; + + if( DescrType == 3 ) + GetDescr[1] |= 0x0409; + TD[1].BufferEnd = realDA + lCount - 1; // DA + lCount - 1; + + // set CLF + ohci->regs->cmdstatus |= 2; // CommandStatus + + ohci->regs->control = 0x90; // set CLE + + ohci->regs->intrstatus = ohci->regs->intrstatus; // clear all Interruptflags + +#ifdef USB_DEBUG + // wait for execution + dbg("waiting for execution\n"); +#endif //USB_DEBUG + do + { + + }while( (ohci->regs->intrstatus & 2)== 0 ); + + Sleep(10); + + // ERRORS? + //ohci_hcca *hcca = (ohci_hcca*)ohci->regs->hcca; // HCCA + ohci_hcca *hcca = (ohci_hcca*)ohci->hcca; + hcca->done_head &= 0xfffffffe; // DoneHead in HCCA + + if( (hcca->done_head>>28) !=0 ) + { +#ifdef USB_DEBUG + dbg("\nError Occured\n"); +#endif //USB_DEBUG + return 1; + } + + //------------------------------------------------------------------ + + ED[1].Headptr = realTDA + 48; //TDA + 48; + ED[1].Tailptr = realTDA + 64; //TDA + 64; + + if( (DescrType==3) && (lCount < Descriptors[0]) && 0) + { + // set CLF + ohci->regs->cmdstatus |= 2; // CommandStatus + + ohci->regs->control = 0x90; // set CLE + + ohci->regs->intrstatus = ohci->regs->intrstatus; // clear all Interruptflags + +#ifdef USB_DEBUG + // wait for execution + dbg("waiting for execution"); +#endif //USB_DEBUG + do + { + + }while( (ohci->regs->intrstatus & 2)== 0 ); + + Sleep(10); + + // ERRORS? + //ohci_hcca *hcca = (ohci_hcca*)ohci->regs->hcca; // HCCA + ohci_hcca *hcca = (ohci_hcca*)ohci->hcca; + hcca->done_head &= 0xfffffffe; // DoneHead in HCCA + + if( (hcca->done_head>>28) !=0 ) + return 1; + } + + if( DescrType==2) + { + if( Descriptors[2] < lCount) lCount = Descriptors[2]; + } + else + { + if( Descriptors[0] < lCount) lCount = Descriptors[0]; + } + + /* + sprintf( buf, "Descriptors:\n"); dbg(buf); + for(int i=0; iregs->revision); dbg(buf); + sprintf( buf, " control 0x%08x\n",ohci->regs->control); dbg(buf); + sprintf( buf, " cmdstatus 0x%08x\n",ohci->regs->cmdstatus); dbg(buf); + sprintf( buf, " intrstatus 0x%08x\n",ohci->regs->intrstatus); dbg(buf); + sprintf( buf, " intrenable 0x%08x\n",ohci->regs->intrenable); dbg(buf); + sprintf( buf, " intrdisable 0x%08x\n",ohci->regs->intrdisable); dbg(buf); + sprintf( buf, " ed_periodcurrent 0x%08x\n",ohci->regs->ed_periodcurrent); dbg(buf); + sprintf( buf, " ed_controlhead 0x%08x\n",ohci->regs->ed_controlhead); dbg(buf); + sprintf( buf, " ed_controlcurrent 0x%08x\n",ohci->regs->ed_controlcurrent); dbg(buf); + sprintf( buf, " ed_bulkhead 0x%08x\n",ohci->regs->ed_bulkhead); dbg(buf); + sprintf( buf, " ed_bulkcurrent 0x%08x\n",ohci->regs->ed_bulkcurrent); dbg(buf); + sprintf( buf, " donehead 0x%08x\n",ohci->regs->donehead); dbg(buf); + sprintf( buf, " fminterval 0x%08x\n",ohci->regs->fminterval); dbg(buf); + sprintf( buf, " fmremaining 0x%08x\n",ohci->regs->fmremaining); dbg(buf); + sprintf( buf, " periodicstart 0x%08x\n",ohci->regs->periodicstart); dbg(buf); + sprintf( buf, " lsthresh 0x%08x\n",ohci->regs->lsthresh); dbg(buf); + sprintf( buf, " ohci_roothub_regs.a 0x%08x\n",ohci->regs->roothub.a); dbg(buf); + sprintf( buf, " ohci_roothub_regs.b 0x%08x\n",ohci->regs->roothub.b); dbg(buf); + sprintf( buf, " ohci_roothub_regs.status 0x%08x\n",ohci->regs->roothub.status); dbg(buf); + + sprintf( buf, " ohci_roothub_regs.portstatus[0] 0x%08x\n",ohci->regs->roothub.portstatus[0]); dbg(buf); + sprintf( buf, " ohci_roothub_regs.portstatus[1] 0x%08x\n",ohci->regs->roothub.portstatus[1]); dbg(buf); + sprintf( buf, " ohci_roothub_regs.portstatus[2] 0x%08x\n",ohci->regs->roothub.portstatus[2]); dbg(buf); + sprintf( buf, " ohci_roothub_regs.portstatus[3] 0x%08x\n",ohci->regs->roothub.portstatus[3]); dbg(buf); +#endif //USB_DEBUG + +}// End of DebugFile(..) + +void DebugDescriptor( s_USB_Devicedescriptor * pDes ) +{ +#ifdef USB_DEBUG + sprintf(buf, "\n*Descriptor*\n"); dbg(buf); + + sprintf(buf, "Descriptor.Length: 0x%x\n", pDes->Length ); dbg(buf); + sprintf(buf, "Descriptor.DescriptorType: 0x%02X\n", pDes->DescriptorType ); dbg(buf); + sprintf(buf, "Descriptor.USB: 0x%04X\n", pDes->USB ); dbg(buf); + sprintf(buf, "Descriptor.DeviceClass: 0x%04X\n", pDes->DeviceClass ); dbg(buf); + sprintf(buf, "Descriptor.DeviceSubClass: 0x%04X\n", pDes->DeviceSubClass ); dbg(buf); + sprintf(buf, "Descriptor.DeviceProtocol: 0x%04X\n", pDes->DeviceProtocol ); dbg(buf); + sprintf(buf, "Descriptor.MaxPacketSize: 0x%04X\n", pDes->MaxPacketSize ); dbg(buf); + + sprintf(buf, "Descriptor.Vendor: 0x%04X\n", pDes->Vendor ); dbg(buf); + sprintf(buf, "Descriptor.ProductID: 0x%04X\n", pDes->ProductID ); dbg(buf); + sprintf(buf, "Descriptor.Device: 0x%04X\n", pDes->Device); dbg(buf); + + sprintf(buf, "Descriptor.Manufacturer: 0x%02X\n", pDes->Manufacturer ); dbg(buf); + sprintf(buf, "Descriptor.ProductIndex: 0x%02X\n", pDes->ProductIndex ); dbg(buf); + sprintf(buf, "Descriptor.SerialNumber: 0x%02X\n", pDes->SerialNumber ); dbg(buf); + sprintf(buf, "Descriptor.ConfigNumber: 0x%02X\n", pDes->ConfigNumber ); dbg(buf); +#endif //USB_DEBUG + +}// End DebugDescriptor(..) + +void DebugConfigDescriptor( s_USB_Configurationdescriptor * pDes ) +{ +#ifdef USB_DEBUG + sprintf(buf, "\n+Configuration Descriptor+\n"); dbg(buf); + + sprintf(buf, "ConfDesc.Length: 0x%02X\n", pDes->Length ); dbg(buf); + sprintf(buf, "ConfDescDescriptorType: 0x%02X\n", pDes->DescriptorType ); dbg(buf); + sprintf(buf, "ConfDesc.TotalLength: 0x%04X\n", pDes->TotalLength ); dbg(buf); + sprintf(buf, "ConfDesc.NumberofInterfaces: 0x%02X\n", pDes->NumberofInterfaces ); dbg(buf); + + sprintf(buf, "ConfDesc.ConfigValue: 0x%02X\n", pDes->ConfigValue ); dbg(buf); + sprintf(buf, "ConfDesc.Configuration: 0x%02X\n", pDes->Configuration ); dbg(buf); + sprintf(buf, "ConfDesc.Attributes: 0x%02X\n", pDes->Attributes ); dbg(buf); + sprintf(buf, "ConfDesc.MaxPower: 0x%02X\n", pDes->MaxPower ); dbg(buf); +#endif //USB_DEBUG + +}// End DebugConfigDescriptor(..) + +void DebugIntefaceDescriptor( s_USB_Interfacedescriptor * pDes ) +{ +#ifdef USB_DEBUG + sprintf(buf, "\n#Interface Descriptor#\n"); dbg(buf); + + sprintf(buf, "InterDesc.Length: 0x%02X\n", pDes->Length ); dbg(buf); + sprintf(buf, "InterDesc.DescriptorType: 0x%02X\n", pDes->DescriptorType ); dbg(buf); + sprintf(buf, "InterDesc.Interfacenumber: 0x%02X\n", pDes->Interfacenumber ); dbg(buf); + sprintf(buf, "InterDesc.AlternateSetting: 0x%02X\n",pDes->AlternateSetting ); dbg(buf); + sprintf(buf, "InterDesc.NumberofEndpoints: 0x%02X\n", pDes->NumberofEndpoints );dbg(buf); + sprintf(buf, "InterDesc.InterfaceClass: 0x%02X\n", pDes->InterfaceClass ); dbg(buf); + sprintf(buf, "InterDesc.InterfaceSubClass: 0x%02X\n", pDes->InterfaceSubClass );dbg(buf); + sprintf(buf, "InterDesc.InterfaceProtocol: 0x%02X\n",pDes->InterfaceProtocol ); dbg(buf); + sprintf(buf, "InterDesc.InterfaceIndex: 0x%02X\n", pDes->InterfaceIndex ); dbg(buf); +#endif //USB_DEBUG + +}// End DebugInterfaceDescriptor(..) + +void DebugEndPointDescriptor( s_USB_Endpointdescriptor * pDes ) +{ +#ifdef USB_DEBUG + sprintf(buf, "\n#EndPointDescriptor Descriptor#\n"); dbg(buf); + + + sprintf(buf, "EndPointDes.Length: 0x%02X\n", pDes->Length ); dbg(buf); + sprintf(buf, "EndPointDes.DescriptorType: 0x%02X\n", pDes->DescriptorType ); dbg(buf); + sprintf(buf, "EndPointDes.EndpointAddress: 0x%02X\n", pDes->EndpointAddress ); dbg(buf); + sprintf(buf, "EndPointDes.Attributes: 0x%02X\n",pDes->Attributes ); dbg(buf); + sprintf(buf, "EndPointDes.MaxPacketSize: 0x%02X\n", pDes->MaxPacketSize ); dbg(buf); + sprintf(buf, "EndPointDes.Interval: 0x%02X\n", pDes->Interval ); dbg(buf); +#endif //USB_DEBUG + +}// End of DebugEndPointDescriptor(..) diff --git a/src/libXFX/usb/ohci.h b/src/libXFX/usb/ohci.h new file mode 100644 index 0000000..ccf5291 --- /dev/null +++ b/src/libXFX/usb/ohci.h @@ -0,0 +1,240 @@ +/******************************************************************************/ +/* */ +/* File: ohci.h */ +/* */ +/* Details: Original File & Design: Thomas Frei */ +/* (modifications for xbox openxdk by bkenwright) */ +/* (bkenwright@xbdev.net) www.xbdev.net */ +/* */ +/******************************************************************************/ + +#pragma once + +#include "misc.h" // We only need this here, for the definitions of __u8, __u32 etc +// to be added in later (example): + + +// Example sippet of possible later improvment on structure aligment in vs +// __declspec(align(32)) struct Str1 +// { +// int a, b, c, d, e; +// }; + +/* +typedef unsigned char __u8; +typedef char __s8; +typedef unsigned short __u16; +typedef short __s16; +typedef unsigned long __u32; +typedef int __s32; + +#define NULL 0 +*/ + + + +#define SIZEOF_HCCA 0x100 + + + +/* + * The HCCA (Host Controller Communications Area) is a 256 byte + * structure defined in the OHCI spec. that the host controller is + * told the base address of. It must be 256-byte aligned. + */ + +#define NUM_INTS 32 /* part of the OHCI standard */ + + + +#pragma pack( push, 1 ) +struct ohci_hcca +{ + __u32 int_table[NUM_INTS]; /* Interrupt ED table */ + __u16 frame_no; /* current frame number */ + __u16 pad1; /* set to 0 on each frame_no change */ + __u32 done_head; /* info returned for an interrupt */ + __u8 reserved_for_hc[116]; +}; +#pragma pack( pop ) +typedef struct ohci_hcca ohci_hcca_t; + + +/* + * Maximum number of root hub ports. + */ + +#define MAX_ROOT_PORTS 15 + + +#pragma pack(1) +volatile struct ohci_regs +{ + /* control and status registers */ + __u32 revision; + __u32 control; + __u32 cmdstatus; + __u32 intrstatus; + __u32 intrenable; + __u32 intrdisable; + /* memory pointers */ + __u32 hcca; + __u32 ed_periodcurrent; + __u32 ed_controlhead; + __u32 ed_controlcurrent; + __u32 ed_bulkhead; + __u32 ed_bulkcurrent; + __u32 donehead; + /* frame counters */ + __u32 fminterval; + __u32 fmremaining; + __u32 fmnumber; + __u32 periodicstart; + __u32 lsthresh; + /* Root hub ports */ + volatile struct ohci_roothub_regs + { + __u32 a; + __u32 b; + __u32 status; + __u32 portstatus[MAX_ROOT_PORTS]; + } roothub; +}; +#pragma pack() +typedef struct ohci_regs ohci_regs_t; + + + + +#pragma pack(1) +typedef struct ohci +{ + volatile struct ohci_hcca *hcca; /* hcca */ + + volatile struct ohci_regs * regs; /* OHCI controller's memory */ + +} ohci_t; +#pragma pack() + + +/******************************************************************************/ + + +#define SKIP 0x4000L +#define OUTV 0x0800L +#define INV 0x1000L +#define AUTOIO 0x1800L +#define LOWS 0x2000L + + + +//#pragma block (push,1) +#pragma pack(1) +typedef struct { +__u32 Format; +__u32 Tailptr; +__u32 Headptr; +__u32 NextED; +} s_Endpointdescripor; +#pragma pack() + +#pragma pack(1) +typedef struct { +__u32 Format; +__u32 Buffer; +__u32 NextTD; +__u32 BufferEnd; +} s_Transferdescriptor; +#pragma pack() + +#pragma pack(1) +typedef struct { +__u8 Length; +__u8 DescriptorType; +__u16 USB; +__u8 DeviceClass; +__u8 DeviceSubClass; +__u8 DeviceProtocol; +__u8 MaxPacketSize; +__u16 Vendor; +__u16 ProductID; +__u16 Device; +__u8 Manufacturer; +__u8 ProductIndex; +__u8 SerialNumber; +__u8 ConfigNumber; +} s_USB_Devicedescriptor; +#pragma pack() + +#pragma pack(1) +typedef struct { +__u8 Length; +__u8 DescriptorType; +__u16 TotalLength; +__u8 NumberofInterfaces; +__u8 ConfigValue; +__u8 Configuration; +__u8 Attributes; +__u8 MaxPower; +} s_USB_Configurationdescriptor; + +typedef struct { +__u8 Length; +__u8 DescriptorType; +__u8 Interfacenumber; +__u8 AlternateSetting; +__u8 NumberofEndpoints; +__u8 InterfaceClass; +__u8 InterfaceSubClass; +__u8 InterfaceProtocol; +__u8 InterfaceIndex; +} s_USB_Interfacedescriptor; + +typedef struct { +__u8 Length; +__u8 DescriptorType; +__u8 EndpointAddress; +__u8 Attributes; +__u16 MaxPacketSize; +__u8 Interval; +} s_USB_Endpointdescriptor; + +typedef struct { +__u8 Length; +__u8 DescriptorType; +__u16 *LANGID; +} s_USB_Languagedescriptor; + +typedef struct { +__u8 Length; +__u8 DescriptorType; +__u8 *String; +} s_USB_Stringdescriptor; +//#pragma block (pop) +#pragma pack() + + +/******************************************************************************/ + +// Main Functions +int FindOHC(ohci_t * ohci, void *regbase); +int FindDev(ohci_t * ohci, int Port); + + +int ResetPort(ohci_t * ohci, int Port); +int SetAddres(ohci_t * ohci, int Port, __u8 AddrNew); +int SetConfigur(ohci_t * ohci, __u8 Addr, __u8 Config); +int GetDesc(ohci_t * ohci, __u8 Addr, __u8 DescrType, __u8 Index, __u8 Count, __u8 *DBuffer); + + + +// Debug Functions +void DebugFile(ohci_t * ohci); +void DebugDescriptor( s_USB_Devicedescriptor * pDes ); +void DebugConfigDescriptor( s_USB_Configurationdescriptor * pDes ); +void DebugInterfaceDescriptor( s_USB_Interfacedescriptor * pDes ); +void DebugEndPointDescriptor( s_USB_Endpointdescriptor * pDes ); + + + + diff --git a/src/libXFX/usb/pad.cpp b/src/libXFX/usb/pad.cpp new file mode 100644 index 0000000..ba3007e --- /dev/null +++ b/src/libXFX/usb/pad.cpp @@ -0,0 +1,404 @@ +/******************************************************************************/ +/* */ +/* File: pad.cpp */ +/* bkenwright@xbdev.net - www.xbdev.net */ +/* */ +/******************************************************************************/ +#include "pad.h" +#include "misc.h" // memcpy(..), KernelCalls etc + +#include + +// These couple of globals are defined in ohci.cpp - there our small group +// of descriptors which we use to communcate with the ohci-usb + +extern unsigned int eds[176 + 0x100 + 0x100]; // ohci.cpp +extern unsigned int EDA; +extern s_Endpointdescripor * ED; + +/******************************************************************************/ +struct ohci_ed_t_ +{ + unsigned int ed_flags; +#define OHCI_ED_GET_FA(s) ((s) & 0x7f) +#define OHCI_ED_ADDRMASK 0x0000007f +#define OHCI_ED_SET_FA(s) (s) +#define OHCI_ED_GET_EN(s) (((s) >> 7) & 0xf) +#define OHCI_ED_SET_EN(s) ((s) << 7) +#define OHCI_ED_DIR_MASK 0x00001800 +#define OHCI_ED_DIR_TD 0x00000000 +#define OHCI_ED_DIR_OUT 0x00000800 +#define OHCI_ED_DIR_IN 0x00001000 +#define OHCI_ED_SPEED 0x00002000 +#define OHCI_ED_SKIP 0x00004000 +#define OHCI_ED_FORMAT_GEN 0x00000000 +#define OHCI_ED_FORMAT_ISO 0x00008000 +#define OHCI_ED_GET_MAXP(s) (((s) >> 16) & 0x07ff) +#define OHCI_ED_SET_MAXP(s) ((s) << 16) +#define OHCI_ED_MAXPMASK (0x7ff << 16) + unsigned int ed_tailp; + unsigned int ed_headp; +#define OHCI_HALTED 0x00000001 +#define OHCI_TOGGLECARRY 0x00000002 +#define OHCI_HEADMASK 0xfffffffc + unsigned int ed_nexted; +}; + +struct ohci_td_t_ +{ + unsigned int td_flags; +#define OHCI_TD_R 0x00040000 /* Buffer Rounding */ +#define OHCI_TD_DP_MASK 0x00180000 /* Direction / PID */ +#define OHCI_TD_SETUP 0x00000000 +#define OHCI_TD_OUT 0x00080000 +#define OHCI_TD_IN 0x00100000 +#define OHCI_TD_GET_DI(x) (((x) >> 21) & 7) /* Delay Interrupt */ +#define OHCI_TD_SET_DI(x) ((x) << 21) +#define OHCI_TD_NOINTR 0x00e00000 +#define OHCI_TD_INTR_MASK 0x00e00000 +#define OHCI_TD_TOGGLE_CARRY 0x00000000 +#define OHCI_TD_TOGGLE_0 0x02000000 +#define OHCI_TD_TOGGLE_1 0x03000000 +#define OHCI_TD_TOGGLE_MASK 0x03000000 +#define OHCI_TD_GET_EC(x) (((x) >> 26) & 3) /* Error Count */ +#define OHCI_TD_GET_CC(x) ((x) >> 28) /* Condition Code */ +#define OHCI_TD_NOCC 0xf0000000 + unsigned int td_cbp; /* Current Buffer Pointer */ + unsigned int td_nexttd; /* Next TD */ + unsigned int td_be; /* Buffer End */ +} ; + +/******************************************************************************/ +void usb_bulk_msg( usbd_device * dev, int size, void * data ) +{ + ohci_t * ohci = dev->p_ohci; + + unsigned char buffer[256] = {0}; + + memcpy(buffer, data, size); + + MmLockUnlockBufferPages((unsigned int)buffer, 0x8, 0); + unsigned int real_pcmd = MmGetPhysicalAddress((unsigned int)buffer); + + unsigned char Descriptors[256] = {0}; + MmLockUnlockBufferPages((unsigned int)Descriptors, 256, 0); + unsigned int real_pDescriptors = MmGetPhysicalAddress((unsigned int)Descriptors); + + s_Transferdescriptor *TD; + TD = (s_Transferdescriptor *)(((unsigned int *)ED) + 20); + unsigned int TDA = EDA + 80; + unsigned int realTDA = MmGetPhysicalAddress((unsigned int)TDA); + +//////////////////////////////////////////////////////////////////////// +// --Transfer Descriptor TD-- +// Offset Field Size Value Desc +// 0 4 0..17 reserved +// +// 18 R - bufferRounding +// 19..20 DP - Direction/PID +// 00b SETUP +// 01b OUT +// 10b IN +// 11b reserved +// 21..23 DI - DelayInterrupt +// 24..25 T - DataToggle +// 26..27 EC - ErrorCount +// 28..31 CC - ConditionCode +// 4 4 CurrentBufferPoinnter (CBP) +// 8 4 0..3 Zero +// 4..31 Next TD (NextTD) +// 12 4 Buffer End (BE) +// +//(Total Size 16 bytes or 4 dwords) +// +//////////////////////////////////////////////////////////////////////// + + // 0xE20050CA + + unsigned int td_format = 0; + td_format |= OHCI_TD_OUT; // 0x00080000 e.g. 1<<19 + td_format |= OHCI_TD_TOGGLE_0; // 0x02000000 e.g. 2<<24 + /* I've set the data toggle sync here in + * the TD by setting the MSB to 1 of Toggle Bits + * so the ED toggle bit isn't used. + */ + td_format |= OHCI_TD_NOCC; // 0xf0000000 + /* Set our ConditionCode to no errors */ + TD[0].Format = td_format; + //TD[0].Format = 0xE20050CA; // Our Bulk Msg! + TD[0].Buffer = real_pcmd; + TD[0].NextTD = realTDA + 16; + TD[0].BufferEnd = real_pcmd + size - 1; + + td_format |= 0; + td_format |= OHCI_TD_OUT; + td_format |= OHCI_TD_TOGGLE_1; + td_format |= OHCI_TD_NOCC; + + TD[1].Format = td_format; // Receive Start of Descriptor + TD[1].Buffer = real_pDescriptors; + TD[1].NextTD = realTDA + 32; + TD[1].BufferEnd = real_pDescriptors + 7; + + td_format |= 0; + td_format |= OHCI_TD_OUT; + td_format |= OHCI_TD_TOGGLE_0; + td_format |= OHCI_TD_NOCC; + + TD[3].Format = td_format; + //TD[1].Format = 0xE30050CB; // Queue END + TD[3].Buffer = 0; + TD[3].NextTD = 0; + TD[3].BufferEnd = 0; + + //////////////////////////////////////////////////////////////////////// +// --EndPoint Descriptor ED-- +// Offset Field Size Value Desc +// 0 4 Bitmap +// 0..6 FA - Function Address +// +// 7..10 EN - EndpointNumber +// 11..12 D - Direction +// 00b GetDir From TD +// 01b OUT +// 10b IN +// 11b GetDir From TD +// 13 S - Speed (Full Speed=0) +// 14 K - sKip +// 15 F - Format +// 0 - Control/Bulk/Int******** +// 1 - Isochronous +// 16..26 MPS MaximumPacketSize +// 27..31 reserved +// 4 4 Bitmap +// 0..3 Zero Aligment +// 4..31 TD Queue Tail Pointer (TailP) +// 8 4 Bitmap +// 0 H - Halted +// 1 C - toggleCarry +// 2..3 reserved +// 4..31 TD Queue Head Pointer (HeadP) +// 12 4 Bitmap +// 0..3 Zero Aligment +// 4..31 Next Endpoint Descriptor (NextED) +// +//(Total Size 16 bytes or 4 dwords) +// +//////////////////////////////////////////////////////////////////////// + + //unsigned int format = 0x00401801; // 2(OUT) or 82(IN)? + // + unsigned int ed_format = 0x00400000; + ed_format |= OHCI_ED_DIR_OUT; // 0x00000800 + ed_format |= OHCI_ED_DIR_IN; // 0x00001000 + + unsigned char Addr = dev->address; + unsigned char EndAddr = 0x2; + + ED[0].Format = ed_format; + + ED[0].Headptr = realTDA; + ED[0].Tailptr = realTDA + 16; + ED[0].Format &= 0xFFFFFF00; // Clear old address + ED[0].Format += Addr; // Insert new address + + ED[0].Format |= (EndAddr << 7 ); + + #define OHCI_CTRL_CLE (1 << 4) /* control list enable */ + #define OHCI_CTRL_BLE (1 << 5) /* bulk list enable */ + #define OHCI_CTRL_HCFS (3 << 6) /* host controller functional state */ + + #define OHCI_CLF (1 << 1) /* control list filled */ + #define OHCI_BLF (1 << 2) /* bulk list filled */ + + // have to enable bulk tx + //ohci->regs->cmdstatus |= 2; // CommandStatus + //ohci->regs->control = 0x90; // set CLE + + ohci->regs->cmdstatus |= (1<<2); // BLF + ohci->regs->control = OHCI_CTRL_BLE | (2<<6); // BLF + ohci->regs->intrstatus = ohci->regs->intrstatus; // clear all Interruptflags + + // wait for execution + //dbg("waiting for execution\n"); + do + { + + }while( (ohci->regs->intrstatus & 2)== 0 ); + + Sleep(10); + + // ERRORS? + ohci_hcca *hcca = (ohci_hcca*)ohci->hcca; // HCCA + hcca->done_head &= 0xfffffffe; // DoneHead in HCCA + + if( (hcca->done_head>>28) !=0 ) + { +#ifdef USB_DEBUG + dbg("\nError Occured\n"); +#endif //USB_DEBUG + return; + } + + //------------------------------------------------------------------ + + // Where all done and finished now, so we set our ED's to our + // Queue END where they behave and wait. + ED[0].Headptr = realTDA + 48; + ED[0].Tailptr = realTDA + 64; + +#ifdef USB_DEBUG + unsigned int ErrorCount = OHCI_TD_GET_EC( TD[0].Format ); + unsigned int ConditionCode = OHCI_TD_GET_CC( TD[0].Format ); + + sprintf(buf, "ErrorCount: %d\n", ErrorCount); dbg(buf); + sprintf(buf, "ConditionCode: %d\n", ConditionCode); dbg(buf); +#endif //USB_DEBUG + + Sleep(10); + + //memcpy( data, Descriptors, size); + + ED[0].Format = 0x00004000; +} + +void once() +{ +} + +unsigned char xbuffer[256] = {0}; + +void usb_bulk_msg_in( usbd_device * dev, int size, void * data ) +{ + ohci_t * ohci = dev->p_ohci; + + memset(xbuffer, 0, 256 ); + + MmLockUnlockBufferPages( (unsigned int)xbuffer, 0x250, 0); + unsigned int real_pbuffer = MmGetPhysicalAddress( (unsigned int)xbuffer); + + s_Transferdescriptor *TD; + TD = (s_Transferdescriptor *)(((unsigned int *)ED) + 20); + unsigned int TDA = EDA + 80; + unsigned int realTDA = MmGetPhysicalAddress( (unsigned int)TDA ); + + // 0xE20050CA + + unsigned int td_format = 0; + td_format |= OHCI_TD_IN; // 0x00100000 e.g. 1<<19 + td_format |= OHCI_TD_TOGGLE_0; // 0x02000000 e.g. 2<<24 + /* I've set the data toggle sync here in + * the TD by setting the MSB to 1 of Toggle Bits + * so the ED toggle bit isn't used. + */ + td_format |= OHCI_TD_NOCC; // 0xf0000000 + /* Set our ConditionCode to no errors */ + TD[0].Format = td_format; // Our Bulk Msg! + TD[0].Buffer = real_pbuffer; + TD[0].NextTD = realTDA + 16; + TD[0].BufferEnd = real_pbuffer + size - 1; + + /* + td_format |= 0; + td_format |= OHCI_TD_IN; + td_format |= OHCI_TD_TOGGLE_1; + td_format |= OHCI_TD_NOCC; + TD[1].Format = td_format; // Receive Start of Descriptor + TD[1].Buffer = real_pbuffer; + TD[1].NextTD = realTDA + 32; + TD[1].BufferEnd = real_pbuffer + size - 1; +*/ + + td_format |= 0; + td_format |= OHCI_TD_IN; + td_format |= OHCI_TD_TOGGLE_1; + td_format |= OHCI_TD_NOCC; + TD[1].Format = td_format; // Queue END + TD[1].Buffer = 0; + TD[1].NextTD = 0; + TD[1].BufferEnd = 0; + + unsigned int ed_format = 0x00400000; + ed_format |= OHCI_ED_DIR_OUT; // 0x00000800 + ed_format |= OHCI_ED_DIR_IN; // 0x00001000 + + unsigned char Addr = dev->address; + unsigned char EndAddr = 0x2; + + ED[0].Format = ed_format; + + ED[0].Headptr = realTDA; + ED[0].Tailptr = realTDA + 16; + ED[0].Format &= 0xFFFFFF00; // Clear old address + ED[0].Format += Addr; // Insert new address + + ED[0].Format |= (EndAddr << 7 ); + + #define OHCI_CTRL_CLE (1 << 4) /* control list enable */ + #define OHCI_CTRL_BLE (1 << 5) /* bulk list enable */ + #define OHCI_CTRL_HCFS (3 << 6) /* host controller functional state */ + + #define OHCI_CLF (1 << 1) /* control list filled */ + #define OHCI_BLF (1 << 2) /* bulk list filled */ + + Sleep(20); + + // have to enable bulk tx + //ohci->regs->cmdstatus |= 2; // CommandStatus + //ohci->regs->control = 0x90; // set CLE + + ohci->regs->cmdstatus |= (1<<2); // BLF + ohci->regs->control = OHCI_CTRL_BLE | (2<<6); // BLF + ohci->regs->intrstatus = ohci->regs->intrstatus; // clear all Interruptflags + + // wait for execution + //dbg("waiting for execution\n"); + do + { + //dbg("waiting for execution-in loop\n"); + + }while( (ohci->regs->intrstatus & 2)== 0 ); + + //dbg("waiting for execution-out loop\n"); + + ohci->regs->intrstatus = ohci->regs->intrstatus; + + Sleep(30); + + // ERRORS? + ohci_hcca *hcca = (ohci_hcca*)ohci->hcca; // HCCA + hcca->done_head &= 0xfffffffe; // DoneHead in HCCA + + if( (hcca->done_head>>28) !=0 ) + { +#ifdef USB_DEBUG + dbg("\nError Occured\n"); +#endif //USB_DEBUG + return; + } + + //------------------------------------------------------------------ + +#ifdef USB_DEBUG + // Where all done and finished now, so we set our ED's to our + // Queue END where they behave and wait. + ED[0].Headptr = realTDA + 48; + ED[0].Tailptr = realTDA + 64; + + + unsigned int ErrorCount = OHCI_TD_GET_EC( TD[0].Format ); + unsigned int ConditionCode = OHCI_TD_GET_CC( TD[0].Format ); + + if( ErrorCount || ConditionCode ) + { + sprintf(buf, "ErrorCount: %d\n", ErrorCount); dbg(buf); + sprintf(buf, "ConditionCode: %d\n", ConditionCode); dbg(buf); + } +#endif //USB_DEBUG + + //Sleep(50); + + memcpy( data, xbuffer, size); + + //ED[0].Format = 0x00004000; +} diff --git a/src/libXFX/usb/pad.h b/src/libXFX/usb/pad.h new file mode 100644 index 0000000..ee9a9ea --- /dev/null +++ b/src/libXFX/usb/pad.h @@ -0,0 +1,84 @@ +/******************************************************************************/ +/* */ +/* File: pad.h */ +/* bkenwright@xbdev.net - www.xbdev.net */ +/* */ +/******************************************************************************/ + +/******************************************************************************/ +/* + What on earth! Whats this file for? + Well once we have our usb device address set...for the xbox gamepad :) + This file will do some simple commands...sending bulk test messages + ...an example would be to send a rumble message? + Also probe for some button presses? + + In Development though. +*/ +/******************************************************************************/ + +#pragma once + + +#include "ohci.h" +#include "hub.h" + +/******************************************************************************/ +/* */ +/* stXPAD - Gamepad Data Structure */ +/* This structure will be filled in by our USB Gamepad - its the data that */ +/* is returned to us when we request a gamepad in on the usb bus. */ +/* */ +/******************************************************************************/ + + +#pragma pack(1) // We use this, so our data is packed nice and tight!..no space. +struct stXPAD // Packed to 1 byte alignment. +{ + char reserved1; + unsigned char structsize; + + char pad; /* 1 up 2 down 4 left 8 right */ + char reserved2; + unsigned char keys[6]; /* A B X Y Black White */ + + unsigned char trig_left; + unsigned char trig_right; + short stick_left_x; + short stick_left_y; + short stick_right_x; + short stick_right_y; + + char padding[0x40]; +}; +#pragma pack() + + +/******************************************************************************/ +/* */ +/* stRumbleXPAD */ +/* We will fill this with data later on, that we will pass to the gamepad, */ +/* it will specify the left or right rumble and speed for example */ +/* */ +/******************************************************************************/ + +#pragma pack(1) +struct stRumbleXPAD +{ +}; +#pragma pack() + + + +/******************************************************************************/ +/* */ +/* Functions */ +/* */ +/******************************************************************************/ + + +void usb_bulk_msg( usbd_device * dev, int size, void * data ); // Send data to the USB + +void usb_bulk_msg_in( usbd_device * dev, int size, void * data ); // Get data from the USB + + diff --git a/src/libXFX/usb/xinput.cpp b/src/libXFX/usb/xinput.cpp new file mode 100644 index 0000000..4bada40 --- /dev/null +++ b/src/libXFX/usb/xinput.cpp @@ -0,0 +1,354 @@ +/******************************************************************************/ +/* */ +/* File: xinput.cpp */ +/* Auth: bkenwright@xbdev.net */ +/* Desc: GamePad entry code for use on the xbox. */ +/* */ +/******************************************************************************/ + +/* + How does this code work? What lib's does it need? How would I use it + in my code? + + Well the aim of the gamepad code was to develop an independent set of + code for the openxdk - but because it's lib independent it also works on + the xdk. + + <1> Include our header file, and the other files which do all the work.. + later they'll be put into a library + e.g. #include "xinput/xinput.h" // Gamepad input + + <2> Init our gamepad code + e.g. + stXINPUT xin; + xInitInput(&xin); + You do this ocne at the start of the program, I did it this way as I don't + like globals, so you need to pass it a stuct called stXINPUT which + keeps all our usb/gampad information in. + + <3> Get our gamepad information in our main loop e.g: + stXPAD pad; + xGetPadInput(&pad, &xin); + + <4> When we've all finished, call xReleaseInput(&xin); + + You can also set the rumble effect - still in development + e.g. xSetPadInput(&pad, &xin); +*/ +/******************************************************************************/ + +//#include // sprintf(..) + +//#define USB_DEBUG + +#include "misc.h" +#include "ohci.h" +#include "hub.h" +#include "pad.h" + +#include "xinput.h" + +/******************************************************************************/ +/* */ +/* http://www.beyondlogic.org/usbnutshell/usb5.htm */ +/* */ +/******************************************************************************/ + +extern unsigned char found; // declared at the top of ohci.cpp + +//extern void InitialiseD3D(); +//extern void DisplayText(char * szStr, long xpos=100, long ypos=100 ); +//extern void DataDisplay(void* data); + +/******************************************************************************/ +/* */ +/* OHCI Code */ +/* */ +/* We use our ohci library functions here, from ohci.h/cpp,...to scan for */ +/* devices and changes etc...get how many are plugged in..what type they are */ +/* simple and sweet. */ +/* */ +/******************************************************************************/ +int xInitInput(stXINPUT* p) +{ + //InitialiseD3D(); + + unsigned char Buffer[256]; + + ohci_t * my_ohci = &(p->my_ohci); + + int Ports = FindOHC( my_ohci, (void*)0xfed00000 ); + +#ifdef USB_DEBUG + if( Ports==0 ) dbg("Error no ports found\n"); +#endif //USB_DEBUG + + //for( int i=0; iconfig[0].bConfigurationValue)) +// usb_set_configuration(my_ohci, found, CD[i][j-1].ConfigValue); + //CD[i][j-1].ConfigValue; + + set_control_msg(my_ohci, found, + USB_REQ_SET_CONFIGURATION, 0, CD[i][j-1].ConfigValue, 0, 0, NULL); + }// End for loop j + //} + + //-----------------------work on the hub!-------------------------/ + + // ref: http://fxr.watson.org/fxr/source/dev/usb/uhub.c + /// + // To have the best chance of success we do things in the exact same + // order as Windoze98. This should not be necessary, but some + // devices do not follow the USB specs to the letter. + // + // These are the events on the bus when a hub is attached: + // Get device and config descriptors (see attach code) + // Get hub descriptor (see above) + // For all ports + // turn on power + // wait for power to become stable + // (all below happens in explore code) + // For all ports + // clear C_PORT_CONNECTION + // For all ports + // get port status + // if device connected + // wait 100 ms + // turn on reset + // wait + // clear C_PORT_RESET + // get port status + // proceed with device attachment + /// + +#ifdef USB_DEBUG + dbg("\n\nHUB INTERIGATION AND SETTING UP\n\n"); +#endif //USB_DEBUG + + memset(Buffer, 0, 255); + + //usb_get_device_descriptor(my_ohci, 1, 18, Buffer); + //DebugDescriptor( (s_USB_Devicedescriptor *)Buffer ); + + usbd_device dev; + dev.p_ohci = my_ohci; + dev.address = found; // root hub should be addr 1 + + do_hub_work(&dev); + + // Testing...gamepad 1 is allocated to addr 3 + + //Assumptions - for this small test section...I've assumed taht only + //a single gamepad is plugged in. + +#ifdef USB_DEBUG + dbg("\n\n--gamepad_0---\n\n"); +#endif //USB_DEBUG + + //Getting Descriptor + s_USB_Devicedescriptor devdesc = {0}; + dev.address = 3; + + devrequest req = {0}; + req.requesttype = UT_READ_DEVICE; + req.request = UR_GET_DESCRIPTOR; + req.value = 0; + req.value |= (0x00ff & 0); + req.value |= (0xff00 & (UDESC_DEVICE<<8)); + req.index = 0; + req.length = 18; + + // What is this new function?...why didn't we use the normal + // usd_do_request(..)?....hmm...well it seems that the gamepad + // max packet size is 0x40...and if we use the 0x8 which I've done upto + // now we only get the first 8 bytes of the desciptor...using this slightly + // modified version, we get the full descriptor of our gamepad :) + usbd_do_request_big_packet(&dev, &req, &devdesc); + +#ifdef USB_DEBUG + DebugDescriptor( &devdesc ); +#endif //USB_DEBUG + + Sleep(10); + //------- + // USB_REQ_SET_CONFIGURATION, 0, configuration, 0, 0, NULL); + // Set the config descriptor for gamepad + unsigned short bConfigurationValue = 0x01; + + usbd_device dev_temp; + dev_temp.address = 3; + dev_temp.p_ohci = dev.p_ohci; + + devrequest dr = {0}; + + int index = 0; + + dr.requesttype = UT_WRITE_DEVICE; // 0x80 + dr.request = UR_SET_CONFIG; // 0x09 + dr.value = bConfigurationValue; // 0x01 + dr.index = 0; + dr.length = 0; + + usbd_do_request_big_packet(&dev_temp, &dr, 0 ); + + return 0; +};// End of xInitInput(..) + +devrequest dr = {0}; + +int xGetPadInput(stXPAD * p, stXINPUT * xin, int iWhichPad /*= 0*/) // 0 is default pad +{ + usbd_device dev; + dev.p_ohci = &(xin->my_ohci); + dev.address = 3; // This will choose the first gamepad it finds, only for debug + + stXPAD data_in = {0}; + + // bug + unsigned short bConfigurationValue = 0x01; + + //devrequest dr = {0}; + + dr.requesttype = UT_WRITE_DEVICE; // 0x80 + dr.request = UR_SET_CONFIG; // 0x09 + dr.value = bConfigurationValue; // 0x01 + dr.index = 0; + dr.length = 0; + + // bug + //while(true) + { + //usbd_do_request_big_packet(&dev, &dr, 0 ); + + usb_bulk_msg_in(&dev, 20, &data_in); + memcpy(p, &data_in, 20); + + //DataDisplay( (void*) &data_in ); + + //Sleep(100); + + usbd_do_request_big_packet(&dev, &dr, 0 ); + + // Some error checking to be put here! + //if( data_in.structsize == 0 ) + // break; + } + return 0; // no error checking as of yet +} + +int xSetPadInput(stXPAD * p, stXINPUT * xin, int iWhichPad /*= 0*/) +{ + usbd_device dev; + dev.p_ohci = &(xin->my_ohci); + dev.address = iWhichPad; // This will choose the first gamepad it finds, only for debug + + // Rumbble...lets see if we can make our gamepad rumble :) + + unsigned char data1[6] = {0,6,0,120,0,120}; // rumble data + usb_bulk_msg(&dev, 6, (void*)data1); // simple bulk send function (in pad.c/.h) + + unsigned char data2[6] = {0,6,0,0, 0,0 }; + usb_bulk_msg(&dev, 6, (void*)data2); + + return 0; // no error checking as of yet +} + + +int xReleaseInput(stXINPUT * p) +{ + return 0; // no error checking as of yet +} diff --git a/src/libXFX/usb/xinput.h b/src/libXFX/usb/xinput.h new file mode 100644 index 0000000..2654a91 --- /dev/null +++ b/src/libXFX/usb/xinput.h @@ -0,0 +1,86 @@ +/******************************************************************************/ +/* */ +/* File: xinput.h */ +/* Auth: bkenwright@xbdev.net */ +/* Desc: GamePad entry code for use on the xbox. */ +/* */ +/******************************************************************************/ +/* + This is our xinput header file, this is where all our functions that we'll + use in our game or app for the xbox that 'require' gamepad support will + be put. +*/ +/******************************************************************************/ +/* + How does this code work? What lib's does it need? How would I use it + in my code? + + Well the aim of the gamepad code was to develop an independent set of + code for the openxdk - but because it's lib independent it also works on + the xdk. + + <1> Include our header file, and the other files which do all the work.. + later they'll be put into a library + e.g. #include "xinput/xinput.h" // Gamepad input + + <2> Init our gamepad code + e.g. + stXINPUT xin; + xInitInput(&xin); + You do this ocne at the start of the program, I did it this way as I don't + like globals, so you need to pass it a stuct called stXINPUT which + keeps all our usb/gampad information in. + + <3> Get our gamepad information in our main loop e.g: + stXPAD pad; + xGetPadInput(&pad, &xin); + + <4> When we've all finished, call xReleaseInput(&xin); + + You can also set the rumble effect - still in development + e.g. xSetPadInput(&pad, &xin); +*/ +/******************************************************************************/ + +#pragma once + + + + +#include "ohci.h" +#include "pad.h" // for stXPAD definition + + + +// About this - at the moment it just contains the offset to the ohci memory +// location (e.g. 0xfed00000...but we will also use this to keep track of +// alocated memory - how many gamepads are plugged in...usb dev drivers etc. + +struct stXINPUT +{ + ohci_t my_ohci; +}; + +struct stXPAD; // Defined in xpad.h + + + +/******************************************************************************/ +/* */ +/* Interface Functions */ +/* */ +/******************************************************************************/ + +//<1> Creation +int xInitInput(stXINPUT* p); + +//<2> Probing/ Getting or Setting Gamepad +int xGetPadInput(stXPAD * p, stXINPUT * xin, int iWhichPad = 0); // 0 is default pad +int xSetPadInput(stXPAD * p, stXINPUT * xin, int iWhichPad = 0); + +//<3> Death End +int xReleaseInput(stXINPUT * p); + + + + diff --git a/src/libmscorlib/Array.cpp b/src/libmscorlib/Array.cpp new file mode 100644 index 0000000..7eb38de --- /dev/null +++ b/src/libmscorlib/Array.cpp @@ -0,0 +1,77 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include + +namespace System +{ + template + void Array::Clear(T array[], int index, int length) + { + for(int i = index; i < (index+length); i++) + { + array[i] = null; + } + } + + template + void Array::Copy(T sourceArray[], int sourceIndex, T destinationArray[], int destinationIndex, int length) + { + if((sourceArray == null) || (destinationArray == null)) + throw ArgumentNullException(sourceArray == null ? "sourceArray" : "destinationArray"); + + if(sourceIndex < 0) + throw IndexOutOfRangeException("sourceIndex must be 0 or greater"); + + if(destinationIndex < 0) + throw IndexOutOfRangeException("destinationIndex must be 0 or greater"); + + if(length < 0) + throw IndexOutOfRangeException("length must be 0 or greater"); + + if((sourceIndex + length) > Length(sourceArray)) + throw ArgumentException(); + + if((destinationIndex + length) > Length(destinationArray)) + throw ArgumentException(); + + for(int i = 0; i < length; i++) + { + sourceArray[sourceIndex] = destinationArray[destinationIndex]; + sourceIndex++; + destinationIndex++; + } + } + + template + int Array::Length(T array[]) + { + return (sizeof(array)/sizeof(T)); + } +} diff --git a/src/libmscorlib/BinaryReader.cpp b/src/libmscorlib/BinaryReader.cpp new file mode 100644 index 0000000..09441db --- /dev/null +++ b/src/libmscorlib/BinaryReader.cpp @@ -0,0 +1,255 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include + +namespace System +{ + namespace IO + { + Stream BinaryReader::BaseStream() + { + return m_stream; + } + + BinaryReader::BinaryReader(Stream input) + { + BinaryReader(input, Encoding::UTF8()); + } + + BinaryReader::BinaryReader(Stream input, Encoding encoding) + { + if (!input.CanRead()) + throw ArgumentException("The stream doesn't support reading."); + + m_disposed = false; + m_stream = input; + m_encoding = encoding; + m_decoder = encoding.GetDecoder(); + m_buffer = new byte[32]; + } + + BinaryReader::~BinaryReader() + { + Dispose(false); + } + + void BinaryReader::Close() + { + Dispose(true); + } + + void BinaryReader::Dispose() + { + Dispose(true); + } + + void BinaryReader::Dispose(bool disposing) + { + m_stream.Close(); + + m_disposed = true; + delete m_buffer; + m_encoding = NULL; + m_stream.Close(); + m_stream = Stream::Null; + delete[] m_charBuffer; + } + + void BinaryReader::FillBuffer(int numBytes) + { + if (m_disposed) + throw ObjectDisposedException("BinaryReader", "Cannot read from a closed BinaryReader."); + + int offset = 0; + int num2 = 0; + if (numBytes == 1) + { + num2 = m_stream.ReadByte(); + if (num2 == -1) + { + throw EndOfStreamException("Attempted to read beyond End OF File."); + } + m_buffer[0] = (byte)num2; + } + else + { + do + { + num2 = m_stream.Read(m_buffer, offset, numBytes - offset); + if (num2 == 0) + { + throw EndOfStreamException("Attempted to read beyond End OF File."); + } + offset += num2; + } + while (offset < numBytes); + } + } + + int BinaryReader::InternalReadChars(char buffer[], int index, int count) + { + + } + + int BinaryReader::InternalReadOneChar() + { + Int64 position; + int num = 0; + int byteCount = 0; + position = position = 0LL; + if (m_stream.CanSeek()) + { + position = m_stream.Position; + } + if (m_charBytes == null) + { + m_charBytes = new byte[0x80]; + } + if (m_singleChar == null) + { + m_singleChar = new char[1]; + } + while (num == 0) + { + byteCount = m_2BytesPerChar ? 2 : 1; + int num4 = m_stream.ReadByte(); + m_charBytes[0] = (byte) num4; + if (num4 == -1) + { + byteCount = 0; + } + if (byteCount == 2) + { + num4 = m_stream.ReadByte(); + m_charBytes[1] = (byte) num4; + if (num4 == -1) + { + byteCount = 1; + } + } + if (byteCount == 0) + { + return -1; + } + try + { + num = m_decoder.GetChars(m_charBytes, 0, byteCount, m_singleChar, 0); + continue; + } + catch (Exception) + { + if (m_stream.CanSeek()) + { + m_stream.Seek(position - m_stream.Position, SeekOrigin::Current); + } + throw; + } + } + if (num == 0) + { + return -1; + } + return m_singleChar[0]; + } + + int BinaryReader::PeekChar() + { + if (!m_stream.CanSeek()) + { + return -1; + } + long position = m_stream.Position; + int num2 = this->Read(); + m_stream.Position = position; + return num2; + } + + int BinaryReader::Read() + { + return InternalReadOneChar(); + } + + int BinaryReader::Read(byte buffer[], int index, int count) + { + if(&m_stream == null) + { + if (m_disposed) + throw ObjectDisposedException("BinaryReader", "Cannot read from a closed BinaryReader."); + + throw IOException("Stream is invalid"); + } + + if (buffer == null) + throw ArgumentNullException("buffer is null"); + + if (index < 0) + throw ArgumentOutOfRangeException("index is less than 0"); + + if (count < 0) + throw ArgumentOutOfRangeException("count is less than 0"); + + if (Array::Length(buffer) < index + count) + throw ArgumentException("buffer is too small"); + + int bytes_read = m_stream.Read(buffer, index, count); + + return(bytes_read); + } + + int BinaryReader::Read(char buffer[], int index, int count) + { + if (m_disposed) + throw ObjectDisposedException("BinaryReader", "Cannot read from a closed BinaryReader."); + + if (buffer == null) + throw ArgumentNullException("buffer is null"); + + if (index < 0) + throw ArgumentOutOfRangeException("index is less than 0"); + + if (count < 0) + throw ArgumentOutOfRangeException("count is less than 0"); + + if ((Array::Length(buffer) - index) < count) + throw ArgumentException("buffer is too small"); + + return InternalReadChars(buffer, index, count); + } + + float BinaryReader::ReadSingle() + { + FillBuffer(4); + uint num = (uint) (((m_buffer[0] | (m_buffer[1] << 8)) | (m_buffer[2] << 0x10)) | (m_buffer[3] << 0x18)); + return *(((float*) &num)); + } + } +} diff --git a/src/libmscorlib/BitConverter.cpp b/src/libmscorlib/BitConverter.cpp new file mode 100644 index 0000000..7028e27 --- /dev/null +++ b/src/libmscorlib/BitConverter.cpp @@ -0,0 +1,166 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include + +namespace System +{ + bool BitConverter::AmIBigOrLittleEndian() + { + // binary representations of 1.0: + // big endian: 3f f0 00 00 00 00 00 00 + // little endian: 00 00 00 00 00 00 f0 3f + // arm fpa little endian: 00 00 f0 3f 00 00 00 00 + double d = 1.0; + byte *b = (byte*)&d; + return (b [0] == 0); + } + + bool BitConverter::SwappedWordsInDouble() + { + // binary representations of 1.0: + // big endian: 3f f0 00 00 00 00 00 00 + // little endian: 00 00 00 00 00 00 f0 3f + // arm fpa little endian: 00 00 f0 3f 00 00 00 00 + double d = 1.0; + byte *b = (byte*)&d; + return b [2] == 0xf0; + } + + void PutBytes(byte *dst, byte src[], int start_index, int count) + { + if (src == null) + throw ArgumentNullException("value"); + + if (start_index < 0 || (start_index > Array::Length(src) - 1)) + throw ArgumentOutOfRangeException("startIndex", "Index was out of range. Must be non-negative and less than the size of the collection."); + + // avoid integer overflow (with large pos/neg start_index values) + if (Array::Length(src) - count < start_index) + throw ArgumentException("Destination array is not long enough to copy all the items in the collection. Check array index and length."); + + for (int i = 0; i < count; i++) + dst[i] = src[i + start_index]; + } + + const bool BitConverter::IsLittleEndian = BitConverter::AmIBigOrLittleEndian(); + + byte *BitConverter::GetBytes(byte *ptr, int count) + { + byte *ret = new byte[count]; + + for (int i = 0; i < count; i++) + { + ret[i] = ptr[i]; + } + + return ret; + } + + byte *BitConverter::GetBytes(bool value) + { + return GetBytes((byte *) &value, 1); + } + + byte *BitConverter::GetBytes(char value) + { + return GetBytes((byte *) &value, 1); + } + + byte *BitConverter::GetBytes(double value) + { + if (SwappedWordsInDouble()) + { + byte *data = new byte[8]; + byte *p = (byte*)&value; + data [0] = p [4]; + data [1] = p [5]; + data [2] = p [6]; + data [3] = p [7]; + data [4] = p [0]; + data [5] = p [1]; + data [6] = p [2]; + data [7] = p [3]; + return data; + } else { + return GetBytes ((byte *) &value, 8); + } + } + + byte *BitConverter::GetBytes(short value) + { + return GetBytes((byte *) &value, 2); + } + + byte *BitConverter::GetBytes(int value) + { + return GetBytes((byte *) &value, 4); + } + + byte *BitConverter::GetBytes(Int64 value) + { + return GetBytes((byte *) &value, 8); + } + + byte *BitConverter::GetBytes(UInt16 value) + { + return GetBytes((byte *) &value, 2); + } + + byte *BitConverter::GetBytes(UInt32 value) + { + return GetBytes((byte *) &value, 4); + } + + byte *BitConverter::GetBytes(UInt64 value) + { + return GetBytes((byte *) &value, 8); + } + + bool BitConverter::ToBoolean(byte value[], int startIndex) + { + if (value == null) + throw ArgumentNullException("value"); + + if (startIndex < 0 || (startIndex > Array::Length(value) - 1)) + throw ArgumentOutOfRangeException("startIndex", "Index was out of range. Must be non-negative and less than the size of the collection."); + + if (value[startIndex] != 0) + return true; + + return false; + } + + char BitConverter::ToChar(byte value[], int startIndex) + { + char ret; + PutBytes ((byte *) &ret, value, startIndex, 2); + return ret; + } +} diff --git a/src/libmscorlib/Buffer.cpp b/src/libmscorlib/Buffer.cpp new file mode 100644 index 0000000..5051d24 --- /dev/null +++ b/src/libmscorlib/Buffer.cpp @@ -0,0 +1,83 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include + +namespace System +{ + template + void Buffer::BlockCopy(T src[], int srcOffset, T dst[], int dstOffset, int count) + { + if (src == null) + throw ArgumentNullException("src"); + + if (dst == null) + throw ArgumentNullException("dst"); + + if (srcOffset < 0) + throw ArgumentOutOfRangeException("srcOffset", "Non-negative number required."); + + if (dstOffset < 0) + throw ArgumentOutOfRangeException("dstOffset", "Non-negative number required."); + + if (count < 0) + throw ArgumentOutOfRangeException("count", "Non-negative number required."); + + if ((srcOffset > ByteLength(src) - count) || (dstOffset > ByteLength(dst) - count)) + throw ArgumentException("Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."); + + for(int i = srcOffset, j = dstOffset; i < (srcOffset + count); i++, j++) + { + dst[j] = src[i]; + } + } + + template + int Buffer::ByteLength(T array[]) + { + return sizeof(array); + } + + template + byte Buffer::GetByte(T array[], int index) + { + if (index < 0 || index >= ByteLength(array)) + throw ArgumentOutOfRangeException("index", "Value must be non-negative and less than the size of the collection."); + + return ((byte *) &array[index]); + } + + template + void Buffer::SetByte(T array[], int index, byte value) + { + if (index < 0 || index >= ByteLength(array)) + throw ArgumentOutOfRangeException ("index", "Value must be non-negative and less than the size of the collection."); + + SetByteInternal(array, index, value); + } +} diff --git a/src/libmscorlib/Calendar.cpp b/src/libmscorlib/Calendar.cpp new file mode 100644 index 0000000..4b3fb9a --- /dev/null +++ b/src/libmscorlib/Calendar.cpp @@ -0,0 +1,49 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include + +namespace System +{ + namespace Globalization + { + DateTime Calendar::AddDays(DateTime time, int days) + { + DateTime result(time); + result.AddDays((double)days); + return result; + } + + DateTime Calendar::AddHours(DateTime time, int hours) + { + DateTime result(time); + result.AddHours((double)hours); + return result; + } + } +} diff --git a/src/libmscorlib/Comparer.cpp b/src/libmscorlib/Comparer.cpp new file mode 100644 index 0000000..6bb83af --- /dev/null +++ b/src/libmscorlib/Comparer.cpp @@ -0,0 +1,12 @@ +#include + +namespace System +{ + namespace Collections + { + namespace Generic + { + + } + } +} diff --git a/src/libmscorlib/DateTime.cpp b/src/libmscorlib/DateTime.cpp new file mode 100644 index 0000000..d46a386 --- /dev/null +++ b/src/libmscorlib/DateTime.cpp @@ -0,0 +1,417 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +#include +#include +#include +#include +#include +#include + +namespace System +{ + // Encodes the DateTime in 64 bits, top two bits contain the DateTimeKind, + // the rest contains the 62 bit value for the ticks. This reduces the + // memory usage from 16 to 8 bytes. + // + const Int64 DateTime::TicksMask = 0x3fffffffffffffffLL; + const Int64 DateTime::KindMask = ((Int64)0xc000000000000000LL); + const int DateTime::KindShift = 62; + // + // w32 file time starts counting from 1/1/1601 00:00 GMT + // which is the constant ticks from the .NET epoch + const Int64 DateTime::w32file_epoch = 504911232000000000LL; + // + //private const long MAX_VALUE_TICKS = 3155378975400000000L; + // -- Microsoft .NET has this value. + const Int64 DateTime::MAX_VALUE_TICKS = 3155378975999999999LL; + // + // The UnixEpoch, it begins on Jan 1, 1970 at 0:0:0, expressed + // in Ticks + // + const Int64 DateTime::UnixEpoch = 621355968000000000LL; + + // for OLE Automation dates + Int64 ticks18991230 = 599264352000000000LL; + double OAMinValue = -657435.0; + double OAMaxValue = 2958466.0; + + int daysmonth[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + int daysmonthleap[] = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + + int DateTime::AbsoluteDays(int year, int month, int day) + { + int *days; + int temp = 0, m=1 ; + + days = (IsLeapYear(year) ? daysmonthleap : daysmonth); + + while (m < month) + temp += days[m++]; + return ((day-1) + temp + (365* (year-1)) + ((year-1)/4) - ((year-1)/100) + ((year-1)/400)); + } + + const DateTime DateTime::MaxValue = DateTime(3155378975999999999LL); + const DateTime DateTime::MinValue = DateTime(0); + + void DateTime::InvalidTickValue(Int64 ticks) + { + char *msg; + sprintf(msg, "Value %d is outside the valid range [0,%d].", ticks, MAX_VALUE_TICKS); + throw ArgumentOutOfRangeException("ticks", msg); + } + + DateTime DateTime::Add(double value, int scale) + { + Int64 num = (Int64) ((value * scale) + ((value >= 0.0) ? 0.5 : -0.5)); + if ((num <= -315537897600000LL) || (num >= 0x11efae44cb400LL)) + throw ArgumentOutOfRangeException("value", "ArgumentOutOfRange_AddValue"); + + return AddTicks(num * 0x2710L); + } + + DateTime::DateTime(int year, int month, int day) + { + DateTime(year, month, day, 0, 0, 0, 0); + } + + DateTime::DateTime(int year, int month, int day, System::Globalization::Calendar calendar) + { + DateTime(year, month, day, 0, 0, 0, 0, calendar); + } + + DateTime::DateTime(int year, int month, int day, int hour, int minute, int second) + { + DateTime(year, month, day, hour, minute, second, 0); + } + + DateTime::DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) + { + if (year < 1 || year > 9999 || month < 1 || month >12 || + day < 1 || day > DaysInMonth(year, month) || hour < 0 || hour > 23 || + minute < 0 || minute > 59 || second < 0 || second > 59 || + millisecond < 0 || millisecond > 999) + throw ArgumentOutOfRangeException("Parameters describe an unrepresentable DateTime."); + + encoded = TimeSpan(AbsoluteDays(year,month,day), hour, minute, second, millisecond).Ticks(); + } + + DateTime::DateTime(Int64 ticks) + { + if (ticks < 0 || ticks > MAX_VALUE_TICKS) + InvalidTickValue(ticks); + encoded = ticks; + } + + DateTime::DateTime(Int64 ticks, DateTimeKind_t kind) + { + if (ticks < 0 || ticks > MAX_VALUE_TICKS) + InvalidTickValue(ticks); + if (kind < 0 || kind > DateTimeKind::Local) + throw ArgumentException("Invalid DateTimeKind value.", "kind"); + + encoded = ((Int64)kind << KindShift) | ticks; + } + + DateTime::DateTime(const DateTime &obj) + { + encoded = obj.encoded; + } + + DateTime DateTime::AddDays(double value) + { + return Add(value, 0x5265c00); + } + + DateTime DateTime::AddHours(double value) + { + return Add(value, 0x36ee80); + } + + DateTime DateTime::AddMilliseconds(double value) + { + return Add(value, 1); + } + + DateTime DateTime::AddMinutes(double value) + { + return Add(value, 0xea60); + } + + DateTime DateTime::AddMonths(int months) + { + int day, month, year, maxday; + + day = Day(); + month = Month() + (months % 12); + year = Year() + months/12; + + if (month < 1) + { + month = 12 + month; + year--; + } + else if (month > 12) + { + month = month -12; + year++; + } + maxday = DaysInMonth(year, month); + if (day > maxday) + day = maxday; + + DateTime temp = DateTime(year, month, day); + temp.encoded |= encoded & KindMask; + return temp.Add(TimeOfDay()); + } + + DateTime DateTime::AddSeconds(double value) + { + return Add(value, 0x3e8); + } + + DateTime DateTime::AddYears(int value) + { + return AddMonths(value * 12); + } + + int DateTime::Compare(DateTime t1, DateTime t2) + { + Int64 t1t = t1.encoded & TicksMask; + Int64 t2t = t2.encoded & TicksMask; + + if (t1t < t2t) + return -1; + else if (t1t > t2t) + return 1; + else + return 0; + } + + int DateTime::CompareTo(DateTime value) + { + return Compare(*this, value); + } + + int DateTime::DaysInMonth(int year, int month) + { + int *days; + + if (month < 1 || month >12) + throw ArgumentOutOfRangeException("month"); + + if (year < 1 || year > 9999) + throw ArgumentOutOfRangeException("year"); + + days = (IsLeapYear(year) ? daysmonthleap : daysmonth); + return days[month]; + } + + bool DateTime::Equals(DateTime obj) + { + return (encoded & TicksMask) == (obj.encoded & TicksMask); + } + + DateTime DateTime::FromFileTime(Int64 fileTime) + { + if (fileTime < 0) + throw ArgumentOutOfRangeException("fileTime", "< 0"); + + return DateTime(w32file_epoch + fileTime).ToLocalTime(); + } + + DateTime DateTime::FromFileTimeUtc(Int64 fileTime) + { + if (fileTime < 0) + throw ArgumentOutOfRangeException("fileTime", "< 0"); + + return DateTime(w32file_epoch + fileTime); + } + + DateTime DateTime::FromOADate(double d) + { + // An OLE Automation date is implemented as a floating-point number + // whose value is the number of days from midnight, 30 December 1899. + + // d must be negative 657435.0 through positive 2958466.0. + if ((d <= OAMinValue) || (d >= OAMaxValue)) + throw ArgumentException("d", "[-657435,2958466]"); + + DateTime dt = DateTime(ticks18991230); + if (d < 0.0) { + double days = Math::Ceiling(d); + // integer part is the number of days (negative) + dt = dt.AddMilliseconds(days * 86400000); + // but decimals are the number of hours (in days fractions) and positive + double hours = (days - d); + dt = dt.AddMilliseconds(hours * 86400000); + } + else { + dt = dt.AddMilliseconds(d * 86400000); + } + + return dt; + } + + int DateTime::GetHashCode() + { + return (int)encoded; + } + + bool DateTime::IsDaylighSavingTime() + { + if ((int)((ulong)encoded >> KindShift) == (int)DateTimeKind::Utc) + return false; + return TimeZone::CurrentTimeZone().IsDaylightSavingTime(*this); + } + + bool DateTime::IsLeapYear(int year) + { + if (year < 1 || year > 9999) + throw ArgumentOutOfRangeException(); + return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0); + } + + TimeSpan DateTime::Subtract(DateTime value) + { + return TimeSpan(Ticks()) - TimeSpan(value.Ticks()); + } + + DateTime DateTime::Subtract(TimeSpan value) + { + Int64 newticks; + + newticks = Ticks() - value.Ticks(); + if (newticks < 0 || newticks > MAX_VALUE_TICKS) + throw new ArgumentOutOfRangeException(); + + DateTime ret = DateTime(newticks); + ret.encoded |= (encoded & KindMask); + return ret; + } + + Int64 DateTime::ToFileTime() + { + DateTime universalTime = ToUniversalTime(); + + if (universalTime.Ticks() < w32file_epoch) + throw ArgumentOutOfRangeException("file time is not valid"); + + return(universalTime.Ticks() - w32file_epoch); + } + + Int64 DateTime::ToFileTimeUtc() + { + if (Ticks() < w32file_epoch) + throw ArgumentOutOfRangeException("file time is not valid"); + + return (Ticks() - w32file_epoch); + } + + double DateTime::ToOADate() + { + Int64 t = Ticks(); + // uninitialized DateTime case + if (t == 0) + return 0; + // we can't reach minimum value + if (t < 31242239136000000LL) + return OAMinValue + 0.001; + + TimeSpan ts = TimeSpan(Ticks() - ticks18991230); + double result = ts.TotalDays(); + // t < 0 (where 599264352000000000 == 0.0d for OA) + if (t < 599264352000000000LL) + { + // negative days (int) but decimals are positive + double d = Math::Ceiling(result); + result = d - 2 - (result - d); + } + else + { + // we can't reach maximum value + if (result >= OAMaxValue) + result = OAMaxValue - 0.00000001; + } + return result; + } + + DateTime DateTime::operator +(TimeSpan other) + { + Int64 res = ((encoded & TicksMask) + other.Ticks()); + if (res < 0 || res > MAX_VALUE_TICKS){ + throw new ArgumentOutOfRangeException(); + } + + return DateTime(res, Kind()); + } + + bool DateTime::operator==(DateTime other) + { + return Equals(other); + } + + bool DateTime::operator >(const DateTime other) + { + return ((encoded & TicksMask) > (other.encoded & TicksMask)); + } + + bool DateTime::operator>=(const DateTime other) + { + return ((encoded & TicksMask) >= (other.encoded & TicksMask)); + } + + bool DateTime::operator!=(DateTime other) + { + return !Equals(other); + } + + bool DateTime::operator <(DateTime other) + { + return ((encoded & TicksMask) < (other.encoded & TicksMask)); + } + + bool DateTime::operator<=(DateTime other) + { + return ((encoded & TicksMask) <= (other.encoded & TicksMask)); + } + + TimeSpan DateTime::operator -(DateTime other) + { + return TimeSpan((encoded & TicksMask) - (other.encoded & TicksMask)); + } + + DateTime DateTime::operator -(TimeSpan t) + { + Int64 res = ((encoded & TicksMask) - t.Ticks()); + if (res < 0 || res > MAX_VALUE_TICKS) + throw ArgumentOutOfRangeException(); + return DateTime(res, Kind()); + } +} diff --git a/src/libmscorlib/Decoder.cpp b/src/libmscorlib/Decoder.cpp new file mode 100644 index 0000000..50eb068 --- /dev/null +++ b/src/libmscorlib/Decoder.cpp @@ -0,0 +1,141 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include + +namespace System +{ + namespace Text + { + void Decoder::Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) + { + CheckArguments(chars, charCount, bytes, byteCount); + + bytesUsed = byteCount; + while (true) { + charsUsed = GetCharCount (bytes, bytesUsed, flush); + if (charsUsed <= charCount) + break; + flush = false; + bytesUsed >>= 1; + } + completed = bytesUsed == byteCount; + charsUsed = GetChars(bytes, bytesUsed, chars, charCount, flush); + } + + void Decoder::Convert(byte bytes[], int byteIndex, int byteCount, char chars[], int charIndex, int charCount, bool flush, int bytesUsed, int charsUsed, bool completed) + { + CheckArguments (bytes, byteIndex, byteCount); + CheckArguments (chars, charIndex); + if (charCount < 0 || Array::Length(chars) < charIndex + charCount) + throw ArgumentOutOfRangeException("charCount"); + + bytesUsed = byteCount; + while (true) + { + charsUsed = GetCharCount (bytes, byteIndex, bytesUsed, flush); + if (charsUsed <= charCount) + break; + flush = false; + bytesUsed >>= 1; + } + completed = bytesUsed == byteCount; + charsUsed = GetChars(bytes, byteIndex, bytesUsed, chars, charIndex, flush); + } + + int Decoder::GetCharCount(byte bytes[], int index, int count, bool flush) + { + if (flush) + Reset(); + return GetCharCount(bytes, index, count); + } + + int Decoder::GetCharCount(byte* bytes, int count, bool flush) + { + if (bytes == null) + { + throw ArgumentNullException("bytes", "Array was null or empty."); + } + if (count < 0) + { + throw ArgumentOutOfRangeException("count", "ArgumentOutOfRange: Non-negative number required."); + } + byte *buffer = new byte[count]; + for (int i = 0; i < count; i++) + { + buffer[i] = bytes[i]; + } + return GetCharCount(buffer, 0, count, flush); + } + + int Decoder::GetChars(byte bytes[], int byteIndex, int byteCount, char chars[], int charIndex, bool flush) + { + CheckArguments(bytes, byteIndex, byteCount); + CheckArguments(chars, charIndex); + + if (flush) + Reset(); + return GetChars(bytes, byteIndex, byteCount, chars, charIndex); + } + + void Decoder::CheckArguments(char chars[], int charIndex) + { + if (chars == null) + throw ArgumentNullException("chars"); + if (charIndex < 0 || Array::Length(chars) <= charIndex) + throw ArgumentOutOfRangeException ("charIndex"); + } + + void Decoder::CheckArguments(byte bytes[], int byteIndex, int byteCount) + { + if (bytes == null) + throw ArgumentNullException("bytes"); + if (byteIndex < 0 || Array::Length(bytes) <= byteIndex) + throw ArgumentOutOfRangeException("byteIndex"); + if (byteCount < 0 || Array::Length(bytes) < byteIndex + byteCount) + throw ArgumentOutOfRangeException("byteCount"); + } + + void Decoder::CheckArguments(char* chars, int charCount, byte* bytes, int byteCount) + { + if (chars == null) + throw ArgumentNullException("chars"); + if (bytes == null) + throw ArgumentNullException("bytes"); + if (charCount < 0) + throw ArgumentOutOfRangeException("charCount"); + if (byteCount < 0) + throw ArgumentOutOfRangeException("byteCount"); + } + + void Decoder::Reset() + { + } + } +} diff --git a/src/libmscorlib/Dictionary.cpp b/src/libmscorlib/Dictionary.cpp new file mode 100644 index 0000000..1fec90d --- /dev/null +++ b/src/libmscorlib/Dictionary.cpp @@ -0,0 +1,328 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include "HashHelpers.h" + +namespace System +{ + namespace Collections + { + namespace Generic + { + template + const char* Dictionary::ComparerName = "Comparer"; + template + const char* Dictionary::HashSizeName = "HashSize"; + template + const char* Dictionary::KeyValuePairsName = "KeyValuePairs"; + template + const char* Dictionary::VersionName = "Version"; + + template + Dictionary::Dictionary(IDictionary dictionary) + { + /*foreach (KeyValuePair pair in dictionary) + { + Add(pair.Key, pair.Value); + }*/ + } + + template + Dictionary::~Dictionary() + { + delete[] buckets; + delete[] entries; + } + + template + IEqualityComparer Dictionary::Comparer() + { + return comparer; + } + + template + void Dictionary::Add(TKey key, TValue value) + { + Insert(key, value, true); + } + + template + void Dictionary::Add(KeyValuePair keyValuePair) + { + Add(keyValuePair.Key(), keyValuePair.Value()); + } + + template + void Dictionary::Clear() + { + if(count > 0) + { + for(int i = 0; i < Array::Length(buckets); i++) + { + buckets[i] = -1; + } + Array::Clear(entries, 0, count); + freeList = -1; + count = 0; + freeCount = 0; + version++; + } + } + + template + bool Dictionary::Contains(KeyValuePair keyValuePair) + { + int index = FindEntry(keyValuePair.Key()); + return ((index >= 0) && EqualityComparer::Default.Equals(entries[index].value, keyValuePair.Value())); + } + + template + void Dictionary::CopyTo(KeyValuePair array[], int index) + { + CopyTo(array, index); + } + + template + int Dictionary::FindEntry(TKey key) + { + if (buckets != null) + { + int num = comparer.GetHashCode(key) & 0x7fffffff; + for (int i = buckets[num % Array::Length(buckets)]; i >= 0; i = entries[i].next) + { + if ((entries[i].hashCode == num) && comparer.Equals(entries[i].key, key)) + { + return i; + } + } + } + return -1; + } + + template + void Dictionary::Initialize(int capacity) + { + int prime = HashHelpers::GetPrime(capacity); + buckets = new int[prime]; + for(int i = 0; i < Array::Length(buckets); i++) + { + buckets[i] = -1; + } + entries = new Entry[prime]; + freeList = -1; + } + + template + void Dictionary::Insert(TKey key, TValue value, bool add) + { + int _freeList; + if(buckets == null) + Initialize(0); + + int num = comparer.GetHashCode(key) & 0x7fffffff; + int index = num % Array::Length(buckets); + for(int i = buckets[index]; i >= 0; i = entries[i].next) + { + if((entries[i].hashCode == num) && comparer.Equals(entries[i].key, key)) + { + if(add) + throw ArgumentException("Adding duplicate of existing key."); + + entries[i].value = value; + version++; + return; + } + } + if(freeCount > 0) + { + _freeList = freeList; + freeList = entries[_freeList].next; + freeCount--; + } + else + { + if(count == Array::Length(entries)) + { + Resize(); + index = num % Array::Length(buckets); + } + freeList = count; + count++; + } + entries[_freeList].hashCode = num; + entries[_freeList].next = buckets[index]; + entries[_freeList].key = key; + entries[_freeList].value = value; + buckets[index] = freeList; + version++; + } + + template + bool Dictionary::Remove(TKey key) + { + if(buckets != null) + { + int num = comparer.GetHashCode(key) & 0x7fffffff; + int index = num % Array::Length(buckets); + int num3 = -1; + for(int i = buckets[index]; i >= 0; i = entries[i].next) + { + if((entries[i].hashCode == num) && comparer.Equals(entries[i].key, key)) + { + if(num3 < 0) + { + buckets[index] = entries[i].next; + } + else + { + entries[num3].next = entries[i].next; + } + entries[i].hashCode = -1; + entries[i].next = freeList; + //entries[i].key = default(TKey); + //entries[i].value = default(TValue); + freeList = i; + freeCount++; + version++; + return true; + } + num3 = i; + } + } + return false; + } + + template + void Dictionary::Resize() + { + int prime = HashHelpers::GetPrime(count * 2); + int* numArray = new int[prime]; + for(int i = 0; i < Array::Length(numArray); i++) + { + numArray[i] = -1; + } + Entry destinationArray[] = new Entry[prime]; + Array::Copy(entries, 0, destinationArray, 0, count); + for(int j = 0; j < count; j++) + { + int index = destinationArray[j].hashCode % prime; + destinationArray[j].next = numArray[index]; + numArray[index] = j; + } + buckets = numArray; + entries = destinationArray; + } + + template + bool Dictionary::TryGetValue(TKey key, out TValue value) + { + int index = FindEntry(key); + if(index >= 0) + { + value = entries[index].value; + return true; + } + //value = default(TValue); + return false; + } + + template + template + Dictionary::KeyCollection::KeyCollection(Dictionary dictionary) + { + _dictionary = dictionary; + } + + template + template + int Dictionary::KeyCollection::Count() + { + return _dictionary.Count(); + } + + template + template + void Dictionary::KeyCollection::Add(UKey item) + { + throw NotSupportedException("Adding keys directly to the Dictionary::Keycollection is not supported."); + } + + template + template + void Dictionary::KeyCollection::Clear() + { + throw NotSupportedException("Directly clearing the Dictionary::KeyCollection is not supported."); + } + + template + template + bool Dictionary::KeyCollection::Contains(UKey item) + { + return _dictionary.ContainsKey(item); + } + + template + template + void Dictionary::KeyCollection::CopyTo(UKey array[], int index) + { + if(array == null) + { + throw ArgumentNullException("array"); + } + if((index < 0) ||(index > Array::Length(array))) + { + throw ArgumentOutOfRangeException("index", "Non-negative array index required."); + } + if((Array::Length(array) - index) < _dictionary.Count()) + { + throw ArgumentException("Array plus offset too small."); + } + int count = _dictionary.Count(); + Entry entries[] = _dictionary.entries; + for(int i = 0; i < count; i++) + { + if(entries[i].hashCode >= 0) + { + array[index++] = entries[i].key; + } + } + } + + template + template + bool Dictionary::KeyCollection::Remove(UKey item) + { + throw NotSupportedException("Removing keys directly from the Dictionary::KeyCollection is not supported."); + return false; + } + } + } +} diff --git a/src/libmscorlib/Directory.cpp b/src/libmscorlib/Directory.cpp new file mode 100644 index 0000000..32c53df --- /dev/null +++ b/src/libmscorlib/Directory.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include + +#include + +#if ENABLE_XBOX +#include +#else +#endif + +namespace System +{ + namespace IO + { + DirectoryInfo Directory::CreateDirectory(char* path) + { + if (path == null) + throw ArgumentNullException("path"); + + if (File::Exists(path)) + throw IOException(strcat((char*)"Cannot create ", strcat(path,(char*)" because a file with the same name already exists."))); + +#if ENABLE_XBOX + XCreateDirectory(path); +#else +#endif + } + + void Directory::Delete(char* path) + { + Delete(path, false); + } + + void Directory::Delete(char* path, bool recursive) + { + + } + + bool Directory::Exists(char* path) + { + return File::Exists(path); + } + + DateTime Directory::GetLastAccessTime(char* path) + { + return File::GetLastAccessTime(path); + } + + DateTime Directory::GetLastWriteTime(char* path) + { + return File::GetLastWriteTime(path); + } + + void Directory::Move(char* sourceDirName, char* destDirName) + { + File::Move(sourceDirName, destDirName); + } + } +} diff --git a/src/libmscorlib/Encoder.cpp b/src/libmscorlib/Encoder.cpp new file mode 100644 index 0000000..03bef59 --- /dev/null +++ b/src/libmscorlib/Encoder.cpp @@ -0,0 +1,58 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace System +{ + namespace Text + { + Encoder::Encoder() + { + } + + void Encoder::Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, int charsUsed, int bytesUsed, bool completed) + { + + } + + void Encoder::Convert(char chars[], int charIndex, int charCount, byte bytes[], int byteIndex, int byteCount, bool flush, int charsUsed, int bytesUsed, bool completed) + { + + } + + int Encoder::GetByteCount(char* chars, int count, bool flush) + { + + } + + int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) + { + + } + } +} diff --git a/src/libmscorlib/Encoding.cpp b/src/libmscorlib/Encoding.cpp new file mode 100644 index 0000000..d7284d3 --- /dev/null +++ b/src/libmscorlib/Encoding.cpp @@ -0,0 +1,36 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace System +{ + namespace Text + { + + } +} diff --git a/src/libmscorlib/Environment.cpp b/src/libmscorlib/Environment.cpp new file mode 100644 index 0000000..d07ce5d --- /dev/null +++ b/src/libmscorlib/Environment.cpp @@ -0,0 +1,81 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include + +extern "C" { +#if ENABLE_XBOX +#include +#else +#endif +} + +namespace System +{ + char* Environment::GetFolderPath(SpecialFolder_t folder) + { +#if ENABLE_XBOX + switch(folder) + { + case SpecialFolder::ApplicationData: + return ""; //! hmmm. What to do here? + case SpecialFolder::Favorites: + return ""; //! XBOX doesn't have a Favorites folder. + case SpecialFolder::Personal: + return ""; //! XBOX doesn't do personal folders, since it lacks user accounts. + case SpecialFolder::Programs: + return "E:\\Apps"; //! Most modded XBOXes have this as their 'programs' directory. + case SpecialFolder::StartMenu: + return ""; //! XBOX doesn't have a Start Menu. + case SpecialFolder::Startup: + return ""; //! XBOX doesn't have a Startup folder. + default: + return ""; + } +#else +#endif + } + + int GetProcessorCount() + { +#if ENABLE_XBOX + return 1; +#else +#endif + } + + int Environment::TickCount() + { +#if ENABLE_XBOX + return KeTickCount; +#else +#endif + } +} diff --git a/src/libmscorlib/Exception.cpp b/src/libmscorlib/Exception.cpp new file mode 100644 index 0000000..0c617c0 --- /dev/null +++ b/src/libmscorlib/Exception.cpp @@ -0,0 +1,82 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace System +{ + char* Exception::Message() + { + return _message; + } + + Exception::Exception() + { + _message = ""; + } + + Exception::Exception(char* message) + { + _message = message; + } + // + // ApplicationException + // + ApplicationException::ApplicationException() + { + _message = ""; + } + + ApplicationException::ApplicationException(char* message) + { + _message = message; + } + // + // ArithmeticException + // + ArithmeticException::ArithmeticException() + { + _message = ""; + } + + ArithmeticException::ArithmeticException(char* message) + { + _message = message; + } + // + // DivideByZeroException + // + DivideByZeroException::DivideByZeroException() + { + _message = ""; + } + + DivideByZeroException::DivideByZeroException(char* message) + { + _message = message; + } +} diff --git a/src/libmscorlib/File.cpp b/src/libmscorlib/File.cpp new file mode 100644 index 0000000..dfbc9fd --- /dev/null +++ b/src/libmscorlib/File.cpp @@ -0,0 +1,218 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include +#include +#include + +namespace System +{ + namespace IO + { + StreamWriter File::AppendText(char* path) + { + if(path == null) + throw ArgumentNullException("path"); + + return StreamWriter(path, true); + } + + void File::Copy(char* sourceFileName, char* destFileName) + { + Copy(sourceFileName, destFileName, false); + } + + void File::Copy(char* sourceFileName, char* destFileName, bool overwrite) + { + if(sourceFileName == null) + throw ArgumentNullException("sourceFileName"); + + if(destFileName == null) + throw ArgumentNullException("destFileName"); + + if(!overwrite && Exists(destFileName)) + { + throw IOException("File specified in 'destFileName' already exists."); + return; + } + + //! Copy the file + } + + FileStream File::Create(char* path) + { + return FileStream(path, FileMode::CreateNew, FileAccess::ReadWrite, FileShare::None); + } + + FileStream File::Create(char* path, int bufferSize) + { + return FileStream(path, FileMode::CreateNew, FileAccess::ReadWrite, FileShare::None, bufferSize); + } + + StreamWriter File::CreateText(char* path) + { + if(path == null) + throw ArgumentNullException("path"); + + return StreamWriter(path, false); + } + + void File::Delete(char* path) + { + if(path == null) + throw ArgumentNullException("path"); + + +#if ENABLE_XBOX + XDeleteFile(path); +#else +#endif + } + + bool File::Exists(char* path) + { + bool flag; + try + { + if(path == null) + return false; + + if(sizeof(path)/sizeof(char) == 0) + return false; + + path = Path::GetFullPath(path); +#if ENABLE_XBOX + PXBOX_FIND_DATA data; + flag = ((FileAttributeInfo(path, data, false, false) == 0) && (data->dwFileAttributes != -1) && ((data->dwFileAttributes & 0x10) == 0)); +#else +#endif + } + catch(ArgumentException) + { + } + catch(NotSupportedException) + { + } +#if !ENABLE_XBOX + catch(SecurityException) + { + } + catch(UnauthorizedAccessException) + { + } +#endif + catch(IOException) + { + } + return flag; + } + + DateTime File::GetCreationTime(char* path) + { +#if ENABLE_XBOX + PXBOX_FIND_DATA data; + path = Path::GetFullPath(path); + FileAttributeInfo(path, data, false, false); + return DateTime::FromFileTimeUtc(data->ftCreationTime); +#else +#endif + } + + DateTime File::GetLastAccessTime(char* path) + { +#if ENABLE_XBOX + PXBOX_FIND_DATA data; + path = Path::GetFullPath(path); + FileAttributeInfo(path, data, false, false); + return DateTime::FromFileTimeUtc(data->ftLastAccessTime); +#else +#endif + } + + DateTime File::GetLastWriteTime(char* path) + { +#if ENABLE_XBOX + PXBOX_FIND_DATA data; + path = Path::GetFullPath(path); + FileAttributeInfo(path, data, false, false); + return DateTime::FromFileTimeUtc(data->ftLastWriteTime); +#else +#endif + } + + void File::Move(char* sourceFileName, char* destFileName) + { + if(sourceFileName == null) + throw ArgumentNullException("sourceFileName"); + + if(destFileName == null) + throw ArgumentNullException("destFileName"); + + char* fullPath = Path::GetFullPath(sourceFileName); + char* dst = Path::GetFullPath(destFileName); + + //! TODO: Move the file + } + + FileStream File::Open(char* path, FileMode_t mode) + { + return Open(path, mode, (mode == FileMode::Append) ? FileAccess::Write : FileAccess::ReadWrite, FileShare::None); + } + + FileStream File::Open(char* path, FileMode_t mode, FileAccess_t access) + { + return FileStream(path, mode, access, FileShare::None); + } + + FileStream File::Open(char* path, FileMode_t mode, FileAccess_t access, FileShare_t share) + { + return FileStream(path, mode, access, share); + } + + FileStream File::OpenRead(char* path) + { + return FileStream(path, FileMode::Open, FileAccess::Read, FileShare::Read); + } + + StreamReader File::OpenText(char* path) + { + if(path == null) + throw ArgumentNullException("path"); + + return StreamReader(path); + } + + FileStream File::OpenWrite(char* path) + { + return FileStream(path, FileMode::OpenOrCreate, FileAccess::Write, FileShare::None); + } + } +} diff --git a/src/libmscorlib/FileStream.cpp b/src/libmscorlib/FileStream.cpp new file mode 100644 index 0000000..da2d17b --- /dev/null +++ b/src/libmscorlib/FileStream.cpp @@ -0,0 +1,361 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include + +#if ENABLE_XBOX +extern "C" { +#include +} +#else +#endif + +namespace System +{ + namespace IO + { + bool FileStream::CanRead() + { + return _access == FileAccess::Read || _access == FileAccess::ReadWrite; + } + + bool FileStream::CanSeek() + { + return canSeek; + } + + bool FileStream::CanWrite() + { + return _access == FileAccess::Write || _access == FileAccess::ReadWrite; + } + + Int64 FileStream::Length() + { + if(handle == -1) + throw ObjectDisposedException("FileStream", "The stream has been closed."); + + if(!canSeek) + throw NotSupportedException("The stream does not support seeking."); + + Int64 length; +#if ENABLE_XBOX + if(XGetFileSize(handle, (unsigned int *)length) != STATUS_SUCCESS) + throw IOException("Could not determine file size. The file may be corrupt."); +#else +#endif + if ((_writePos > 0) && ((_pos + _writePos) > length)) + { + length = _writePos + _pos; + } + return length; + } + + Int64 FileStream::Position() + { + if (handle == -1) + throw ObjectDisposedException("FileStream", "The stream has been closed."); + + if (!canSeek) + throw NotSupportedException("The stream does not support seeking."); + + return (_pos + ((_readPos - _readLen) + _writePos)); + } + + void FileStream::Position(Int64 newPosition) + { + if(canSeek == false) + throw NotSupportedException("The stream does not support seeking"); + + if(newPosition < 0) + throw ArgumentOutOfRangeException("newPosition", "Attempt to set the position to a negative value."); + + Seek(newPosition, SeekOrigin::Begin); + } + + FileStream::FileStream() + { + handle = -1; + } + + FileStream::FileStream(char* path, FileMode_t mode) + { + if(path == null || path == "") + throw ArgumentNullException("path", "path was either NULL or an empty string."); + + _access = (mode == FileMode::Append ? FileAccess::Write : FileAccess::ReadWrite); +#if ENABLE_XBOX + XCreateFile(&handle, path, _access, FileShare::Read, mode, FILE_ATTRIBUTE_NORMAL); +#else +#endif + } + + FileStream::FileStream(char* path, FileMode_t mode, FileAccess_t access) + { + if(path == null || path == "") + throw ArgumentNullException("path", "path was either NULL, or an empty string."); + + _access = access; +#if ENABLE_XBOX + XCreateFile(&handle, path, access, FILE_SHARE_READ | FILE_SHARE_WRITE, mode, FILE_ATTRIBUTE_NORMAL); +#else +#endif + } + + FileStream::FileStream(char* path, FileMode_t mode, FileAccess_t access, FileShare_t share) + { + if(path == null || path == "") + throw ArgumentNullException("path", "path was either NULL, or an empty string."); + +#if ENABLE_XBOX + XCreateFile(&handle, path, access, share, mode, FILE_ATTRIBUTE_NORMAL); +#else +#endif + } + + FileStream::FileStream(char* path, FileMode_t mode, FileAccess_t access, FileShare_t share, int bufferSize) + { + FileStream(path, mode, access, share, bufferSize, false); + } + + FileStream::FileStream(char* path, FileMode_t mode, FileAccess_t access, FileShare_t share, int bufferSize, bool useAsync) + { + if (bufferSize <= 0) + throw ArgumentOutOfRangeException("bufferSize", "Positive number required."); + +#if ENABLE_XBOX + isAsync = useAsync; + + if(isAsync) + { + } + else + { + XCreateFile(&handle, path, access, share, mode, FILE_ATTRIBUTE_NORMAL); + } +#else +#endif + } + + FileStream::~FileStream() + { + Dispose(false); + } + + void FileStream::Dispose(bool disposing) + { + try + { + if((handle != -1) && (_writePos > 0)) + { + FlushWrite(!disposing); + } + } + catch(Exception) + { + } + if((handle != -1)) + { + // ! Invalidate the handle + handle = -1; + } + } + + void FileStream::Flush() + { + if(handle == -1) + throw ObjectDisposedException("FileStream", "The stream has been closed."); + + if (_writePos > 0) + { + FlushWrite(false); + } + else if ((_readPos < _readLen) && canSeek) + { + FlushRead(); + } + _readPos = 0; + _readLen = 0; + } + + void FileStream::FlushWrite(bool calledFromFinalizer) + { + if (isAsync) + { + IAsyncResult asyncResult = BeginWrite(_buffer, 0, _writePos, null, null); + if (!calledFromFinalizer) + { + EndWrite(asyncResult); + } + } + else + { + Write(_buffer, 0, _writePos); + } + _writePos = 0; + } + + int FileStream::Read(byte array[], int offset, int count) + { + if(handle == -1) + throw ObjectDisposedException("FileStream", "The stream has been closed."); + + if(array == null) + throw ArgumentNullException("array"); + + if (!CanRead()) + throw NotSupportedException("Stream does not support reading"); + + int len = (sizeof(array)/sizeof(byte)); + if (offset < 0) + throw ArgumentOutOfRangeException("offset", "< 0"); + if (count < 0) + throw ArgumentOutOfRangeException("count", "< 0"); + if (offset > len) + throw ArgumentException("destination offset is beyond array size"); + // reordered to avoid possible integer overflow + if (offset > len - count) + throw ArgumentException("Reading would overrun buffer"); + + if(isAsync) + { + IAsyncResult ares = BeginRead(array, offset, count, null, null); + return EndRead(ares); + } + +#if ENABLE_XBOX + UInt32 bytesRead; + XReadFile(handle, &array[offset], count, &bytesRead); + return bytesRead; +#else +#endif + } + + int FileStream::ReadByte() + { + void* data; + UInt32 bytesRead; + XReadFile(handle, data, 1, &bytesRead); + + if(bytesRead != 1) + return -1; + + return (int)data; + } + + long long FileStream::Seek(long long offset, SeekOrigin_t origin) + { + if(handle == -1) + throw ObjectDisposedException("FileStream", "The stream has been closed."); + +#if ENABLE_XBOX + FILE_POSITION_INFORMATION positionInfo; + LARGE_INTEGER targetPointer; + IO_STATUS_BLOCK ioStatusBlock; + NTSTATUS status; + UInt32 filesize; + + // Calculate the target pointer + switch (origin) + { + case SeekOrigin::Begin: // From the beginning of the file + targetPointer.QuadPart = offset; + break; + case SeekOrigin::Current: // From the current position + status = NtQueryInformationFile((void*)handle, &ioStatusBlock, &positionInfo, sizeof(positionInfo), FilePositionInformation); + if (!NT_SUCCESS(status)) + return RtlNtStatusToDosError(status); + targetPointer.QuadPart = positionInfo.CurrentByteOffset.QuadPart + offset; + break; + case SeekOrigin::End: // From the end of the file + status = XGetFileSize(handle, &filesize); + if (!NT_SUCCESS(status)) + return RtlNtStatusToDosError(status); + targetPointer.QuadPart -= offset; + break; + } + + // Fill in the new position information + positionInfo.CurrentByteOffset.u.HighPart = targetPointer.u.HighPart; + positionInfo.CurrentByteOffset.u.LowPart= targetPointer.u.LowPart; + + // Set the new position + status = NtSetInformationFile((void*)handle, &ioStatusBlock, &positionInfo, sizeof(positionInfo), FilePositionInformation); + if (!NT_SUCCESS(status)) + return RtlNtStatusToDosError(status); + else + { + return targetPointer.QuadPart; + } +#else +#endif + } + + void FileStream::SetLength(long long value) + { + if(!CanSeek()) + throw NotSupportedException("The stream does not support seeking."); + + if(!CanWrite()) + throw NotSupportedException("The stream does not support writing."); + + if(value < 0) + throw ArgumentOutOfRangeException("value is less than 0"); + + Flush(); + + // + + if (Position() > value) + Position(value); + } + + void FileStream::Write(byte array[], int offset, int count) + { + if(isAsync) + { + IAsyncResult asyncResult = BeginWrite(array, offset, count, null, null); + EndWrite(asyncResult); + } + else + { +#if ENABLE_XBOX + XWriteFile(handle, &array[offset], count, null); +#else +#endif + } + } + + void FileStream::WriteByte(byte value) + { +#if ENABLE_XBOX + XWriteFile(handle, (void*)value, 1, null); +#else +#endif + } + } +} diff --git a/src/libmscorlib/HashHelpers.cpp b/src/libmscorlib/HashHelpers.cpp new file mode 100644 index 0000000..74dcab5 --- /dev/null +++ b/src/libmscorlib/HashHelpers.cpp @@ -0,0 +1,77 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include "HashHelpers.h" +#include +#include + +namespace System +{ + namespace Collections + { + const int HashHelpers::primes[] = { + 3, 7, 11, 0x11, 0x17, 0x1d, 0x25, 0x2f, 0x3b, 0x47, 0x59, 0x6b, 0x83, 0xa3, 0xc5, 0xef, + 0x125, 0x161, 0x1af, 0x209, 0x277, 0x2f9, 0x397, 0x44f, 0x52f, 0x63d, 0x78b, 0x91d, 0xaf1, 0xd2b, 0xfd1, 0x12fd, + 0x16cf, 0x1b65, 0x20e3, 0x2777, 0x2f6f, 0x38ff, 0x446f, 0x521f, 0x628d, 0x7655, 0x8e01, 0xaa6b, 0xcc89, 0xf583, 0x126a7, 0x1619b, + 0x1a857, 0x1fd3b, 0x26315, 0x2dd67, 0x3701b, 0x42023, 0x4f361, 0x5f0ed, 0x72125, 0x88e31, 0xa443b, 0xc51eb, 0xec8c1, 0x11bdbf, 0x154a3f, 0x198c4f, + 0x1ea867, 0x24ca19, 0x2c25c1, 0x34fa1b, 0x3f928f, 0x4c4987, 0x5b8b6f, 0x6dda89 }; + + int HashHelpers::GetPrime(int min) + { + if(min < 0) + throw ArgumentException("min","CapacityOverflow"); + + for(int i = 0; i < Array::Length(primes); i++) + { + int num2 = primes[i]; + if(num2 >= min) + return num2; + } + for(int j = min | 1; j < 0x7fffffff; j += 2) + { + if(IsPrime(j)) + return j; + } + return min; + } + + bool HashHelpers::IsPrime(int candidate) + { + if((candidate & 1) == 0) + return (candidate == 2); + + int num = (int)Math::Sqrt((double)candidate); + for(int i = 3; i <= num; i += 2) + { + if((candidate % i) == 0) + return false; + } + return true; + } + } +} diff --git a/src/libmscorlib/HashHelpers.h b/src/libmscorlib/HashHelpers.h new file mode 100644 index 0000000..20ce9ba --- /dev/null +++ b/src/libmscorlib/HashHelpers.h @@ -0,0 +1,32 @@ +/******************************************************** + * HashHelpers.h * + * * + * XFX HashHelpers class definition file * + * Copyright © XFX Team. All Rights Reserved * + ********************************************************/ +#ifndef _SYSTEM_COLLECTIONS_HASHHELPERS_ +#define _SYSTEM_COLLECTIONS_HASHHELPERS_ + +namespace System +{ + namespace Collections + { + /// + /// This helper class is not meant to be used by the end user. + /// Only XFX source files should reference this class. + /// + class HashHelpers + { + private: + static const int primes[]; + + HashHelpers(); + + public: + static int GetPrime(int min); + static bool IsPrime(int candidate); + }; + } +} + +#endif //_SYSTEM_COLLECTIONS_HASHHELPERS_ diff --git a/src/libmscorlib/IOException.cpp b/src/libmscorlib/IOException.cpp new file mode 100644 index 0000000..31d725e --- /dev/null +++ b/src/libmscorlib/IOException.cpp @@ -0,0 +1,88 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace System +{ + namespace IO + { + IOException::IOException() + { + _message = ""; + } + + IOException::IOException(const char *message) + { + _message = message; + } + // + // DirectoryNotFoundException + // + DirectoryNotFoundException::DirectoryNotFoundException() + { + _message = ""; + } + DirectoryNotFoundException::DirectoryNotFoundException(const char *message) + { + _message = message; + } + // + // EndOfStreamException + // + EndOfStreamException::EndOfStreamException() + { + _message = ""; + } + EndOfStreamException::EndOfStreamException(const char *message) + { + _message = message; + }; + // + // FileNotFoundException + // + FileNotFoundException::FileNotFoundException() + { + _message = ""; + } + FileNotFoundException::FileNotFoundException(const char *message) + { + _message = message; + } + // + // PathTooLongException + // + PathTooLongException::PathTooLongException() + { + _message = ""; + } + PathTooLongException::PathTooLongException(const char *message) + { + _message = message; + } + }; +} diff --git a/src/libmscorlib/KeyNotFoundException.cpp b/src/libmscorlib/KeyNotFoundException.cpp new file mode 100644 index 0000000..b75abd0 --- /dev/null +++ b/src/libmscorlib/KeyNotFoundException.cpp @@ -0,0 +1,52 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace System +{ + namespace Collections + { + namespace Generic + { + KeyNotFoundException::KeyNotFoundException() + : SystemException("Key not found.") + { + } + + KeyNotFoundException::KeyNotFoundException(char* message) + : SystemException(message) + { + } + + KeyNotFoundException::KeyNotFoundException(char* message, Exception innerException) + : SystemException(message, innerException) + { + } + } + } +} diff --git a/src/libmscorlib/KeyValuePair.cpp b/src/libmscorlib/KeyValuePair.cpp new file mode 100644 index 0000000..3aa6837 --- /dev/null +++ b/src/libmscorlib/KeyValuePair.cpp @@ -0,0 +1,63 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace System +{ + namespace Collections + { + namespace Generic + { + template + KeyValuePair::KeyValuePair(TKey key, TValue value) + { + _key = key; + _value = value; + } + + template + KeyValuePair::KeyValuePair(const KeyValuePair &obj) + { + _key = obj._key; + _value = obj._value; + } + + template + TKey KeyValuePair::Key() + { + return _key; + } + + template + TValue KeyValuePair::Value() + { + return _value; + } + } + } +} diff --git a/src/libmscorlib/Math.cpp b/src/libmscorlib/Math.cpp new file mode 100644 index 0000000..08b3a5c --- /dev/null +++ b/src/libmscorlib/Math.cpp @@ -0,0 +1,309 @@ +// Copyright (C) 2010-2012, Halofreak_1990 +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace System +{ + const double Math::E = 2.7182818284590451; + const double Math::PI = 3.1415926535897931; + + double Math::Abs(double value) + { + return (value < 0) ? -value : value; + } + + float Math::Abs(float value) + { + return (value < 0) ? -value : value; + } + + int Math::Abs(int value) + { + return (value < 0) ? -value : value; + } + + long long Math::Abs(long long value) + { + return (value < 0) ? -value : value; + } + + sbyte Math::Abs(sbyte value) + { + return (value < 0) ? -value : value; + } + + short Math::Abs(short value) + { + return (value < 0) ? -value : value; + } + + double Math::Acos(double value) + { + return acos(value); + } + + double Math::Asin(double value) + { + return asin(value); + } + + double Math::Atan(double value) + { + return atan(value); + } + + double Math::Atan2(double value1, double value2) + { + return atan2(value1, value2); + } + + double Math::Ceiling(double value) + { + double result = Floor(value); + if (result != value) + { + result++; + } + return result; + } + + double Math::Cos(double value) + { + return cos(value); + } + + double Math::Cosh(double value) + { + return cosh(value); + } + + double Math::Exp(double value) + { + return exp(value); + } + + double Math::Floor(double value) + { + return floor(value); + } + + double Math::IEEERemainder(double value1, double value2) + { + double d = fmod(value1, value2); + double num2 = d - (Abs(value2) * Sign(value1)); + if (Abs(num2) == Abs(d)) + { + double a = value1 / value2; + if (Abs(Round(a)) > Abs(a)) + { + return num2; + } + return d; + } + if (Abs(num2) < Abs(d)) + { + return num2; + } + return d; + } + + double Math::Log(double value) + { + return log(value); + } + + double Math::Log10(double value) + { + return log10(value); + } + + byte Math::Max(byte value1, byte value2) + { + return (value1 > value2) ? value1 : value2; + } + + double Math::Max(double value1, double value2) + { + return (value1 > value2) ? value1 : value2; + } + + float Math::Max(float value1, float value2) + { + return (value1 > value2) ? value1 : value2; + } + + int Math::Max(int value1, int value2) + { + return (value1 > value2) ? value1 : value2; + } + + long long Math::Max(long long value1, long long value2) + { + return (value1 > value2) ? value1 : value2; + } + + sbyte Math::Max(sbyte value1, sbyte value2) + { + return (value1 > value2) ? value1 : value2; + } + + short Math::Max(short value1, short value2) + { + return (value1 > value2) ? value1 : value2; + } + + uint Math::Max(uint value1, uint value2) + { + return (value1 > value2) ? value1 : value2; + } + + ulong Math::Max(ulong value1, ulong value2) + { + return (value1 > value2) ? value1 : value2; + } + + byte Math::Min(byte value1, byte value2) + { + return (value1 < value2) ? value1 : value2; + } + + double Math::Min(double value1, double value2) + { + return (value1 < value2) ? value1 : value2; + } + + float Math::Min(float value1, float value2) + { + return (value1 < value2) ? value1 : value2; + } + + int Math::Min(int value1, int value2) + { + return (value1 < value2) ? value1 : value2; + } + + long long Math::Min(long long value1, long long value2) + { + return (value1 < value2) ? value1 : value2; + } + + sbyte Math::Min(sbyte value1, sbyte value2) + { + return (value1 < value2) ? value1 : value2; + } + + short Math::Min(short value1, short value2) + { + return (value1 < value2) ? value1 : value2; + } + + uint Math::Min(uint value1, uint value2) + { + return (value1 < value2) ? value1 : value2; + } + + ulong Math::Min(ulong value1, ulong value2) + { + return (value1 < value2) ? value1 : value2; + } + + ushort Math::Min(ushort value1, ushort value2) + { + return (value1 < value2) ? value1 : value2; + } + + double Math::Pow(double value1, double value2) + { + return pow(value1, value2); + } + + double Math::Round(double value) + { + return round(value); + } + + double Math::Round(double value, int digits) + { + return ldexp(value, digits); + } + + int Math::Sign(double value) + { + return (value < 0) ? -1 : (value > 0) ? 1 : 0; + } + + int Math::Sign(float value) + { + return (value < 0) ? -1 : (value > 0) ? 1 : 0; + } + + int Math::Sign(int value) + { + return (value < 0) ? -1 : (value > 0) ? 1 : 0; + } + + int Math::Sign(long long value) + { + return (value < 0) ? -1 : (value > 0) ? 1 : 0; + } + + int Math::Sign(sbyte value) + { + return (value < 0) ? -1 : (value > 0) ? 1 : 0; + } + + int Math::Sign(short value) + { + return (value < 0) ? -1 : (value > 0) ? 1 : 0; + } + + double Math::Sin(double value) + { + return sin(value); + } + + double Math::Sinh(double value) + { + return sinh(value); + } + + double Math::Sqrt(double value) + { + return sqrt(value); + } + + double Math::Tan(double value) + { + return tan(value); + } + + double Math::Tanh(double value) + { + return tanh(value); + } +} diff --git a/src/libmscorlib/MemoryStream.cpp b/src/libmscorlib/MemoryStream.cpp new file mode 100644 index 0000000..6f19825 --- /dev/null +++ b/src/libmscorlib/MemoryStream.cpp @@ -0,0 +1,513 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include + +namespace System +{ + namespace IO + { +#if ENABLE_XBOX // The XBOX Limits us to 64MB; we do not take XDKs into account + const int MemoryStream::MemStreamMaxLength = 0x40000000; +#else + const int MemoryStream::MemStreamMaxLength = 0x7fffffff; +#endif + + bool MemoryStream::CanRead() + { + return _isOpen; + } + + bool MemoryStream::CanSeek() + { + return _isOpen; + } + + bool MemoryStream::CanWrite() + { + return _writable; + } + + int MemoryStream::Capacity() + { + if (!_isOpen) + { + throw ObjectDisposedException(null, "Stream is closed."); + } + return (_capacity - _origin); + } + + void MemoryStream::Capacity(int value) + { + if (!_isOpen) + { + throw ObjectDisposedException(null, "Stream is closed."); + } + if (value != _capacity) + { + if (!_expandable) + { + throw NotSupportedException(""); + } + if (value < _length) + { + throw ArgumentOutOfRangeException("value"); + } + if (value > 0) + { + byte* dst = new byte[value]; + if (_length > 0) + { + Buffer::BlockCopy(_buffer, 0, dst, 0, _length); + } + _buffer = dst; + } + else + { + _buffer = null; + } + _capacity = value; + } + } + + MemoryStream::MemoryStream() + { + _buffer = new byte[0]; + _capacity = 0; + _expandable = true; + _writable = true; + _exposable = true; + _origin = 0; + _isOpen = true; + } + + MemoryStream::MemoryStream(int capacity) + { + if (capacity < 0) + { + throw ArgumentOutOfRangeException("capacity", "Negative capacity is not allowed."); + } + _buffer = new byte[capacity]; + _capacity = capacity; + _expandable = true; + _writable = true; + _exposable = true; + _origin = 0; + _isOpen = true; + } + + MemoryStream::MemoryStream(byte buffer[]) + { + if (buffer == null) + { + throw ArgumentNullException("buffer", "Buffer was NULL."); + } + _buffer = buffer; + _length = _capacity = Array::Length(buffer); + _writable = true; + _exposable = false; + _origin = 0; + _isOpen = true; + } + + MemoryStream::MemoryStream(byte buffer[], bool writable) + { + if (buffer == null) + { + throw ArgumentNullException("buffer", "Buffer was NULL."); + } + _buffer = buffer; + _length = _capacity = Array::Length(buffer); + _writable = writable; + _exposable = false; + _origin = 0; + _isOpen = true; + } + + MemoryStream::MemoryStream(byte buffer[], int index, int count) + { + if (buffer == null) + { + throw ArgumentNullException("buffer", "Buffer was NULL."); + } + if (index < 0) + { + throw ArgumentOutOfRangeException("index", "Non-negative number required."); + } + if (count < 0) + { + throw ArgumentOutOfRangeException("count", "Non-negative number required."); + } + if ((Array::Length(buffer) - index) < count) + { + throw ArgumentException("Invalid offset or length."); + } + _buffer = buffer; + _origin = _position = index; + _length = _capacity = index + count; + _writable = true; + _exposable = false; + _expandable = true; + _isOpen = true; + } + + MemoryStream::MemoryStream(byte buffer[], int index, int count, bool writable) + { + if (buffer == null) + { + throw ArgumentNullException("buffer", "Buffer was NULL."); + } + if (index < 0) + { + throw ArgumentOutOfRangeException("index", "Non-negative number required."); + } + if (count < 0) + { + throw ArgumentOutOfRangeException("count", "Non-negative number required."); + } + if ((Array::Length(buffer) - index) < count) + { + throw ArgumentException("Invalid offset or length."); + } + _buffer = buffer; + _origin = _position = index; + _length = _capacity = index + count; + _writable = writable; + _exposable = false; + _expandable = true; + _isOpen = true; + } + + MemoryStream::MemoryStream(byte buffer[], int index, int count, bool writable, bool publiclyVisible) + { + if (buffer == null) + { + throw ArgumentNullException("buffer", "Buffer was NULL."); + } + if (index < 0) + { + throw ArgumentOutOfRangeException("index", "Non-negative number required."); + } + if (count < 0) + { + throw ArgumentOutOfRangeException("count", "Non-negative number required."); + } + if ((Array::Length(buffer) - index) < count) + { + throw ArgumentException("Invalid offset or length."); + } + _buffer = buffer; + _origin = _position = index; + _length = _capacity = index + count; + _writable = writable; + _exposable = publiclyVisible; + _expandable = true; + _isOpen = true; + } + + void MemoryStream::Dispose(bool disposing) + { + if (disposing) + { + _isOpen = false; + _writable = false; + _expandable = false; + } + Stream::Dispose(disposing); + } + + bool MemoryStream::EnsureCapacity(int value) + { + if (value < 0) + { + throw IOException("Stream too long."); + } + if (value <= _capacity) + { + return false; + } + int num = value; + if (num < 0x100) + { + num = 0x100; + } + if (num < (_capacity * 2)) + { + num = _capacity * 2; + } + _capacity = num; + return true; + } + + void MemoryStream::Flush() + { + } + + byte* MemoryStream::GetBuffer() + { + if (!_exposable) + { + throw UnauthorizedAccessException("Unauthorized access to this MemoryStream buffer."); + } + return _buffer; + } + + int MemoryStream::Read(byte buffer[], int offset, int count) + { + if (!_isOpen) + { + throw ObjectDisposedException(null, "Stream is closed."); + } + if (_buffer == null) + { + throw ArgumentNullException("buffer", "Buffer was null."); + } + if (offset < 0) + { + throw ArgumentOutOfRangeException("offset", "Non-negative number required."); + } + if (count < 0) + { + throw ArgumentOutOfRangeException("count", "Non-negative number required."); + } + if ((Array::Length(buffer) - offset) < count) + { + throw ArgumentException("Invalid offset or length."); + } + int num = _length - _position; + if (num > count) + { + num = count; + } + if (num <= 0) + { + return 0; + } + if (num <= 8) + { + int num2 = num; + while (--num2 >= 0) + { + buffer[offset + num2] = _buffer[_position + num2]; + } + } + else + { + Buffer::BlockCopy(_buffer, _position, buffer, offset, num); + } + _position += num; + return num; + } + + int MemoryStream::ReadByte() + { + if (!_isOpen) + { + throw ObjectDisposedException(null, "Stream is closed."); + } + if (_position >= _length) + { + return -1; + } + return _buffer[_position++]; + } + + Int64 MemoryStream::Seek(Int64 offset, SeekOrigin_t loc) + { + if (!_isOpen) + { + throw ObjectDisposedException(null, "Stream is closed."); + } + if (offset > MemStreamMaxLength) + { + throw ArgumentOutOfRangeException("offset", "offset is greater than the maximum length of this Stream."); + } + switch (loc) + { + case SeekOrigin::Begin: + if (offset < 0LL) + { + throw IOException("Attempting to seek before the start of the Stream."); + } + _position = _origin + ((int)offset); + break; + + case SeekOrigin::Current: + if ((offset + _position) < _origin) + { + throw IOException("Attempting to seek before the start of the Stream."); + } + _position += ((int)offset); + break; + + case SeekOrigin::End: + if ((_length + offset) < _origin) + { + throw IOException("Attempting to seek before the start of the Stream."); + } + _position = _length + ((int)offset); + break; + + default: + throw ArgumentException("Invalid SeekOrigin."); + } + return (Int64)_position; + } + + void MemoryStream::SetLength(Int64 value) + { + if (!_writable) + { + throw NotSupportedException("This Stream does not support writing."); + } + if (value > MemStreamMaxLength) + { + throw ArgumentOutOfRangeException("value", "offset is greater than the maximum length of this Stream."); + } + if ((value < 0LL) || (value > (MemStreamMaxLength - _origin))) + { + throw ArgumentOutOfRangeException("value", "offset is greater than the maximum length of this Stream."); + } + int num = _origin + ((int)value); + if (!EnsureCapacity(num) && (num > _length)) + { + Array::Clear(_buffer, _length, num - _length); + } + _length = num; + if (_position > num) + { + _position = num; + } + } + + byte* MemoryStream::ToArray() + { + byte* dst = new byte[_length - _origin]; + Buffer::BlockCopy(_buffer, _origin, dst, 0, _length - _origin); + return dst; + } + + void MemoryStream::Write(byte buffer[], int offset, int count) + { + if (!_isOpen) + { + throw ObjectDisposedException(null, "Stream is closed."); + } + if (!_writable) + { + throw NotSupportedException("This Stream does not support writing."); + } + if (_buffer == null) + { + throw ArgumentNullException("buffer", "Buffer was null."); + } + if (offset < 0) + { + throw ArgumentOutOfRangeException("offset", "Non-negative number required."); + } + if (count < 0) + { + throw ArgumentOutOfRangeException("count", "Non-negative number required."); + } + if ((Array::Length(buffer) - offset) < count) + { + throw ArgumentException("Invalid offset or length."); + } + int num = _position + count; + if (num < 0) + { + throw IOException("Stream too long"); + } + if (num > _length) + { + bool flag = _position > _length; + if ((num > _capacity) && EnsureCapacity(num)) + { + flag = false; + } + if (flag) + { + Array::Clear(_buffer, _length, num - _length); + } + _length = num; + } + if (count <= 8) + { + int num2 = count; + while (--num2 >= 0) + { + _buffer[_position + num2] = buffer[offset + num2]; + } + } + else + { + Buffer::BlockCopy(buffer, offset, _buffer, _position, count); + } + _position = num; + } + + void MemoryStream::WriteByte(byte value) + { + if (!_isOpen) + { + throw ObjectDisposedException(null, "Stream is closed."); + } + if (!_writable) + { + throw NotSupportedException("This Stream does not support writing."); + } + if (_position >= _length) + { + int num = _position + 1; + bool flag = _position > _length; + if ((num >= _capacity) && EnsureCapacity(num)) + { + flag = false; + } + if (flag) + { + Array::Clear(_buffer, _length, _position - _length); + } + _length = num; + } + _buffer[_position++] = value; + } + + void MemoryStream::WriteTo(Stream stream) + { + if (!_isOpen) + { + throw ObjectDisposedException(null, "Stream is closed."); + } + stream.Write(_buffer, _origin, _length - _origin); + } + } +} diff --git a/src/libmscorlib/Object.cpp b/src/libmscorlib/Object.cpp new file mode 100644 index 0000000..2966351 --- /dev/null +++ b/src/libmscorlib/Object.cpp @@ -0,0 +1,43 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include + +namespace System +{ + bool Object::Equals(Object* obj) + { + //! compare this instance to obj, using the size of the smallest of the two classes + return (memcmp(this, obj, (sizeof(obj) > sizeof(this)) ? sizeof(this) : sizeof(obj)) == 0); + } + + bool Object::Equals(Object* objA, Object* objB) + { + return ((&objA == &objB) || ((objA != null) && (objB != null) && objA->Equals(objB))); + } +} diff --git a/src/libmscorlib/Path.cpp b/src/libmscorlib/Path.cpp new file mode 100644 index 0000000..19cfb64 --- /dev/null +++ b/src/libmscorlib/Path.cpp @@ -0,0 +1,161 @@ +#include +#include +#include +#include + +#define NT_STATUS_OBJECT_NAME_NOT_FOUND long(0xC0000000 | 0x0034) +#define NT_STATUS_VOLUME_DISMOUNTED long(0xC0000000 | 0x026E) + +typedef struct +{ + char cDriveLetter; + char* szDevice; + int iPartition; +} +stDriveMapping; + +#if ENABLE_XBOX +stDriveMapping driveMapping[] = +{ + { 'C', "Harddisk0\\Partition2", 2}, + { 'D', "Cdrom0", -1}, + { 'E', "Harddisk0\\Partition1", 1}, + { 'X', "Harddisk0\\Partition3", 3}, + { 'Y', "Harddisk0\\Partition4", 4}, + { 'Z', "Harddisk0\\Partition5", 5}, +}; +char extendPartitionMapping[] = +{ + 'F','G','R','S','V','W','A','B' +}; +#else +stDriveMapping driveMapping[] = +{ + { 'C', "C:", 2}, + { 'D', "D:", -1}, + { 'E', "E:", 1}, + { 'X', "X:", 3}, + { 'Y', "Y:", 4}, + { 'Z', "Z:", 5}, +}; +#endif + +#define NUM_OF_DRIVES (sizeof(driveMapping) / sizeof(driveMapping[0])) + +namespace System +{ + namespace IO + { + + const char Path::PathSeparator = '\\'; + const char Path::DirectorySeparatorChar = '\\'; + + Path::Path() + { + InvalidPathChars = GetInvalidPathChars(); + + dirEqualsVolume = (DirectorySeparatorChar == VolumeSeparatorChar); + } + + char* Path::ChangeExtension(char* path, char* extension) + { + + } + + char* Path::Combine(char* path1, char* path2) + { + if (path1 == null) + throw ArgumentNullException("path1"); + + if (path2 == null) + throw ArgumentNullException("path2"); + + if ((sizeof(path1)/sizeof(char)) == 0) + return path2; + + if ((sizeof(path2)/sizeof(char)) == 0) + return path1; + + if (IsPathRooted(path2)) + return path2; + + char p1end = path1[(sizeof(path2)/sizeof(char)) - 1]; + if (p1end != DirectorySeparatorChar && p1end != AltDirectorySeparatorChar && p1end != VolumeSeparatorChar) + return strcat(strcat(path1, (const char*)DirectorySeparatorChar), path2); + + return strcat(path1, path2); + } + + bool Path::IsPathRooted(char* path) + { + if (path == null || (sizeof(path)/sizeof(char)) == 0) + return false; + + /* FIXME: check for InvalidPathChars in path + if (path.IndexOfAny (InvalidPathChars) != -1) + throw new ArgumentException ("Illegal characters in path.");*/ + + char c = path [0]; + return (c == DirectorySeparatorChar || c == AltDirectorySeparatorChar || + (!dirEqualsVolume && (sizeof(path)/sizeof(char)) > 1 && path[1] == VolumeSeparatorChar)); + } + + void Path::GetDrive(const char* szPartition, out char* cDriveLetter) + { + int part_str_len = strlen(szPartition); + int part_num; + + if (part_str_len < 19) + { + *cDriveLetter = 0; + return; + } + + part_num = atoi(szPartition + 19); +#ifdef _XBOX + if (part_num >= 6) + { + *cDriveLetter = extendPartitionMapping[part_num-6]; + return; + } +#endif + for (unsigned int i=0; i < NUM_OF_DRIVES; i++) + if (strnicmp(driveMapping[i].szDevice, szPartition, strlen(driveMapping[i].szDevice)) == 0) + { + *cDriveLetter = driveMapping[i].cDriveLetter; + return; + } + *cDriveLetter = 0; + } + + char *Path::GetInvalidFileNameChars() + { + // return a new array as we do not want anyone to be able to change the values +#if ENABLE_XBOX + char invChars[41] = { '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', + '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12', + '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D', + '\x1E', '\x1F', '\x22', '\x3C', '\x3E', '\x7C', ':', '*', '?', '\\', '/' }; + return invChars; +#else + char invChars[2] = { '\x00', '/' }; + return invChars; +#endif + } + + char *Path::GetInvalidPathChars() + { + // return a new array as we do not want anyone to be able to change the values +#if ENABLE_XBOX + char invChars[36] = { '\x22', '\x3C', '\x3E', '\x7C', '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', + '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12', + '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D', + '\x1E', '\x1F' }; + return invChars; +#else + char invChar[1] = { '\x00' }; + return invChar; +#endif + } + } +} diff --git a/src/libmscorlib/Stream.cpp b/src/libmscorlib/Stream.cpp new file mode 100644 index 0000000..bdb2bc6 --- /dev/null +++ b/src/libmscorlib/Stream.cpp @@ -0,0 +1,142 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include + +namespace System +{ + namespace IO + { + Stream::Stream() + { + _asyncActiveCount = 1; + } + + bool Stream::CanTimeOut() + { + return false; + } + + IAsyncResult Stream::BeginRead(byte buffer[], int offset, int count, ASyncCallback callback, void *state) + { + if(!CanRead()) + throw NotSupportedException("This stream does not support reading"); + + StreamAsyncResult result = StreamAsyncResult(state); + try + { + int nbytes = Read(buffer, offset, count); + result.SetComplete(null, nbytes); + } + catch (Exception e) + { + result.SetComplete(&e, 0); + } + + return result; + } + + IAsyncResult Stream::BeginWrite(byte buffer[], int offset, int count, ASyncCallback callback, void *state) + { + if(!CanWrite()) + throw NotSupportedException("This stream does not support writing"); + + StreamAsyncResult result = StreamAsyncResult(state); + try + { + Write (buffer, offset, count); + result.SetComplete(null); + } + catch (Exception e) + { + result.SetComplete(&e); + } + + callback(result); + + return result; + } + + void Stream::Close() + { + Dispose(true); + } + + void Stream::Dispose() + { + Close(); + } + + int Stream::EndRead(IAsyncResult asyncResult) + { + StreamAsyncResult result = (StreamAsyncResult)asyncResult; + if (result.NBytes() == -1) + throw ArgumentException("Invalid IAsyncResult", "asyncResult"); + + if (result.Done) + throw InvalidOperationException("EndRead already called."); + + result.Done = true; + if (result.Exception_() != null) + throw result.Exception_(); + + return result.NBytes(); + } + + void Stream::EndWrite(IAsyncResult asyncResult) + { + StreamAsyncResult result = (StreamAsyncResult)asyncResult; + if (result.NBytes() != -1) + throw ArgumentException("Invalid IAsyncResult", "asyncResult"); + + if (result.Done) + throw InvalidOperationException("EndWrite already called."); + + result.Done = true; + if (result.Exception_() != null) + throw result.Exception_(); + } + + int Stream::ReadByte() + { + byte* buffer = new byte[1]; + if (Read(buffer, 0, 1) == 0) + { + return -1; + } + return buffer[0]; + } + + void Stream::WriteByte(byte value) + { + byte buffer[] = { value }; + Write(buffer, 0, 1); + } + } +} diff --git a/src/libmscorlib/StreamAsyncResult.cpp b/src/libmscorlib/StreamAsyncResult.cpp new file mode 100644 index 0000000..bb326eb --- /dev/null +++ b/src/libmscorlib/StreamAsyncResult.cpp @@ -0,0 +1,89 @@ +// Copyright (C) 2010-2012, Halofreak_1990 +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace System +{ + namespace IO + { + StreamAsyncResult::StreamAsyncResult(void* state) + { + _nbytes = -1; + _state = state; + } + + StreamAsyncResult::StreamAsyncResult(const IAsyncResult &obj) + { + _nbytes = -1; + } + + void* StreamAsyncResult::AsyncState() + { + return _state; + } + + bool StreamAsyncResult::CompletedSynchronously() + { + return true; + } + + Exception* StreamAsyncResult::Exception_() + { + return exc; + } + + bool StreamAsyncResult::IsCompleted() + { + return completed; + } + + int StreamAsyncResult::NBytes() + { + return _nbytes; + } + + void StreamAsyncResult::SetComplete(Exception* e) + { + exc = e; + completed = true; + /* + lock(this) + { + if(wh != null) + wh.Set(); + } + */ + } + + void StreamAsyncResult::SetComplete(Exception* e, int nbytes) + { + _nbytes = nbytes; + SetComplete(e); + } + } +} diff --git a/src/libmscorlib/StreamReader.cpp b/src/libmscorlib/StreamReader.cpp new file mode 100644 index 0000000..61208ac --- /dev/null +++ b/src/libmscorlib/StreamReader.cpp @@ -0,0 +1,36 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace System +{ + namespace IO + { + + } +} diff --git a/src/libmscorlib/StreamWriter.cpp b/src/libmscorlib/StreamWriter.cpp new file mode 100644 index 0000000..2b87cd9 --- /dev/null +++ b/src/libmscorlib/StreamWriter.cpp @@ -0,0 +1,60 @@ +#include +#include + +namespace System +{ + namespace IO + { + void StreamWriter::Close() + { + Dispose(true); + } + + void StreamWriter::Dispose(bool disposing) + { + if(!closable) + { + Flush(true, true); + } + } + + void StreamWriter::Flush() + { + Flush(true, true); + } + + void StreamWriter::Flush(bool flushStream, bool flushEncoder) + { + if (((charPos != 0) || flushStream) || flushEncoder) + { + if (!haveWrittenPreamble) + { + haveWrittenPreamble = true; + byte* preamble = encoding.GetPreamble(); + if (Array::Length(preamble) > 0) + { + stream.Write(preamble, 0, Array::Length(preamble)); + } + } + int count = encoder.GetBytes(charBuffer, 0, charPos, &byteBuffer, 0, flushEncoder); + charPos = 0; + if (count > 0) + { + stream.Write(&byteBuffer, 0, count); + } + if(flushStream) + { + stream.Flush(); + } + } + } + + void StreamWriter::Write(char value) + { + if(charPos == charLen) + { + Flush(false, false); + } + } + } +} diff --git a/src/libmscorlib/String.cpp b/src/libmscorlib/String.cpp new file mode 100644 index 0000000..fa1ba88 --- /dev/null +++ b/src/libmscorlib/String.cpp @@ -0,0 +1,365 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include +#include +#include + +namespace System +{ + const String String::Empty = String(); + + int String::Length() + { + return Array::Length(internalString); + } + + String::String() + { + } + + String::String(char c, int count) + { + if(count < 0) + throw ArgumentOutOfRangeException("count"); + + internalString = new char[count]; + } + + String::String(char value[], int startIndex, int length) + { + if(value == NULL) + throw ArgumentNullException("value"); + + if((length < 0) || startIndex + length > Array::Length(value)) + throw ArgumentOutOfRangeException("length"); + + internalString = new char[length]; + for(int i = 0; i < length; i++) + { + internalString[i] = value[startIndex]; + startIndex++; + } + } + + String::String(char *value) + { + internalString = value; + } + + String::~String() + { + delete internalString; + } + + String String::Clone() + { + return *this; + } + + int String::Compare(String str1, String str2) + { + return strcmp(str1.internalString, str2.internalString); + } + + String String::Concat(String values[]) + { + if(values = NULL) + throw ArgumentNullException("values"); + + char *result; + + return String(result); + } + + String String::Concat(String str1, String str2, String str3, String str4) + { + str1.internalString + str2.internalString + str3.internalString + str4.internalString + return String(tmp); + } + + bool String::Equals(const String obj) + { + return (Compare(internalString, obj.internalString) == 0); + } + + bool String::Equals(const String str1, const String str2) + { + return (Compare(str1.internalString, str2.internalString) == 0); + } + + char* String::Format(char* format, ...) + { + + } + + int String::IndexOf(char value) + { + for(int i = 0; i < Length(); i++) + { + if (internalString[i] == value) + return i; + } + } + + int String::IndexOf(char value, int startIndex) + { + for(int i=startIndex; i < Length(); i++) + { + if(strArray[i] == value) + return i; + } + return -1; + } + + int String::IndexOf(char value, int startIndex, int count) + { + if(startIndex+count > Length()) + return -1; + + for(int i=startIndex; i < startIndex+count; i++) + { + if(strArray[i] == value) + return i; + } + return -1; + } + + bool String::IsNullOrEmpty(String value) + { + return ((value.internalSTring == NULL) || value.internalString == ""); + } + + String String::Join(char* separator, String value[]) + { + if (value == NULL) + throw ArgumentNullException("value"); + + return Join(separator, value, 0, value.Length()); + } + + String String::Join(String separator, String value[], int startIndex, int count) + { + if (separator == NULL) + { + separator = Empty; + } + if (value == NULL) + throw ArgumentNullException("value"); + + if(startIndex < 0) + throw ArgumentOutOfRangeException("startIndex"); + + if (count < 0) + throw ArgumentOutOfRangeException("count"); + + if (startIndex > (value.Length() - count)) + throw ArgumentOutOfRangeException("startIndex"); + + if (count == 0) + { + return Empty; + } + + + } + + String String::PadLeft(int totalWidth) + { + return PadLeft(totalWidth, " "); + } + + String String::PadLeft(int totalWidth, char paddingChar) + { + if(totalWidth < length) + return *this; + + char *buf; + + for(int i=0; i < totalWidth; i++) + { + buf[i] = paddingChar; + } + + strArray = strcat(buf, strArray); + return *this; + } + + String String::PadRight(int totalWidth) + { + if(totalWidth <= Length()) + return *this; + + int diff = totalWidth - internalString.length(); + internalString.append(diff, " "); + return *this; + } + + String String::PadRight(int totalWidth, char paddingChar) + { + if(totalWidth <= Length()) + return *this; + } + + char* *String::Split(String *separator, int count, StringSplitOptions_t options) + { + String arr[1] = { String::Empty }; + return arr; + } + + char* *String::Split(String *separator, StringSplitOptions_t options) + { + + } + + char* *String::Split(char separator[], int count, StringSplitOptions_t options) + { + if (count < 0) + throw ArgumentOutOfRangeException("count") + + if ((options < StringSplitOptions::None) || (options > StringSplitOptions::RemoveEmptyEntries)) + { + throw ArgumentException("options"); + } + bool flag = options == StringSplitOptions::RemoveEmptyEntries; + if ((count == 0) || (flag && (this.Length == 0))) + { + return new string[0]; + } + int[] sepList = new int[this.Length]; + int numReplaces = MakeSeparatorList(separator, ref sepList); + if ((numReplaces == 0) || (count == 1)) + { + return String[] { this }; + } + if (flag) + { + return InternalSplitOmitEmptyEntries(sepList, NULL, numReplaces, count); + } + return InternalSplitKeepEmptyEntries(sepList, NULL, numReplaces, count); + } + + char* *String::Split(char separator[], StringSplitOptions_t options) + { + return Split(separator, 0x7fffffff, options); + } + + char* *String::Split(char separator[], int count) + { + return Split(separator, count, StringSplitOptions::None); + } + + char* *String::Split(char separator[]) + { + return Split(separator, 0x7fffffff, StringSplitOptions::None); + } + + bool String::StartsWith(String value) + { + if (value == NULL) + throw ArgumentNullException("value"); + + + return true; + } + + String String::SubString(int startIndex) + { + String result; + result.internalString = internalString.substr(startIndex); + return result; + } + + String String::SubString(int startIndex, int length) + { + String result; + result.internalString = internalString.substr(startIndex, length); + return result; + } + + char *String::ToCharArray(int startIndex, int length) + { + char tmp[length]; + char *buf = internalString.c_str(); + for(int i = startIndex, j = 0; i < startIndex+length; i++, j++) + { + tmp[j] = + } + } + + char *String::ToCharArray() + { + return internalString.c_str(); + } + + String String::ToLower() + { + + } + + String String::ToString() + { + return *this; + } + + String String::ToUpper() + { + + } + + bool String::operator!=(const String right) + { + return !Equals(right); + } + + bool String::operator==(const String right) + { + return Equals(right); + } + + String String::operator=(const char *right) + { + internalString = right; + return *this; + } + + String String::operator=(const String right) + { + internalString = right.internalString; + return *this; + } + + char String::operator [](int index) + { + if (index < 0 || index >= internalString.length()) + throw IndexOutOfRangeException(); + + return internalString[index]; + } +} diff --git a/src/libmscorlib/SystemException.cpp b/src/libmscorlib/SystemException.cpp new file mode 100644 index 0000000..158dc61 --- /dev/null +++ b/src/libmscorlib/SystemException.cpp @@ -0,0 +1,196 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace System +{ + SystemException::SystemException() + { + _message = ""; + } + + SystemException::SystemException(char* message) + { + _message = message; + } + + SystemException::SystemException(char* message, Exception innerException) + { + _message = message; + } + + AccessViolationException::AccessViolationException() + { + _message = ""; + } + + AccessViolationException::AccessViolationException(char* message) + { + _message = message; + } + + AppDomainUnloadedException::AppDomainUnloadedException() + { + _message = ""; + } + + AppDomainUnloadedException::AppDomainUnloadedException(char* message) + { + _message = message; + } + + ArgumentException::ArgumentException() + { + _message = ""; + _paramName = ""; + } + + ArgumentException::ArgumentException(char* message) + { + _message = message; + _paramName = ""; + } + + ArgumentException::ArgumentException(char* message, char* paramName) + { + _message = message; + _paramName = paramName; + } + + ArgumentNullException::ArgumentNullException() + { + _message = ""; + _paramName = ""; + } + + ArgumentNullException::ArgumentNullException(char* message) + { + _message = message; + _paramName = ""; + } + + ArgumentNullException::ArgumentNullException(char* message, char* paramName) + { + _message = message; + _paramName = paramName; + } + + ArgumentOutOfRangeException::ArgumentOutOfRangeException() + { + } + + ArgumentOutOfRangeException::ArgumentOutOfRangeException(char* paramName, char* message) + { + _message = message; + _paramName = paramName; + } + + ArgumentOutOfRangeException::ArgumentOutOfRangeException(char* paramName, void* object, char* message) + { + _message = message; + _paramName = paramName; + } + + IndexOutOfRangeException::IndexOutOfRangeException() + { + } + + IndexOutOfRangeException::IndexOutOfRangeException(char* message) + { + _message = message; + } + + InvalidOperationException::InvalidOperationException() + { + } + + InvalidOperationException::InvalidOperationException(char* message) + { + _message = message; + } + + NotImplementedException::NotImplementedException() + { + } + + NotImplementedException::NotImplementedException(char* message) + { + _message = message; + } + + NotImplementedException::NotImplementedException(char* message, Exception innerException) + { + _message = message; + } + + NotSupportedException::NotSupportedException() + { + _message = ""; + } + + NotSupportedException::NotSupportedException(char* message) + { + _message = message; + } + + NotSupportedException::NotSupportedException(char* message, Exception innerException) + { + _message = message; + } + + ObjectDisposedException::ObjectDisposedException(char* objectName) + { + _objectName = objectName; + } + + ObjectDisposedException::ObjectDisposedException(char* objectName, char* message) + { + _objectName = objectName; + _message = message; + } + + char* ObjectDisposedException::ObjectName() + { + return _objectName; + } + + UnauthorizedAccessException::UnauthorizedAccessException() + { + _message = ""; + } + + UnauthorizedAccessException::UnauthorizedAccessException(char* message) + { + _message = message; + } + + UnauthorizedAccessException::UnauthorizedAccessException(char* message, Exception inner) + { + _message = message; + } +} diff --git a/src/libmscorlib/TextureCollection.cpp b/src/libmscorlib/TextureCollection.cpp new file mode 100644 index 0000000..af02cfa --- /dev/null +++ b/src/libmscorlib/TextureCollection.cpp @@ -0,0 +1,77 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the copyright holder nor the names of any +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace XFX +{ + namespace Graphics + { + void TextureCollection::Dispose() + { + Dispose(true); + } + + void TextureCollection::Dispose(bool disposing) + { + if (!disposed) + { + if (disposing) + { + // Release all textures + Texture textureArray[] = new Texture[textures.Count]; + textures.CopyTo(textureArray); + for(int i = 0; i < textures.Count; i++) + { + texture.Dispose(); + } + textures.Clear(); + } + disposed = true; + + // Release any unmanaged components + } + } + + TextureCollection::TextureCollection() + { + // Nothing + } + + TextureCollection::~TextureCollection() + { + Dispose(false); + } + // + // Operators + // + Texture TextureCollection::operator [](int index) + { + return textures[index]; + } + } +} diff --git a/src/libmscorlib/Thread.cpp b/src/libmscorlib/Thread.cpp new file mode 100644 index 0000000..bf43d4b --- /dev/null +++ b/src/libmscorlib/Thread.cpp @@ -0,0 +1,139 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace System +{ + namespace Threading + { + ULONG Thread::Id = 0; + + void Thread::Thread_init() + { + PsCreateSystemThreadEx(&system_thread_handle, //Thread Handle + 0, //KernelStackSize + stack_size, //Stack Size + 0, //TlsDataSize + &Id, //Thread ID + NULL, //StartContext1 + NULL, //StartContext2 + TRUE, //CreateSuspended + FALSE, //DebugStack + (PKSTART_ROUTINE)&callback); //StartRoutine + + ObReferenceObjectByHandle(system_thread_handle, PsThreadObjectType, &system_thread_handle); + + //#define LOW_PRIORITY 0 + //#define LOW_REALTIME_PRIORITY 16 + //#define HIGH_PRIORITY 31 + //#define MAXIMUM_PRIORITY 32 + + KeSetBasePriorityThread((PKTHREAD)system_thread_handle, (PVOID)0); //Default the thread to low priority + + state = ThreadState::Unstarted; + + Id++; //increment Id so every thread is unique + } + + void Thread::Abort() + { + PsTerminateSystemThread(STATUS_SUCCESS); + state = ThreadState::Aborted; + } + + Thread::Thread(PKSTART_ROUTINE callBack) + { + stack_size = 65536; + callback = callBack; + Thread_init(); + } + + Thread::Thread(PKSTART_ROUTINE callBack, int stackSize) + { + if(stackSize < 131072) + stack_size = 65536; //Default stack size is 65536, which should be enough, unless there is need for a > 128k stack. + + stack_size = stackSize; + callback = callBack; + Thread_init(); + } + + void Thread::Resume() + { + NtResumeThread(&system_thread_handle, suspendCount); + state = ThreadState::Running; + } + + void Thread::SetPriority(int priority) + { + if((priority != 0) && (priority != 16) && (priority != 31) && (priority != 32)) + return; //no valid values + + ObReferenceObjectByHandle(system_thread_handle, PsThreadObjectType, &system_thread_handle); + KeSetBasePriorityThread((PKTHREAD)system_thread_handle, (PVOID)priority); + } + + void Thread::Sleep(int millisecondsTimeout) + { + if(millisecondsTimeout <= 0) + return; //no reason to sleep. We could also throw an ArgumentOutOfRangeException, but what's the point in that? + + + } + + void Thread::Sleep(TimeSpan timeout) + { + if(timeout == TimeSpan::Zero) + return; //! no reason to sleep + + + } + + void Thread::Start() + { + Resume(); + } + + void Thread::Suspend() + { + NtSuspendThread(&system_thread_handle, suspendCount); + state = ThreadState::Suspended; + } + + bool Thread::IsAlive() + { + return !((state == ThreadState::Aborted) || (state == ThreadState::Stopped) || (state == ThreadState::Unstarted)); + } + + Thread::~Thread() + { + //! Remove any otherwise persistent references to this instance + ObfDereferenceObject(system_thread_handle); + } + } +} diff --git a/src/libmscorlib/TimeSpan.cpp b/src/libmscorlib/TimeSpan.cpp new file mode 100644 index 0000000..4207b21 --- /dev/null +++ b/src/libmscorlib/TimeSpan.cpp @@ -0,0 +1,320 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include + +namespace System +{ + const TimeSpan TimeSpan::Zero = TimeSpan(0L); + const TimeSpan TimeSpan::MaxValue = TimeSpan(0L); + const TimeSpan TimeSpan::MinValue = TimeSpan(0L); + const Int64 TimeSpan::TicksPerMillisecond = 10000L; + const Int64 TimeSpan::TicksPerSecond = 10000000L; + const Int64 TimeSpan::TicksPerMinute = 600000000L; + const Int64 TimeSpan::TicksPerHour = 36000000000LL; + const Int64 TimeSpan::TicksPerDay = 864000000000LL; + + TimeSpan::TimeSpan(int hours, int minutes, int seconds) + { + CalculateTicks(0, hours, minutes, seconds, 0, true, _ticks); + } + + TimeSpan::TimeSpan(int days, int hours, int minutes, int seconds) + { + CalculateTicks(days, hours, minutes, seconds, 0, true, _ticks); + } + + TimeSpan::TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) + { + CalculateTicks(days, hours, minutes, seconds, milliseconds, true, _ticks); + } + + TimeSpan::TimeSpan(Int64 ticks) + { + _ticks = ticks; + } + + TimeSpan::TimeSpan(const TimeSpan &obj) + { + _ticks = obj._ticks; + } + + int TimeSpan::Days() + { + return (int) (_ticks / TicksPerDay); + } + + int TimeSpan::Hours() + { + return (int) (_ticks % TicksPerDay / TicksPerHour); + } + + int TimeSpan::Milliseconds() + { + return (int) (_ticks % TicksPerSecond / TicksPerMillisecond); + } + + int TimeSpan::Minutes() + { + return (int) (_ticks % TicksPerHour / TicksPerMinute); + } + + int TimeSpan::Seconds() + { + return (int) (_ticks % TicksPerMinute / TicksPerSecond); + } + + Int64 TimeSpan::Ticks() + { + return _ticks; + } + + double TimeSpan::TotalDays() + { + return (double) _ticks / TicksPerDay; + } + + double TimeSpan::TotalHours() + { + return (double) _ticks / TicksPerHour; + } + + double TimeSpan::TotalMilliseconds() + { + return (double) _ticks / TicksPerMillisecond; + } + + double TimeSpan::TotalMinutes() + { + return (double) _ticks / TicksPerMinute; + } + + double TimeSpan::TotalSeconds() + { + return (double) _ticks / TicksPerSecond; + } + + TimeSpan TimeSpan::Add(TimeSpan ts) + { + Int64 temp; + temp = _ticks + ts._ticks; + + //! Check for overflow + if(temp - ts._ticks != _ticks) + throw OverflowException("Resulting TimeSpan is too big."); + + //! Everything checks out + return TimeSpan(_ticks + ts._ticks); + } + + int TimeSpan::Compare(TimeSpan t1, TimeSpan t2) + { + if (t1._ticks < t2._ticks) + return -1; + if (t1._ticks > t2._ticks) + return 1; + return 0; + } + + int TimeSpan::CompareTo(TimeSpan ts) + { + return Compare(*this, ts); + } + + bool TimeSpan::Equals(TimeSpan obj) + { + return (_ticks == obj._ticks); + } + + bool TimeSpan::Equals(TimeSpan t1, TimeSpan t2) + { + return (t1._ticks == t2._ticks); + } + + TimeSpan TimeSpan::FromDays(double value) + { + return Interval(value, 0x5265c00); + } + + TimeSpan TimeSpan::FromHours(double value) + { + return Interval(value, 0x36ee80); + } + + TimeSpan TimeSpan::FromMilliseconds(double value) + { + return Interval(value, 1); + } + + TimeSpan TimeSpan::FromMinutes(double value) + { + return Interval(value, 0xea60); + } + + TimeSpan TimeSpan::FromSeconds(double value) + { + return Interval(value, 0x3e8); + } + + TimeSpan TimeSpan::FromTicks(Int64 value) + { + return TimeSpan(value); + } + + int TimeSpan::GetHashCode() + { + return (((int)_ticks) ^ ((int)(_ticks >> 0x20))); + } + + TimeSpan TimeSpan::Negate() + { + if (_ticks == MinValue._ticks) + throw OverflowException(); + + return TimeSpan(-_ticks); + } + + TimeSpan TimeSpan::Subtract(TimeSpan ts) + { + Int64 ticks = _ticks - ts._ticks; + if (((_ticks >> 0x3f) != (ts._ticks >> 0x3f)) && ((_ticks >> 0x3f) != (ticks >> 0x3f))) + throw new OverflowException("TimeSpan too long."); + + return TimeSpan(ticks); + } + + TimeSpan TimeSpan::operator +(const TimeSpan other) + { + return Add(other); + } + + bool TimeSpan::operator==(const TimeSpan other) + { + return Equals(*this, other); + } + + bool TimeSpan::operator >(const TimeSpan other) + { + return _ticks > other._ticks; + } + + bool TimeSpan::operator >=(const TimeSpan other) + { + return _ticks >= other._ticks; + } + + bool TimeSpan::operator!=(const TimeSpan other) + { + return !Equals(*this, other); + } + + bool TimeSpan::operator <(const TimeSpan other) + { + return _ticks < other._ticks; + } + + bool TimeSpan::operator <=(const TimeSpan other) + { + return _ticks <= other._ticks; + } + + TimeSpan TimeSpan::operator -(const TimeSpan other) + { + return Subtract(other); + } + + TimeSpan TimeSpan::operator -() + { + return Negate(); + } + + bool TimeSpan::CalculateTicks(int days, int hours, int minutes, int seconds, int milliseconds, bool throwExc, long long result) + { + // there's no overflow checks for hours, minutes, ... + // so big hours/minutes values can overflow at some point and change expected values + int hrssec = (hours * 3600); // break point at (Int32.MaxValue - 596523) + int minsec = (minutes * 60); + Int64 t = ((Int64)(hrssec + minsec + seconds) * 1000L + (Int64)milliseconds); + t *= 10000; + + result = 0; + + bool overflow = false; + // days is problematic because it can overflow but that overflow can be + // "legal" (i.e. temporary) (e.g. if other parameters are negative) or + // illegal (e.g. sign change). + if (days > 0) { + Int64 td = TicksPerDay * days; + if (t < 0) { + Int64 ticks = t; + t += td; + // positive days -> total ticks should be lower + overflow = (ticks > t); + } + else { + t += td; + // positive + positive != negative result + overflow = (t < 0); + } + } + else if (days < 0) { + Int64 td = TicksPerDay * days; + if (t <= 0) { + t += td; + // negative + negative != positive result + overflow = (t > 0); + } + else { + Int64 ticks = t; + t += td; + // negative days -> total ticks should be lower + overflow = (t > ticks); + } + } + + if (overflow) { + if (throwExc) + throw ArgumentOutOfRangeException("The timespan is too big or too small."); + return false; + } + + result = t; + return true; + } + + TimeSpan TimeSpan::Interval(double value, int scale) + { + double num = value * scale; + double num2 = num + ((value >= 0.0) ? 0.5 : -0.5); + if ((num2 > 922337203685477LL) || (num2 < -922337203685477LL)) + { + throw OverflowException("TimeSpan too long."); + } + return TimeSpan(((Int64) num2) * 0x2710L); + } +} diff --git a/src/libmscorlib/Version.cpp b/src/libmscorlib/Version.cpp new file mode 100644 index 0000000..6f34c65 --- /dev/null +++ b/src/libmscorlib/Version.cpp @@ -0,0 +1,127 @@ +// Copyright (C) 2010-2012, XFX Team +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +//* Redistributions of source code must retain the above copyright +//notice, this list of conditions and the following disclaimer. +//* Redistributions in binary form must reproduce the above copyright +//notice, this list of conditions and the following disclaimer in the +//documentation and/or other materials provided with the distribution. +//* Neither the name of the copyright holder nor the names of any +//contributors may be used to endorse or promote products derived from +//this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include + +namespace System +{ + int Version::Build() + { + return _build; + } + + int Version::Major() + { + return _major; + } + + int Version::Minor() + { + return _minor; + } + + int Version::Revision() + { + return _revision; + } + + Version::Version(int major, int minor) + { + _major = major; + _minor = minor; + } + + Version::Version(char* version) + { + + } + + Version Version::Clone() + { + return Version(_major, _minor, _build, _revision); + } + + bool Version::Equals(Version obj) + { + return ((_build == obj._build) && (_major == obj._major) && + (_minor == obj._minor) && (_revision == obj._revision)); + } + + int Version::GetHashCode() + { + return (_build ^ _major ^ _minor ^ _revision); + } + + char* Version::ToString() + { + return String::Format("%d.%d.%d.%d", _major, _minor, _build, _revision); + } + + char* Version::ToString(int fieldCount) + { + if(fieldCount <= 0 || fieldCount > 4) + throw ArgumentOutOfRangeException("fieldCount"); + + + } + + bool Version::operator !=(Version other) + { + return !Equals(other); + } + + bool Version::operator <(Version other) + { + return ((_build < other._build) && (_major < other._major) && + (_minor < other._minor) && (_revision < other._revision)); + } + + bool Version::operator <=(Version other) + { + return ((_build <= other._build) && (_major <= other._major) && + (_minor <= other._minor) && (_revision <= other._revision)); + } + + bool Version::operator ==(Version other) + { + return Equals(other); + } + + bool Version::operator >(Version other) + { + return ((_build > other._build) && (_major > other._major) && + (_minor > other._minor) && (_revision > other._revision)); + } + + bool Version::operator >=(Version other) + { + return ((_build >= other._build) && (_major >= other._major) && + (_minor >= other._minor) && (_revision >= other._revision)); + } +} diff --git a/src/libmscorlib/libmscorlib.vcproj b/src/libmscorlib/libmscorlib.vcproj new file mode 100644 index 0000000..726c1e3 --- /dev/null +++ b/src/libmscorlib/libmscorlib.vcproj @@ -0,0 +1,548 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/libmscorlib/makefile b/src/libmscorlib/makefile new file mode 100644 index 0000000..e07670e --- /dev/null +++ b/src/libmscorlib/makefile @@ -0,0 +1,53 @@ +# +# update this variable to wherever you installed the OpenXDK libraries +# +######################################################################### +# +# The ENABLE_XBOX definition is there because of intentions to eventually +# support Linux as well +# +PREFIX = /usr/local/openxdk + +CC = gcc +CCAS = gcc +CPP = g++ +AR = ar rcu +RANLIB = ranlib +CXBE = $(PREFIX)/bin/cxbe + +SDLFLAGS = -DENABLE_XBOX -DDEBUG +CC_FLAGS = -c -g -std=gnu99 -ffreestanding -nostdlib -fno-builtin -fno-exceptions -mno-cygwin -march=i386 $(SDLFLAGS) +CCAS_FLAGS = -g -O2 +CPP_FLAGS = -c -O2 -Wall -nostdlib -fno-builtin -mno-cygwin -march=i386 -mmmx -msse -mfpmath=sse $(SDLFLAGS) +INCLUDE = -I$(PREFIX)/i386-pc-xbox/include -I$(PREFIX)/include -I$(PREFIX)/include/SDL -I../../include + +CLINK = -nostdlib +ALIGN = -Wl,--file-alignment,0x20 -Wl,--section-alignment,0x20 +SHARED = -shared +ENTRYPOINT = -Wl,--entry,_WinMainCRTStartup +STRIP = -Wl,--strip-all +LD_FLAGS = $(CLINK) $(ALIGN) $(SHARED) $(ENTRYPOINT) $(STRIP) +LD_DIRS = -L$(PREFIX)/i386-pc-xbox/lib -L$(PREFIX)/lib +LD_LIBS = $(LD_DIRS) -lm -lopenxdk -lhal -lc -lusb -lc -lxboxkrnl -lc -lhal -lxboxkrnl -lhal -lopenxdk -lc -lstdc++ -lgcc + +OBJS = Array.o BinaryReader.o BitConverter.o Buffer.o Calendar.o DateTime.o Decoder.o Dictionary.o Directory.o Encoder.o Environment.o Exception.o File.o FileStream.o HashHelpers.o KeyNotFoundException.o KeyValuePair.o List.o Math.o misc.o MemoryStream.o Path.o Stream.o StreamAsyncResult.o StreamReader.o StreamWriter.o Thread.o TimeSpan.o Version.o + +all: libmscorlib.a + +rebuild: clean libmscorlib.a + +libmscorlib.a: $(OBJS) + $(AR) $@ $(OBJS) + $(RANLIB) $@ + +.c.o: + $(CC) -c $< $(CC_FLAGS) $(INCLUDE) + +.cpp.o: + $(CPP) -c $< $(CPP_FLAGS) $(INCLUDE) + +.s.o: + $(CCAS) -c $< $(CCAS_FLAGS) + +clean: + rm -f *.o *.exe *.dll *.xbe *.cxbe *.lib *.a diff --git a/src/libmscorlib/misc.cpp b/src/libmscorlib/misc.cpp new file mode 100644 index 0000000..96e2d57 --- /dev/null +++ b/src/libmscorlib/misc.cpp @@ -0,0 +1,182 @@ +/******************************************************************************/ +/* */ +/* File: misc.cpp */ +/* Author: bkenwright@xbdev.net */ +/* Desc: Misc functions, making our usb/gamepad code lib independent */ +/* */ +/******************************************************************************/ + +#include +#include + +/******************************************************************************/ +/* */ +/* Debug Function */ +/* */ +/* Its a simple, but useful function to provide essential feedback during */ +/* the early development stages....especially when your developing an app */ +/* like the ohci-usb :-/ */ +/* */ +/******************************************************************************/ + +//#include +//#include + +//extern void op_txt(char* str); // top of main.cpp + +char buf[500]; +void dbg(char* str) +{ + //FILE *fp = fopen("d:\\output.txt", "a+"); + //fprintf(fp, "%s", str); + //fclose(fp); + + //char buffer[500]; + //sprintf(buffer, "%s", str); + //op_txt(str); +}// End dbg(..) + +/******************************************************************************/ + +// Might want to look into using this kernel api at a later date for xSleep(..) +// extern "C" void __stdcall KeDelayExecutionThread(__u32 a, __u32 b, __u32 c); +void Sleep(long timemilliseconds) +{ + //Sleep(timemilliseconds); + + unsigned long long nowTime = KeTickCount; + unsigned long long oldTime = KeTickCount; + + while( nowTime < (oldTime + timemilliseconds) ) + nowTime = (int)KeTickCount; +} + +#define small_memcpy(dest, src, count)\ +{\ + register unsigned long dummy;\ + __asm__ __volatile__(\ + "rep; movsb"\ + :"=&D"(dest), "=&S"(src), "=&c"(dummy)\ + :"0"(dest), "1" (src),"2" (count)\ + : "memory");\ +} + +void *__memcpy(void *dest, const void *src, size_t count) +{ + int d0, d1, d2; + + if (count < 4) + { + small_memcpy(dest, src, count); + } + else + __asm__ __volatile__( + "rep ; mvsl\n\t" + "testb $2,%b4\n\t" + "je 1f\n\t" + "movsw\n" + "1:\ttestb $1,%b4\n\t" + "je 2f\n\t" + "movsb\n" + "2:" + : "=&c" (d0), "=&D" (d1), "=&S" (d2) + :"0" (count/4), "q" (count),"1" ((long) dest),"2" ((long) src) + : "memory"); + return dest; +} + +void *memcpy(void *dest, const void *src, size_t count) +{ + void *retval; + size_t i; + retval = dest; + + /* prefetch has effect, even for movsb instruction */ + __asm__ __volatile__ ( + "prefetchnta (%0)\n" + "prefetchnta 64(%0)\n" + "prefetchnta 128(%0)\n" + "prefetchnta 192(%0)\n" + "prefetchnta 256(%0)\n" + : : "r" (src) ); + + if(count >= 0x40) + { + register unsigned long delta; + /* Align destination to 16 - boundary */ + delta = ((unsigned long)dest)&(15); + if(delta) + { + delta = 16 - delta; + count -= delta; + small_memcpy(dest, src, delta); + } + i = count >> 6; /* count / 64 */ + count &=63; + if (((unsigned long)src) & 15) + /* If src is misaligned */ + for (; i > 0; i--) + { + __asm__ __volatile__ ( + "prefetchnta 320(%0)\n" + "movups (%0), %%xmm0\n" + "movups 16(%0), %%xmm1\n" + "movups 32(%0), %%xmm2\n" + "movups 48(%0), %%xmm3\n" + "movntps %%xmm0, (%1)\n" + "movntps %%xmm1, 16(%1)\n" + "movntps %%xmm2, 32(%1)\n" + "movntps %%xmm3, 48(%1)\n" + :: "r" (src), "r" (dest) : "memory"); + src = ((const unsigned char *)src)+64; + dest = ((unsigned char*)dest)+64; + } + else + /* Only if src is aligned on 16-byte boundary. + It allows to use movaps instead of movups, which required + data to be aligned or a general protection exception (#GP) + is generated. + */ + for (; i > 0; i--) + { + __asm__ __volatile__ ( + "prefetchnta 320(%0)\n" + "movaps (%0), %%xmm0\n" + "movaps 16(%0), %%xmm1\n" + "movaps 32(%0), %%xmm2\n" + "movaps 48(%0), %%xmm3\n" + "movntps %%xmm0, (%1)\n" + "movntps %%xmm1, 16(%1)\n" + "movntps %%xmm2, 32(%1)\n" + "movntps %%xmm3, 48(%1)\n" + :: "r" (src), "r" (dest) : "memory"); + src = ((const unsigned char *)src)+64; + dest = ((unsigned char*)dest)+64; + } + /* since movntq is weakly-ordered, a "sfence" + * is needed to become aligned again. */ + __asm__ __volatile__ ("sfence":::"memory"); + /* enables to use FPU */ + __asm__ __volatile__ ("ems":::"memory"); + } + /* Now, do the tail of the block */ + if (count) __memcpy(dest, src, count); + return retval; +} + +void *malloc(size_t size) +{ + return (void*)MmAllocateContiguousMemory(size); +} + +void *memset(void *s, char c, size_t count) +{ + int d0, d1; + __asm__ __volatile__( + "rep\n\t" + "stosb" + : "=&c" (d0), "=&D" (d1) + :"a" (c),"1" (s),"0" (count) + :"memory"); + return s; +}