├── BspViewer.Tests ├── TestData │ └── Entities │ │ ├── InvalidEntity.txt │ │ ├── InvalidEmptyEntity.txt │ │ └── ValidEntites.txt ├── packages.config ├── Properties │ └── AssemblyInfo.cs ├── TestBase.cs ├── EntityTests.cs ├── WadTests.cs └── BspViewer.Tests.csproj ├── Assets ├── BspViewer.gif ├── BspViewer.png ├── Maps │ └── SampleMap.bsp ├── Wads │ └── SampleWad.wad └── Docs │ ├── Unofficial_WAD3_FileSpec.htm │ └── Unofficial_BSPv30_FileSpec.htm ├── BspViewer.Desktop ├── packages.config ├── App.config ├── Program.cs ├── Utils │ └── MathLib.cs ├── Properties │ ├── AssemblyInfo.cs │ └── OpenTK.dll.config ├── BspViewer.Desktop.csproj ├── Viewer.cs ├── Components │ └── Camera.cs └── Renderer.cs ├── BspViewer ├── SourceMap │ ├── WadDefs.cs │ ├── WadLumps.cs │ ├── BspMap.cs │ ├── BspDefs.cs │ ├── BspRenderer.cs │ ├── BspLumps.cs │ ├── BspLoader.cs │ └── WadLoader.cs ├── Utils │ ├── MathLib.cs │ ├── ColorUtils.cs │ └── TexUtil.cs ├── SourceEntity │ ├── Entities.cs │ ├── EntityParser.cs │ └── Entity.cs ├── Extensions │ ├── StringExtensions.cs │ └── BinaryReaderExtensions.cs ├── Properties │ └── AssemblyInfo.cs └── BspViewer.csproj ├── README.md ├── BspViewer.sln ├── .gitattributes ├── .gitignore └── LICENSE /BspViewer.Tests/TestData/Entities/InvalidEntity.txt: -------------------------------------------------------------------------------- 1 | { 2 | -------------------------------------------------------------------------------- /BspViewer.Tests/TestData/Entities/InvalidEmptyEntity.txt: -------------------------------------------------------------------------------- 1 | { 2 | } -------------------------------------------------------------------------------- /Assets/BspViewer.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PSneijder/BspViewer/HEAD/Assets/BspViewer.gif -------------------------------------------------------------------------------- /Assets/BspViewer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PSneijder/BspViewer/HEAD/Assets/BspViewer.png -------------------------------------------------------------------------------- /Assets/Maps/SampleMap.bsp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PSneijder/BspViewer/HEAD/Assets/Maps/SampleMap.bsp -------------------------------------------------------------------------------- /Assets/Wads/SampleWad.wad: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PSneijder/BspViewer/HEAD/Assets/Wads/SampleWad.wad -------------------------------------------------------------------------------- /BspViewer.Desktop/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /BspViewer/SourceMap/WadDefs.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace BspViewer 3 | { 4 | public static class WadDefs 5 | { 6 | public const int MAXTEXTURENAME = 16; 7 | public const int MIPLEVELS = 4; 8 | } 9 | } -------------------------------------------------------------------------------- /BspViewer.Desktop/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /BspViewer.Tests/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /BspViewer.Desktop/Program.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace BspViewer 3 | { 4 | class Program 5 | { 6 | static void Main() 7 | { 8 | using (var viewer = new Viewer()) 9 | { 10 | viewer.Run(); 11 | } 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /BspViewer/Utils/MathLib.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace BspViewer 3 | { 4 | internal static class MathLib 5 | { 6 | public const float SQRT2 = 1.41421356237f; 7 | 8 | public static float DotProduct(float[] v1, float[] v2) 9 | { 10 | return (v1[0] * v2[0]) + (v1[1] * v2[1]) + (v1[2] * v2[2]); 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /BspViewer.Tests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("BspViewer.Tests")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("")] 9 | [assembly: AssemblyProduct("BspViewer.Tests")] 10 | [assembly: AssemblyCopyright("Copyright © 2017")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("e460c57d-2707-4b78-8c74-831f064e3b39")] 17 | 18 | // [assembly: AssemblyVersion("1.0.*")] 19 | [assembly: AssemblyVersion("1.0.0.0")] 20 | [assembly: AssemblyFileVersion("1.0.0.0")] 21 | -------------------------------------------------------------------------------- /BspViewer/SourceEntity/Entities.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace BspViewer 5 | { 6 | public sealed class Entities 7 | : List 8 | { 9 | public Entities(IEnumerable entities) 10 | : base(entities) { } 11 | 12 | public Dictionary this[string key] 13 | { 14 | get 15 | { 16 | int index = FindIndex(dict => dict.Values.Any(val => val == key)); 17 | 18 | if(index != -1) 19 | { 20 | return this[index]; 21 | } 22 | 23 | return new Dictionary(); 24 | } 25 | set { } 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /BspViewer/Extensions/StringExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | 4 | namespace BspViewer.Extensions 5 | { 6 | public static class StringExtensions 7 | { 8 | public static float[] AsSingleArray(this string key) 9 | { 10 | float[] results = new float[3]; 11 | string[] nums = key.Split(' '); 12 | 13 | for (int i = 0; i < results.Length && i < nums.Length; ++i) 14 | { 15 | try 16 | { 17 | results[i] = Single.Parse(nums[i], NumberStyles.Float); 18 | } 19 | catch 20 | { 21 | results[i] = 0; 22 | } 23 | } 24 | 25 | return results; 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /BspViewer.Tests/TestBase.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Reflection; 3 | 4 | namespace BspViewer.Tests 5 | { 6 | public abstract class TestBase 7 | { 8 | protected string GetFileContents(string sampleFile) 9 | { 10 | var assembly = Assembly.GetExecutingAssembly(); 11 | var resource = string.Format("BspViewer.Tests.TestData.{0}", sampleFile); 12 | 13 | using (var stream = assembly.GetManifestResourceStream(resource)) 14 | { 15 | if (stream != null) 16 | { 17 | using (var reader = new StreamReader(stream)) 18 | { 19 | return reader.ReadToEnd(); 20 | } 21 | } 22 | } 23 | 24 | return string.Empty; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /BspViewer/SourceMap/WadLumps.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace BspViewer 3 | { 4 | public struct WadLump 5 | { 6 | public int Offset { get; set; } 7 | public int CompressedSize { get; set; } 8 | public int Size { get; set; } 9 | public sbyte Type { get; set; } 10 | public bool Compression { get; set; } 11 | public char[] Name { get; set; } 12 | } 13 | 14 | public struct WadHeader 15 | { 16 | public static readonly int SizeInBytes = 12; 17 | 18 | public string Magic { get; set; } // Should be WAD2/WAD3 19 | public int Dirs { get; set; } // Number of directory entries 20 | public int DirOffset { get; set; } // Offset into directory 21 | 22 | public override string ToString() 23 | { 24 | return string.Format("DirOffset: {0} Dirs: {1}", DirOffset, Dirs); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /BspViewer/Utils/ColorUtils.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Drawing; 3 | 4 | namespace BspViewer 5 | { 6 | public static class ColorUtils 7 | { 8 | private static readonly Random _random; 9 | 10 | static ColorUtils() 11 | { 12 | _random = new Random(); 13 | } 14 | 15 | /// 16 | /// Brush colours only vary from given mix 17 | /// 18 | public static Color GenerateRandomColor(Color mix) 19 | { 20 | int red = _random.Next(256); 21 | int green = _random.Next(256); 22 | int blue = _random.Next(256); 23 | 24 | if (mix != null) 25 | { 26 | red = (red + mix.R) / 2; 27 | green = (green + mix.G) / 2; 28 | blue = (blue + mix.B) / 2; 29 | } 30 | 31 | Color color = Color.FromArgb(red, green, blue); 32 | return color; 33 | } 34 | 35 | /// 36 | /// Brush colours only vary from shades of green and blue 37 | /// 38 | public static Color GenerateRandomBrushColour() 39 | { 40 | return Color.FromArgb(0, _random.Next(128, 256), _random.Next(128, 256)); 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /BspViewer/SourceMap/BspMap.cs: -------------------------------------------------------------------------------- 1 | using System.Drawing; 2 | 3 | namespace BspViewer 4 | { 5 | public sealed class BspMap 6 | { 7 | private string _name; 8 | 9 | public BspMap(string name) 10 | { 11 | _name = name; 12 | } 13 | 14 | public BspHeader Header { get; internal set; } 15 | public Entities Entities { get; internal set; } 16 | public BspModel[] Models { get; internal set; } 17 | public BspPlane[] Planes { get; internal set; } 18 | public BspFace[] Faces { get; internal set; } 19 | public BspVertex[] Vertices { get; internal set; } 20 | public BspEdge[] Edges { get; internal set; } 21 | public BspLeaf[] Leafs { get; internal set; } 22 | public BspNode[] Nodes { get; internal set; } 23 | public BspClipNode[] ClipNodes { get; internal set; } 24 | public short[] MarkSurfaces { get; internal set; } 25 | public int[] SurfEdges { get; internal set; } 26 | 27 | public BspTextureHeader TextureHeader { get; internal set; } 28 | public BspMipTexture[] MipTextures { get; internal set; } 29 | public BspTextureInfo[] TextureInfos { get; internal set; } 30 | 31 | public bool[][] VisList { get; internal set; } 32 | public Color[] FaceColors { get; internal set; } 33 | } 34 | } -------------------------------------------------------------------------------- /BspViewer/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // Allgemeine Informationen über eine Assembly werden über die folgenden 6 | // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, 7 | // die einer Assembly zugeordnet sind. 8 | [assembly: AssemblyTitle("BspViewer")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("BspViewer")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar 18 | // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von 19 | // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. 20 | [assembly: ComVisible(false)] 21 | 22 | // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird 23 | [assembly: Guid("1a5ef55a-96ff-4891-87ec-0d0fa0b15433")] 24 | 25 | // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: 26 | // 27 | // Hauptversion 28 | // Nebenversion 29 | // Buildnummer 30 | // Revision 31 | // 32 | [assembly: AssemblyVersion("1.0.0.0")] 33 | [assembly: AssemblyFileVersion("1.0.0.0")] 34 | 35 | [assembly: InternalsVisibleTo("BspViewer.Tests")] -------------------------------------------------------------------------------- /BspViewer.Desktop/Utils/MathLib.cs: -------------------------------------------------------------------------------- 1 | using OpenTK; 2 | using System; 3 | 4 | namespace BspViewer 5 | { 6 | sealed class MathLib 7 | { 8 | private const float EPSILON = 0.03125f; // 1/32 9 | 10 | public static Func DegToRad = (x) => ((x) * (float) Math.PI / 180.0f); 11 | public static Func RadToDeg = (x) => ((x) * 180.0f / (float) Math.PI); 12 | 13 | public static Vector3 RotateX(float a, Vector3 v) 14 | { 15 | a = DegToRad(a); 16 | 17 | Vector3 res; 18 | res.X = v.X; 19 | res.Y = v.Y * (float) Math.Cos(a) + v.Z * (float) -Math.Sin(a); 20 | res.Z = v.Y * (float) Math.Sin(a) + v.Z * (float) Math.Cos(a); 21 | return res; 22 | } 23 | 24 | public static Vector3 RotateY(float a, Vector3 v) 25 | { 26 | a = DegToRad(a); 27 | 28 | Vector3 res; 29 | res.X = v.X * (float) Math.Cos(a) + v.Z * (float) Math.Sin(a); 30 | res.Y = v.Y; 31 | res.Z = v.X * (float) -Math.Sin(a) + v.Z * (float) Math.Cos(a); 32 | return res; 33 | } 34 | 35 | public static Vector3 RotateZ(float a, Vector3 v) 36 | { 37 | a = DegToRad(a); 38 | 39 | Vector3 res; 40 | res.X = v.X * (float) Math.Cos(a) + v.Y * (float) -Math.Sin(a); 41 | res.Y = v.X * (float) Math.Sin(a) + v.Y * (float) Math.Cos(a); 42 | res.Z = v.Z; 43 | return res; 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /BspViewer.Tests/EntityTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System.Text; 3 | 4 | namespace BspViewer.Tests 5 | { 6 | [TestClass] 7 | public class EntityTests 8 | : TestBase 9 | { 10 | [TestMethod] 11 | [DataTestMethod] 12 | [DataRow("Entities.ValidEntites.txt")] 13 | public void TestReadValidEntities(string fileName) 14 | { 15 | // Given 16 | var validEntities = GetFileContents(fileName); 17 | var entitiesData = Encoding.ASCII.GetBytes(validEntities); 18 | 19 | // When 20 | var parser = new EntityParser(entitiesData); 21 | var entities = parser.Parse(); 22 | 23 | // Then 24 | Assert.IsNotNull(entities); 25 | Assert.IsTrue(entities.Count == 114); 26 | } 27 | 28 | [TestMethod] 29 | [DataTestMethod] 30 | [DataRow("Entities.InvalidEmptyEntity.txt")] 31 | [DataRow("Entities.InvalidEntity.txt")] 32 | public void TestReadInvalidEntity(string fileName) 33 | { 34 | // Given 35 | var invalidEntity = GetFileContents(fileName); 36 | var entityData = Encoding.ASCII.GetBytes(invalidEntity); 37 | 38 | // When 39 | var parser = new EntityParser(entityData); 40 | var entities = parser.Parse(); 41 | 42 | // Then 43 | Assert.IsNotNull(entities); 44 | Assert.IsTrue(entities.Count == 0); 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /BspViewer.Tests/WadTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System.IO; 3 | 4 | namespace BspViewer.Tests 5 | { 6 | [TestClass] 7 | public class WadTests 8 | : TestBase 9 | { 10 | // This TestClass consists more of IntegrationTests then UnitTests. 11 | // We should refactor this. 12 | 13 | [TestMethod] 14 | public void TestExportTextureToBitmap() 15 | { 16 | // Given 17 | var fileName = @"C:\Sierra\Half-Life\valve\maps\hldemo1.bsp"; 18 | var wadFileNames = new string[] { @"C:\Sierra\Half-Life\valve\halflife.wad" }; 19 | 20 | var loader = new BspLoader(fileName); 21 | var map = loader.Load(); 22 | 23 | var wadLoader = new WadLoader(map, fileName, wadFileNames); 24 | var textures = wadLoader.Load(); 25 | 26 | if (!Directory.Exists("Textures")) 27 | { 28 | Directory.CreateDirectory("Textures"); 29 | } 30 | 31 | // When 32 | foreach (var texture in textures) 33 | { 34 | using (var bitmap = TexUtil.PixelsToTexture(texture.TextureData, texture.Width, texture.Height, 4)) 35 | { 36 | bitmap.Save("Textures\\" + texture.Name + ".bmp"); 37 | } 38 | } 39 | 40 | // Then 41 | foreach (var texture in textures) 42 | { 43 | var isExisting = File.Exists("Textures\\" + texture.Name + ".bmp"); 44 | 45 | Assert.IsTrue(isExisting); 46 | } 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /BspViewer.Desktop/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // Allgemeine Informationen über eine Assembly werden über die folgenden 6 | // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, 7 | // die einer Assembly zugeordnet sind. 8 | [assembly: AssemblyTitle("BspViewer.Desktop")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("BspViewer.Desktop")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly 18 | // für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von 19 | // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. 20 | [assembly: ComVisible(false)] 21 | 22 | // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird 23 | [assembly: Guid("73145abe-a2ec-40b2-b769-b54da4cb53a2")] 24 | 25 | // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: 26 | // 27 | // Hauptversion 28 | // Nebenversion 29 | // Buildnummer 30 | // Revision 31 | // 32 | // Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, 33 | // übernehmen, indem Sie "*" eingeben: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /BspViewer.Desktop/Properties/OpenTK.dll.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BspViewer 2 | 3 | ![](https://img.shields.io/badge/.net-v4.5.2-blue.svg) 4 | ![](https://img.shields.io/badge/build-passing-green.svg) 5 | 6 | Rendering BSP v30 files from Halflife and it's modifications. (CSTRIKE, TFC, VALVE) 7 | 8 | ![BspViewer](https://github.com/PSneijder/BspViewer/blob/master/Assets/BspViewer.gif) 9 | 10 | ## Reasons 11 | In November of 1998, I first played Half-Life and loved it! Since then I became interested in first person shooter games and in particular how the levels are created and rendered in real time. I found myself in between jobs and so I embarked on an effort to learn about 3D rendering with the goal of creating my own 3D rendering engine. Since I am a developer and not an artist I didn't have the skills to create my own models, levels, and textures. So I decided to attempt to write a rendering engine that would render existing game levels. I mainly used information and articles I found on the web about Quake 2, Half Life, WAD and BSP files. The Half-Life SDK and a lot of C++ projects floating around the web were useful resources too. 12 | 13 | ## Controls 14 | ``` 15 | W Move forward 16 | S Move backward 17 | A Move sidewards left (strafe) 18 | D Move sidewards right (strafe) 19 | E or Space/Shift Move up 20 | Q or Ctrl Move down 21 | 22 | Left Rotate left 23 | Right Rotate right 24 | Up Look up 25 | Down Look down 26 | ``` 27 | 28 | ## TODOs 29 | * Reading BSP and WAD3 files 30 | * Binary-Space-Partition 31 | * Render BSP 32 | * Free-Look-Camera 33 | * Potentially-Visible-Set (PVS - to significantly improve rendering performance) 34 | * Textures 35 | * Collision Detection 36 | * Shaders 37 | 38 | ## Recent Changes 39 | See [CHANGES.txt](CHANGES.txt) 40 | 41 | ## Committers 42 | * [Philip Schneider](https://github.com/PSneijder) 43 | 44 | ## Licensing 45 | The license for the code is [ALv2](http://www.apache.org/licenses/LICENSE-2.0.html). 46 | -------------------------------------------------------------------------------- /BspViewer/Utils/TexUtil.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Drawing; 3 | using System.Drawing.Imaging; 4 | using System.Runtime.InteropServices; 5 | 6 | namespace BspViewer 7 | { 8 | public static class TexUtil 9 | { 10 | public static Bitmap PixelsToTexture(uint[] pixelData, int width, int height, int channels) 11 | { 12 | var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); 13 | var boundsRect = new Rectangle(0, 0, width, height); 14 | 15 | BitmapData bmpData = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat); 16 | IntPtr pointer = bmpData.Scan0; 17 | int bytes = bmpData.Stride * bitmap.Height; 18 | 19 | var imgData = new byte[bytes]; 20 | for (var x = 0; x < width; x++) 21 | { 22 | for (var y = 0; y < height; y++) 23 | { 24 | var dataIndex = (x + y * width) * 4; 25 | var pixelIndex = (x + y * width) * channels; 26 | imgData[dataIndex + 0] = (byte)pixelData[pixelIndex + 0]; 27 | imgData[dataIndex + 1] = (byte)pixelData[pixelIndex + 1]; 28 | imgData[dataIndex + 2] = (byte)pixelData[pixelIndex + 2]; 29 | 30 | if (channels == 4) 31 | imgData[dataIndex + 3] = (byte)pixelData[pixelIndex + 3]; 32 | else 33 | imgData[dataIndex + 3] = 255; 34 | } 35 | } 36 | 37 | Marshal.Copy(imgData, 0, pointer, bytes); 38 | bitmap.UnlockBits(bmpData); 39 | 40 | return bitmap; 41 | } 42 | 43 | public static bool IsPowerOfTwo(int x) 44 | { 45 | return (x & (x - 1)) == 0; 46 | } 47 | 48 | public static int NextHighestPowerOfTwo(int x) 49 | { 50 | --x; 51 | for (var i = 1; i < 32; i <<= 1) 52 | x = x | x >> i; 53 | return x + 1; 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /BspViewer/SourceMap/BspDefs.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace BspViewer 3 | { 4 | public static class BspDefs 5 | { 6 | public const int CONTENTS_EMPTY = -1; 7 | public const int CONTENTS_SOLID = -2; 8 | public const int CONTENTS_WATER = -3; 9 | public const int CONTENTS_SLIME = -4; 10 | public const int CONTENTS_LAVA = -5; 11 | public const int CONTENTS_SKY = -6; 12 | public const int CONTENTS_ORIGIN = -7; 13 | public const int CONTENTS_CLIP = -8; 14 | public const int CONTENTS_CURRENT_0 = -9; 15 | public const int CONTENTS_CURRENT_90 = -10; 16 | public const int CONTENTS_CURRENT_180 = -11; 17 | public const int CONTENTS_CURRENT_270 = -12; 18 | public const int CONTENTS_CURRENT_UP = -13; 19 | public const int CONTENTS_CURRENT_DOWN = -14; 20 | public const int CONTENTS_TRANSLUCENT = -15; 21 | 22 | public const int LUMP_ENTITIES = 0; 23 | public const int LUMP_PLANES = 1; 24 | public const int LUMP_TEXTURES = 2; 25 | public const int LUMP_VERTEXES = 3; 26 | public const int LUMP_VISIBILITY = 4; 27 | public const int LUMP_NODES = 5; 28 | public const int LUMP_TEXINFO = 6; 29 | public const int LUMP_FACES = 7; 30 | public const int LUMP_LIGHTING = 8; 31 | public const int LUMP_CLIPNODES = 9; 32 | public const int LUMP_LEAFS = 10; 33 | public const int LUMP_MARKSURFACES = 11; 34 | public const int LUMP_EDGES = 12; 35 | public const int LUMP_SURFEDGES = 13; 36 | public const int LUMP_MODELS = 14; 37 | public const int HEADER_LUMPS = 15; 38 | 39 | public const int MAXLIGHTMAPS = 4; 40 | 41 | public const int PLANE_X = 0; // Plane is perpendicular to given axis 42 | public const int PLANE_Y = 1; 43 | public const int PLANE_Z = 2; 44 | public const int PLANE_ANYX = 3; // Non-axial plane is snapped to the nearest 45 | public const int PLANE_ANYY = 4; 46 | public const int PLANE_ANYZ = 5; 47 | } 48 | } -------------------------------------------------------------------------------- /BspViewer.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26228.4 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BspViewer", "BspViewer\BspViewer.csproj", "{CF9AB6E2-8E15-4915-820D-2D0D8F365CBF}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BspViewer.Desktop", "BspViewer.Desktop\BspViewer.Desktop.csproj", "{73145ABE-A2EC-40B2-B769-B54DA4CB53A2}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BspViewer.Tests", "BspViewer.Tests\BspViewer.Tests.csproj", "{E460C57D-2707-4B78-8C74-831F064E3B39}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {CF9AB6E2-8E15-4915-820D-2D0D8F365CBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {CF9AB6E2-8E15-4915-820D-2D0D8F365CBF}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {CF9AB6E2-8E15-4915-820D-2D0D8F365CBF}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {CF9AB6E2-8E15-4915-820D-2D0D8F365CBF}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {73145ABE-A2EC-40B2-B769-B54DA4CB53A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {73145ABE-A2EC-40B2-B769-B54DA4CB53A2}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {73145ABE-A2EC-40B2-B769-B54DA4CB53A2}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {73145ABE-A2EC-40B2-B769-B54DA4CB53A2}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {E460C57D-2707-4B78-8C74-831F064E3B39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {E460C57D-2707-4B78-8C74-831F064E3B39}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {E460C57D-2707-4B78-8C74-831F064E3B39}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {E460C57D-2707-4B78-8C74-831F064E3B39}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | EndGlobal 35 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /BspViewer/BspViewer.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {CF9AB6E2-8E15-4915-820D-2D0D8F365CBF} 8 | Library 9 | BspViewer 10 | BspViewer 11 | v4.5.2 12 | 512 13 | true 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | false 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /BspViewer/Extensions/BinaryReaderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Linq; 3 | using System.Text; 4 | 5 | namespace BspViewer.Extensions 6 | { 7 | internal static class BinaryReaderExtensions 8 | { 9 | public static float[] ReadSingleArray(this BinaryReader reader, int count = 3) 10 | { 11 | float[] floats = new float[count]; 12 | 13 | for (int i = 0; i < count; i++) 14 | { 15 | floats[i] = reader.ReadSingle(); 16 | } 17 | 18 | return floats; 19 | } 20 | 21 | public static uint[] ReadUInt8Array(this BinaryReader reader, long offset, int count) 22 | { 23 | reader.BaseStream.Seek(offset, SeekOrigin.Begin); 24 | 25 | uint[] integers = new uint[count]; 26 | 27 | for (int i = 0; i < count; i++) 28 | { 29 | integers[i] = reader.ReadByte(); 30 | } 31 | 32 | return integers; 33 | } 34 | 35 | public static int[] ReadInt32Array(this BinaryReader reader, int count = 3) 36 | { 37 | int[] integers = new int[count]; 38 | 39 | for (int i = 0; i < count; i++) 40 | { 41 | integers[i] = reader.ReadInt32(); 42 | } 43 | 44 | return integers; 45 | } 46 | 47 | public static short[] ReadInt16Array(this BinaryReader reader, int count = 3) 48 | { 49 | short[] shorts = new short[count]; 50 | 51 | for (int i = 0; i < count; i++) 52 | { 53 | shorts[i] = reader.ReadInt16(); 54 | } 55 | 56 | return shorts; 57 | } 58 | 59 | public static uint[] ReadUInt32Array(this BinaryReader reader, int count = 3) 60 | { 61 | uint[] integers = new uint[count]; 62 | 63 | for (int i = 0; i < count; i++) 64 | { 65 | integers[i] = reader.ReadUInt32(); 66 | } 67 | 68 | return integers; 69 | } 70 | 71 | public static ushort[] ReadUInt16Array(this BinaryReader reader, int count = 2) 72 | { 73 | ushort[] shorts = new ushort[count]; 74 | 75 | for (int i = 0; i < count; i++) 76 | { 77 | shorts[i] = reader.ReadUInt16(); 78 | } 79 | 80 | return shorts; 81 | } 82 | 83 | public static string ReadString(this BinaryReader reader, int count = 16) 84 | { 85 | byte[] bytes = reader.ReadBytes(count); 86 | 87 | if (bytes == null) 88 | { 89 | return null; 90 | } 91 | 92 | char[] dirtyCharacters = Encoding.UTF8.GetChars(bytes); 93 | 94 | char[] cleanedCharacters = dirtyCharacters 95 | .Where(c => !char.IsControl(c)) 96 | .ToArray(); 97 | 98 | return new string(cleanedCharacters); 99 | } 100 | } 101 | } -------------------------------------------------------------------------------- /BspViewer.Desktop/BspViewer.Desktop.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {73145ABE-A2EC-40B2-B769-B54DA4CB53A2} 8 | WinExe 9 | BspViewer.Desktop 10 | BspViewer.Desktop 11 | v4.5.2 12 | 512 13 | true 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | 37 | 38 | 39 | ..\packages\OpenTK.2.0.0\lib\net20\OpenTK.dll 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | {cf9ab6e2-8e15-4915-820d-2d0d8f365cbf} 67 | BspViewer 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /BspViewer/SourceEntity/EntityParser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace BspViewer 5 | { 6 | sealed class EntityParser 7 | : List 8 | { 9 | private byte[] _data; 10 | 11 | public EntityParser(byte[] data) 12 | { 13 | _data = data; 14 | } 15 | 16 | public Entities Parse() 17 | { 18 | // Keep track of whether or not we're currently in a set of quotation marks. 19 | // I came across a map where the idiot map maker used { and } within a value. This broke the code before. 20 | bool inQuotes = false; 21 | int braceCount = 0; 22 | 23 | // The current character being read in the file. This is necessary because 24 | // we need to know exactly when the { and } characters occur and capture 25 | // all text between them. 26 | char currentChar; 27 | // This will be the resulting entity, fed into Entity.FromString 28 | System.Text.StringBuilder current = new System.Text.StringBuilder(); 29 | 30 | for (int offset = 0; offset < _data.Length; ++offset) 31 | { 32 | currentChar = (char) _data[offset]; 33 | 34 | // Allow for escape-sequenced quotes to not affect the state machine. 35 | if (currentChar == '\"' && (offset == 0 || (char) _data[offset - 1] != '\\')) 36 | { 37 | inQuotes = !inQuotes; 38 | } 39 | 40 | if (!inQuotes) 41 | { 42 | if (currentChar == '{') 43 | { 44 | // Occasionally, texture paths have been known to contain { or }. Since these aren't always contained 45 | // in quotes, we must be a little more precise about how we want to select our delimiters. 46 | // As a general rule, though, making sure we're not in quotes is still very effective at error prevention. 47 | if (offset == 0 || (char) _data[offset - 1] == '\n' || (char) _data[offset - 1] == '\t' || (char) _data[offset - 1] == ' ' || (char) _data[offset - 1] == '\r') 48 | { 49 | ++braceCount; 50 | } 51 | } 52 | } 53 | 54 | if (braceCount > 0) 55 | { 56 | current.Append(currentChar); 57 | } 58 | 59 | if (!inQuotes) 60 | { 61 | if (currentChar == '}') 62 | { 63 | if (offset == 0 || (char) _data[offset - 1] == '\n' || (char) _data[offset - 1] == '\t' || (char) _data[offset - 1] == ' ' || (char) _data[offset - 1] == '\r') 64 | { 65 | --braceCount; 66 | if (braceCount == 0) 67 | { 68 | Add(Entity.FromString(current.ToString())); 69 | 70 | // Reset StringBuilder 71 | current.Length = 0; 72 | } 73 | } 74 | } 75 | } 76 | } 77 | 78 | if (braceCount != 0) 79 | { 80 | throw new ArgumentException(string.Format("Brace mismatch when parsing entities! Brace level: {0}", braceCount)); 81 | } 82 | 83 | return new Entities(this); 84 | } 85 | } 86 | } -------------------------------------------------------------------------------- /BspViewer.Desktop/Viewer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using OpenTK; 3 | using OpenTK.Graphics; 4 | using OpenTK.Graphics.OpenGL; 5 | using OpenTK.Input; 6 | using BspViewer.Extensions; 7 | using System.IO; 8 | 9 | namespace BspViewer 10 | { 11 | sealed class Viewer 12 | : GameWindow 13 | { 14 | private Renderer _renderer; 15 | private Camera _camera; 16 | 17 | public Viewer() 18 | : base(640, 480, GraphicsMode.Default, AppDomain.CurrentDomain.FriendlyName) 19 | { 20 | VSync = VSyncMode.On; 21 | 22 | CursorVisible = false; 23 | } 24 | 25 | protected override void OnLoad(EventArgs e) 26 | { 27 | base.OnLoad(e); 28 | 29 | //var fileName = @"C:\Sierra\Half-Life\valve\maps\hldemo1.bsp"; 30 | //var wadFileNames = new string[] { @"C:\Sierra\Half-Life\valve\halflife.wad" }; 31 | 32 | var wadPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\..\Assets\Wads\", "SampleWad.wad")); 33 | var fileName = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\..\Assets\Maps\", "SampleMap.bsp")); 34 | var wadFileNames = new string[] { Path.Combine(wadPath) }; 35 | 36 | var loader = new BspLoader(fileName); 37 | var map = loader.Load(); 38 | 39 | var wadLoader = new WadLoader(map, fileName, wadFileNames); 40 | var textures = wadLoader.Load(); 41 | 42 | _renderer = new Renderer(map, textures); 43 | _camera = new Camera(this); 44 | 45 | float[] origin = map.Entities["info_player_start"]["origin"].AsSingleArray(); 46 | _camera.SetPosition(origin[0], origin[1], origin[2]); 47 | 48 | float[] angles = map.Entities["info_player_start"]["angles"].AsSingleArray(); 49 | _camera.SetViewAngles(angles[0], angles[1]); 50 | 51 | InitGL(); 52 | } 53 | 54 | protected override void OnResize(EventArgs e) 55 | { 56 | base.OnResize(e); 57 | 58 | GL.Viewport(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width, ClientRectangle.Height); 59 | 60 | GL.MatrixMode(MatrixMode.Projection); 61 | GL.LoadIdentity(); 62 | 63 | Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView((float)((Math.PI * 60.0f) / 180.0f), Width / Height, 8.0f, 4000.0f); 64 | GL.LoadMatrix(ref projection); 65 | 66 | GL.MatrixMode(MatrixMode.Modelview); 67 | GL.LoadIdentity(); 68 | } 69 | 70 | protected override void OnUpdateFrame(FrameEventArgs e) 71 | { 72 | base.OnUpdateFrame(e); 73 | 74 | _camera.Update(e.Time); 75 | 76 | if (Keyboard[Key.Escape]) 77 | { 78 | Exit(); 79 | } 80 | } 81 | 82 | protected override void OnRenderFrame(FrameEventArgs e) 83 | { 84 | base.OnRenderFrame(e); 85 | 86 | GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); 87 | GL.LoadIdentity(); 88 | 89 | _camera.Look(); 90 | 91 | _renderer.Render(_camera.Position); 92 | 93 | SwapBuffers(); 94 | } 95 | 96 | private void InitGL() 97 | { 98 | GL.ShadeModel(ShadingModel.Smooth); // Enable Smooth Shading 99 | GL.ClearColor(Color4.CornflowerBlue); // Blue Background 100 | GL.ClearDepth(1.0f); // Depth Buffer Setup 101 | GL.DepthFunc(DepthFunction.Lequal); // The Type Of Depth Testing To Do 102 | 103 | GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest); 104 | GL.Hint(HintTarget.PointSmoothHint, HintMode.Nicest); 105 | GL.Hint(HintTarget.LineSmoothHint, HintMode.Nicest); 106 | GL.Hint(HintTarget.PolygonSmoothHint, HintMode.Nicest); 107 | 108 | GL.CullFace(CullFaceMode.Front); 109 | 110 | GL.Enable(EnableCap.CullFace); 111 | GL.Enable(EnableCap.Multisample); 112 | } 113 | } 114 | } -------------------------------------------------------------------------------- /BspViewer/SourceMap/BspRenderer.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace BspViewer 3 | { 4 | struct FaceCoord 5 | { 6 | public float Vec3s { get; set; } 7 | public float Vec3t { get; set; } 8 | } 9 | 10 | public abstract class BspRenderer 11 | { 12 | protected BspMap Map { get; private set; } 13 | 14 | protected BspRenderer(BspMap map) 15 | { 16 | Map = map; 17 | } 18 | 19 | #region BSP Traversal 20 | 21 | protected int TraverseTree(BspVector position, int nodeIndex) 22 | { 23 | var node = Map.Nodes[nodeIndex]; 24 | 25 | // Run once for each child 26 | for (int i = 0; i < 2; i++) 27 | { 28 | // If the index is positive it is an index into the nodes array 29 | if ((node.Children[i]) >= 0) 30 | { 31 | if (PointInBox(position, Map.Nodes[node.Children[i]].Mins, Map.Nodes[node.Children[i]].Maxs)) 32 | return TraverseTree(position, node.Children[i]); 33 | } 34 | // Else, bitwise inversed, it is an index into the leaf array 35 | // Do not test solid leaf 0 36 | else if (~node.Children[i] != 0) 37 | { 38 | if (PointInBox(position, Map.Leafs[~(node.Children[i])].Mins, Map.Leafs[~(node.Children[i])].Maxs)) 39 | return ~(node.Children[i]); 40 | } 41 | } 42 | 43 | return -1; 44 | } 45 | 46 | private bool PointInBox(BspVector vPoint, short[] vMin, short[] vMax) 47 | { 48 | if (vMin[0] <= vPoint.X && vPoint.X <= vMax[0] && 49 | vMin[1] <= vPoint.Y && vPoint.Y <= vMax[1] && 50 | vMin[2] <= vPoint.Z && vPoint.Z <= vMax[2] || 51 | vMin[0] >= vPoint.X && vPoint.X >= vMax[0] && 52 | vMin[1] >= vPoint.Y && vPoint.Y >= vMax[1] && 53 | vMin[2] >= vPoint.Z && vPoint.Z >= vMax[2]) 54 | return true; 55 | else 56 | return false; 57 | } 58 | 59 | #endregion 60 | 61 | #region BSP Rendering 62 | 63 | protected virtual void RenderLevel(BspVector cameraPos) 64 | { 65 | // Get the leaf where the camera is in 66 | int cameraLeaf = TraverseTree(cameraPos, 0); 67 | 68 | // Start the render traversal on the static geometry 69 | RenderNode(0, cameraLeaf, cameraPos); 70 | } 71 | 72 | protected void RenderNode(int nodeIndex, int cameraLeaf, BspVector cameraPos) 73 | { 74 | if (nodeIndex < 0) 75 | { 76 | if (nodeIndex == -1) // Solid leaf 0 77 | return; 78 | 79 | if (cameraLeaf > 0) 80 | if (Map.Header.Lumps[BspDefs.LUMP_VISIBILITY].Length != 0 81 | && Map.VisList != null 82 | && Map.VisList[cameraLeaf - 1] != null 83 | && !Map.VisList[cameraLeaf - 1][~nodeIndex - 1]) 84 | return; 85 | 86 | RenderLeaf(~nodeIndex); 87 | 88 | return; 89 | } 90 | 91 | float distance; 92 | 93 | var node = Map.Nodes[nodeIndex]; 94 | var plane = Map.Planes[node.PlaneId]; 95 | 96 | switch (plane.Type) 97 | { 98 | case BspDefs.PLANE_X: 99 | distance = cameraPos.X - plane.Distance; 100 | break; 101 | case BspDefs.PLANE_Y: 102 | distance = cameraPos.Y - plane.Distance; 103 | break; 104 | case BspDefs.PLANE_Z: 105 | distance = cameraPos.Z - plane.Distance; 106 | break; 107 | default: 108 | var normal = plane.Normal; 109 | distance = DotProduct(new BspVector(normal[0], normal[1], normal[2]), cameraPos) - plane.Distance; 110 | break; 111 | } 112 | 113 | if (distance > 0.0f) 114 | { 115 | RenderNode(node.Children[1], cameraLeaf, cameraPos); 116 | RenderNode(node.Children[0], cameraLeaf, cameraPos); 117 | } 118 | else 119 | { 120 | RenderNode(node.Children[0], cameraLeaf, cameraPos); 121 | RenderNode(node.Children[1], cameraLeaf, cameraPos); 122 | } 123 | } 124 | 125 | private void RenderLeaf(int leafIndex) 126 | { 127 | var leaf = Map.Leafs[leafIndex]; 128 | 129 | // Loop through each face in this leaf 130 | for (int i = 0; i < leaf.NumMarkSurfaces; i++) 131 | RenderFace(Map.MarkSurfaces[leaf.FirstMarkSurface + i]); 132 | } 133 | 134 | protected abstract void RenderFace(int faceIndex); 135 | 136 | protected float DotProduct(BspVector v1, BspVector v2) 137 | { 138 | return (v1.X * v2.X) + (v1.Y * v2.Y) + (v1.Z * v2.Z); 139 | } 140 | 141 | #endregion 142 | } 143 | } -------------------------------------------------------------------------------- /BspViewer.Tests/BspViewer.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {E460C57D-2707-4B78-8C74-831F064E3B39} 8 | Library 9 | Properties 10 | BspViewer.Tests 11 | BspViewer.Tests 12 | v4.5.2 13 | 512 14 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 15 | 15.0 16 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 17 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 18 | False 19 | UnitTest 20 | 21 | 22 | 23 | 24 | true 25 | full 26 | false 27 | bin\Debug\ 28 | DEBUG;TRACE 29 | prompt 30 | 4 31 | 32 | 33 | pdbonly 34 | true 35 | bin\Release\ 36 | TRACE 37 | prompt 38 | 4 39 | 40 | 41 | 42 | ..\packages\MSTest.TestFramework.1.1.11\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll 43 | 44 | 45 | ..\packages\MSTest.TestFramework.1.1.11\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | {cf9ab6e2-8e15-4915-820d-2d0d8f365cbf} 63 | BspViewer 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | Dieses Projekt verweist auf mindestens ein NuGet-Paket, das auf diesem Computer fehlt. Verwenden Sie die Wiederherstellung von NuGet-Paketen, um die fehlenden Dateien herunterzuladen. Weitere Informationen finden Sie unter "http://go.microsoft.com/fwlink/?LinkID=322105". Die fehlende Datei ist "{0}". 78 | 79 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /BspViewer.Desktop/Components/Camera.cs: -------------------------------------------------------------------------------- 1 | using OpenTK; 2 | using OpenTK.Graphics.OpenGL; 3 | using OpenTK.Input; 4 | using System; 5 | 6 | namespace BspViewer 7 | { 8 | sealed class Camera 9 | { 10 | public Vector3 Position { get; private set; } 11 | 12 | private MouseDevice _mouse; 13 | private KeyboardDevice _keyboard; 14 | 15 | private bool _captureMouse = false; // When set to true, the mouse is tracked by the camera 16 | 17 | private float _lastX; 18 | private float _lastY; 19 | 20 | private float _pitch = 0.0f; 21 | private float _yaw = 0.0f; 22 | 23 | private float _lookSens = 0.25f; // Look sensitivity. Applies to mouse movement 24 | private float _moveSens = 500f; // Move sensitivity. Applies to keyboard movement 25 | 26 | private int _width; 27 | private int _height; 28 | 29 | public Camera(GameWindow game) 30 | { 31 | _mouse = game.Mouse; 32 | _keyboard = game.Keyboard; 33 | 34 | _width = game.ClientRectangle.Width; 35 | _height = game.ClientRectangle.Height; 36 | 37 | Position = new Vector3(0, 0, 0); 38 | } 39 | 40 | public void SetPosition(float x, float y, float z) 41 | { 42 | Position = new Vector3(x, y, z); 43 | } 44 | 45 | public void SetViewAngles(float pitch, float yaw) 46 | { 47 | _pitch = pitch; 48 | _yaw = yaw; 49 | } 50 | 51 | public void Update(double interval) 52 | { 53 | if (_captureMouse) 54 | { 55 | var x = _mouse.X; 56 | var y = _mouse.Y; 57 | 58 | // Update rotation based on mouse input 59 | _yaw += _lookSens * (_lastX - x); 60 | 61 | // Correct z angle to interval [0;360] 62 | if (_yaw >= 360.0) 63 | _yaw -= 360.0f; 64 | 65 | if (_yaw < 0.0) 66 | _yaw += 360.0f; 67 | 68 | // Update up down view 69 | _pitch += _lookSens * (_lastY - y); 70 | 71 | // Correct x angle to interval [-90;90] 72 | if (_pitch < -90.0) 73 | _pitch = -90.0f; 74 | 75 | if (_pitch > 90.0) 76 | _pitch = 90.0f; 77 | 78 | // Reset track point 79 | _lastX = x; 80 | _lastY = y; 81 | } 82 | 83 | var moveFactor = _moveSens * (float) interval; 84 | var oldPos = new Vector3(Position); 85 | var newPos = new Vector3(Position); 86 | 87 | if (_keyboard[Key.E] || _keyboard[Key.Space]) // E or SPACE - UP 88 | { 89 | newPos.Z += moveFactor; 90 | } 91 | 92 | if (_keyboard[Key.Q] || _keyboard[Key.LControl]) // Q or CRTL - DOWN 93 | { 94 | newPos.Z -= moveFactor; 95 | } 96 | 97 | // If strafing and moving reduce speed to keep total move per frame constant 98 | var strafing = (_keyboard[Key.W] || _keyboard[Key.S]) && (_keyboard[Key.A] || _keyboard[Key.D]); 99 | 100 | if (strafing) 101 | moveFactor = (float) Math.Sqrt((moveFactor * moveFactor) / 2.0); 102 | 103 | if (_keyboard[Key.W]) // W - FORWARD 104 | { 105 | newPos.X += (float) Math.Cos(MathLib.DegToRad(_yaw)) * moveFactor; 106 | newPos.Y += (float) Math.Sin(MathLib.DegToRad(_yaw)) * moveFactor; 107 | } 108 | 109 | if (_keyboard[Key.S]) // S - BACKWARD 110 | { 111 | newPos.X -= (float) Math.Cos(MathLib.DegToRad(_yaw)) * moveFactor; 112 | newPos.Y -= (float) Math.Sin(MathLib.DegToRad(_yaw)) * moveFactor; 113 | } 114 | 115 | if (_keyboard[Key.A]) // A - LEFT 116 | { 117 | newPos.X += (float) Math.Cos(MathLib.DegToRad(_yaw + 90.0f)) * moveFactor; 118 | newPos.Y += (float) Math.Sin(MathLib.DegToRad(_yaw + 90.0f)) * moveFactor; 119 | } 120 | 121 | if (_keyboard[Key.D]) // D - RIGHT 122 | { 123 | newPos.X += (float) Math.Cos(MathLib.DegToRad(_yaw - 90.0f)) * moveFactor; 124 | newPos.Y += (float) Math.Sin(MathLib.DegToRad(_yaw - 90.0f)) * moveFactor; 125 | } 126 | 127 | if (_keyboard[Key.Up]) // UP - ROTATE UP 128 | { 129 | _pitch += (moveFactor / 3); 130 | } 131 | 132 | if (_keyboard[Key.Down]) // DOWN - ROTATE DOWN 133 | { 134 | _pitch -= (moveFactor / 3); 135 | } 136 | 137 | if (_keyboard[Key.Left]) // LEFT - ROTATE LEFT 138 | { 139 | _yaw += (moveFactor / 3); 140 | } 141 | 142 | if (_keyboard[Key.Right]) // RIGHT - ROTATE RIGHT 143 | { 144 | _yaw -= (moveFactor / 3); 145 | } 146 | 147 | Position = newPos; 148 | } 149 | 150 | public void Look() 151 | { 152 | // In BSP v30 the z axis points up and we start looking parallel to x axis. 153 | 154 | // Look Up/Down 155 | GL.Rotate(-_pitch - 90.0, 1, 0, 0); 156 | 157 | // Look Left/Right 158 | GL.Rotate(-_yaw + 90.0, 0, 0, 1); 159 | 160 | // Move 161 | GL.Translate(-Position.X, -Position.Y, -Position.Z); 162 | } 163 | } 164 | } -------------------------------------------------------------------------------- /BspViewer/SourceMap/BspLumps.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | 3 | namespace BspViewer 4 | { 5 | public struct BspLump 6 | { 7 | public int Offset { get; set; } // File offset to data 8 | public int Length { get; set; } // Length of data 9 | 10 | public override string ToString() 11 | { 12 | return string.Format("Offset: {0} Size: {1}", Offset, Length); 13 | } 14 | } 15 | 16 | public struct BspHeader 17 | { 18 | public int Version { get; set; } 19 | public BspLump[] Lumps { get; set; } 20 | } 21 | 22 | public struct BspPlane 23 | { 24 | public static readonly int SizeInBytes = 20; 25 | 26 | public float[] Normal { get; set; } // The planes normal vector 27 | public float Distance { get; set; } // Plane equation is: vNormal * X = fDist 28 | public int Type { get; set; } // Plane type, see #defines 29 | } 30 | 31 | public struct BspFace 32 | { 33 | public static readonly int SizeInBytes = 20; 34 | 35 | public short PlaneId { get; set; } // Plane the face is parallel to 36 | public short PlaneSide { get; set; } // Set if different normals orientation 37 | public int FirstEdge { get; set; } // Index of the first surfedge 38 | public short NumEdges { get; set; } // Number of consecutive surfedges 39 | public short TextureInfo { get; set; } // Index of the texture info structure 40 | public byte[] Styles { get; set; } // Specify lighting styles 41 | public int LightmapOffset { get; set; } // Offsets into the raw lightmap data 42 | } 43 | 44 | public struct BspVertex 45 | { 46 | public static readonly int SizeInBytes = 12; 47 | 48 | public float[] Point { get; set; } 49 | } 50 | 51 | public struct BspEdge 52 | { 53 | public static readonly int SizeInBytes = 4; 54 | 55 | public ushort[] Vertices { get; set; } // Indices into vertex array 56 | } 57 | 58 | public struct BspLeaf 59 | { 60 | public static readonly int SizeInBytes = 28; 61 | 62 | public int Contents { get; set; } // Contents enumeration 63 | public int VisOffset { get; set; } // Offset into the visibility lump 64 | public short[] Mins { get; set; } // Defines bounding box 65 | public short[] Maxs { get; set; } 66 | public ushort FirstMarkSurface { get; set; } // Index and count into marksurfaces array 67 | public ushort NumMarkSurfaces { get; set; } 68 | public byte[] AmbientLevels { get; set; } // Ambient sound levels 69 | public BitArray Pvs { get; set; } 70 | } 71 | 72 | public struct BspNode 73 | { 74 | public static readonly int SizeInBytes = 24; 75 | 76 | public int PlaneId { get; set; } // Index into Planes lump 77 | public short[] Children { get; set; } // If > 0, then indices into Nodes // otherwise bitwise inverse indices into Leafs 78 | public short[] Mins { get; set; } // Defines bounding box 79 | public short[] Maxs { get; set; } 80 | public ushort FirstFace { get; set; } // Index and count into Faces 81 | public ushort NumFaces { get; set; } 82 | } 83 | 84 | public struct BspClipNode 85 | { 86 | public static readonly int SizeInBytes = 8; 87 | 88 | public int PlaneId { get; set; } // Index into Planes lump 89 | public short[] Children { get; set; } // negative numbers are contents 90 | } 91 | 92 | public struct BspVisData 93 | { 94 | public byte[] CompressedVis { get; set; } 95 | } 96 | 97 | public struct BspModel 98 | { 99 | public float[] Mins { get; set; } // Defines bounding box 100 | public float[] Maxs { get; set; } // Defines bounding box 101 | public float[] Origin { get; set; } // Coordinates to move the // coordinate system 102 | public int[] Nodes { get; set; } // [0] index of first BSP node, [1] index of the first Clip node, [2] index of the second Clip node, [3] usually zero 103 | public int NumLeafs { get; set; } // number of BSP leaves 104 | public int FirstFace { get; set; } 105 | public int NumFaces { get; set; } // Index and count into faces lump 106 | } 107 | 108 | public struct BspMipTexture 109 | { 110 | public string Name { get; set; } // Name of texture 111 | public uint Width { get; set; } // Extends of the texture 112 | public uint Height { get; set; } 113 | public uint[] Offsets { get; set; } // Offsets to texture mipmaps BSPMIPTEX; 114 | 115 | public override string ToString() 116 | { 117 | return string.Format("{0} {1} {2}", Name, Width, Height); 118 | } 119 | } 120 | 121 | public struct BspTextureInfo 122 | { 123 | public float[] Vec3s { get; set; } 124 | public float SShift { get; set; } // Texture shift in s direction 125 | public float[] Vec3t { get; set; } 126 | public float TShift { get; set; } // Texture shift in t direction 127 | public uint MipTex { get; set; } // Index into textures array 128 | public uint Flags { get; set; } // Texture flags, seem to always be 0 129 | } 130 | 131 | public struct BspTextureHeader 132 | { 133 | public int NumberMipTextures { get; set; } 134 | public int[] Offsets { get; set; } 135 | } 136 | 137 | public struct BspVector 138 | { 139 | public BspVector(float x, float y, float z) 140 | : this() 141 | { 142 | X = x; 143 | Y = y; 144 | Z = z; 145 | } 146 | 147 | public float X { get; set; } 148 | public float Y { get; set; } 149 | public float Z { get; set; } 150 | } 151 | 152 | public struct BspTextureData 153 | { 154 | public BspTextureData(uint[] textureData, int width, int height, string name) 155 | : this() 156 | { 157 | TextureData = textureData; 158 | Width = width; 159 | Height = height; 160 | Name = name; 161 | } 162 | 163 | public uint[] TextureData { get; private set; } 164 | public int Width { get; private set; } 165 | public int Height { get; private set; } 166 | public string Name { get; private set; } 167 | } 168 | } -------------------------------------------------------------------------------- /BspViewer/SourceEntity/Entity.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace BspViewer 4 | { 5 | public sealed class Entity 6 | : Dictionary 7 | { 8 | public const char ConnectionMemberSeparater = (char)0x1B; 9 | 10 | public Entity(string[] lines) 11 | { 12 | int braceCount = 0; 13 | 14 | bool inConnections = false; 15 | bool inBrush = false; 16 | 17 | List child = new List(); 18 | 19 | foreach (string line in lines) 20 | { 21 | string current = line.Trim(' ', '\t', '\r'); 22 | 23 | // Cull everything after a // 24 | bool inQuotes = false; 25 | 26 | for (int i = 0; i < current.Length; ++i) 27 | { 28 | if (current[i] == '\"' && (i == 0 || current[i - 1] != '\\')) 29 | { 30 | inQuotes = !inQuotes; 31 | } 32 | 33 | if (!inQuotes && current[i] == '/' && i != 0 && current[i - 1] == '/') 34 | { 35 | current = current.Substring(0, i - 1); 36 | } 37 | } 38 | 39 | if (string.IsNullOrEmpty(current)) 40 | { 41 | continue; 42 | } 43 | 44 | // Perhaps I should not assume these will always be the first thing on the line 45 | if (current[0] == '{') 46 | { 47 | // If we're only one brace deep, and we have no prior information, assume a brush 48 | if (braceCount == 1 && !inBrush && !inConnections) 49 | { 50 | inBrush = true; 51 | } 52 | ++braceCount; 53 | } 54 | else if (current[0] == '}') 55 | { 56 | --braceCount; 57 | // If this is the end of an entity substructure 58 | if (braceCount == 1) 59 | { 60 | // If we determined we were inside a brush substructure 61 | if (inBrush) 62 | { 63 | child.Add(current); 64 | //brushes.Add(new MAPBrush(child.ToArray())); // TODO 65 | child = new List(); 66 | } 67 | inBrush = false; 68 | inConnections = false; 69 | } 70 | else 71 | { 72 | child.Add(current); 73 | } 74 | continue; 75 | } 76 | else if (current.Length >= 5 && current.Substring(0, 5) == "solid") 77 | { 78 | inBrush = true; 79 | continue; 80 | } 81 | else if (current.Length >= 11 && current.Substring(0, 11) == "connections") 82 | { 83 | inConnections = true; 84 | continue; 85 | } 86 | 87 | if (inBrush) 88 | { 89 | child.Add(current); 90 | continue; 91 | } 92 | 93 | Add(current); 94 | } 95 | 96 | void Add(string st) 97 | { 98 | string key = ""; 99 | string val = ""; 100 | bool inQuotes = false; 101 | bool isVal = false; 102 | int numCommas = 0; 103 | for (int i = 0; i < st.Length; ++i) 104 | { 105 | // Some entity values in Source can use escape sequenced quotes. Need to make sure not to parse those. 106 | if (st[i] == '\"' && (i == 0 || st[i - 1] != '\\')) 107 | { 108 | if (inQuotes) 109 | { 110 | if (isVal) 111 | { 112 | break; 113 | } 114 | isVal = true; 115 | } 116 | inQuotes = !inQuotes; 117 | } 118 | else 119 | { 120 | if (inQuotes) 121 | { 122 | if (!isVal) 123 | { 124 | key += st[i]; 125 | } 126 | else 127 | { 128 | val += st[i]; 129 | if (st[i] == ',' || st[i] == ConnectionMemberSeparater) { ++numCommas; } 130 | } 131 | } 132 | } 133 | } 134 | val.Replace("\\\"", "\""); 135 | if (key != null && key != "") 136 | { 137 | if (numCommas == 4 || numCommas == 6) 138 | { 139 | st = st.Replace(',', ConnectionMemberSeparater); 140 | string[] connection = val.Split(','); 141 | if (connection.Length < 5) 142 | { 143 | connection = val.Split((char)0x1B); 144 | } 145 | if (connection.Length == 5 || connection.Length == 7) 146 | { 147 | // TODO 148 | //connections.Add(new EntityConnection 149 | //{ 150 | // name = key, 151 | // target = connection[0], 152 | // action = connection[1], 153 | // param = connection[2], 154 | // delay = Double.Parse(connection[3], _format), 155 | // fireOnce = Int32.Parse(connection[4]), 156 | // unknown0 = connection.Length > 5 ? connection[5] : "", 157 | // unknown1 = connection.Length > 6 ? connection[6] : "", 158 | //}); 159 | } 160 | } 161 | else 162 | { 163 | if (!ContainsKey(key)) 164 | { 165 | this[key] = val; 166 | } 167 | } 168 | } 169 | } 170 | } 171 | 172 | public static Entity FromString(string value) 173 | { 174 | return new Entity(value.Split('\n')); 175 | } 176 | 177 | public new string this[string key] 178 | { 179 | get 180 | { 181 | if (ContainsKey(key)) 182 | { 183 | return base[key]; 184 | } 185 | else 186 | { 187 | return ""; 188 | } 189 | } 190 | set { base[key] = value; } 191 | } 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /BspViewer.Desktop/Renderer.cs: -------------------------------------------------------------------------------- 1 | using OpenTK; 2 | using OpenTK.Graphics.OpenGL; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Drawing; 6 | using System.IO; 7 | 8 | namespace BspViewer 9 | { 10 | struct FaceBuffer 11 | { 12 | public int Start { get; set; } 13 | public int Count { get; set; } 14 | } 15 | 16 | sealed class Renderer 17 | : BspRenderer 18 | { 19 | private FaceBuffer[] _faceBufferRegions; 20 | 21 | private int _vertexBuffer; 22 | 23 | public Renderer(BspMap map, BspTextureData[] textures) 24 | : base(map) 25 | { 26 | PreRender(textures); 27 | } 28 | 29 | public void Render(Vector3 position) 30 | { 31 | GL.Enable(EnableCap.DepthTest); 32 | 33 | RenderLevel(new BspVector(position.X, position.Y, position.Z)); 34 | //RenderLeavesOutlines(); 35 | 36 | GL.Disable(EnableCap.DepthTest); 37 | } 38 | 39 | protected override void RenderFace(int faceIndex) 40 | { 41 | var face = Map.Faces[faceIndex]; 42 | 43 | if (Map.Faces[faceIndex].Styles[0] == 0xFF) // Skip sky faces 44 | return; 45 | 46 | // if the light map offset is not -1 and the lightmap lump is not empty, there are lightmaps 47 | var lightmapAvailable = face.LightmapOffset != -1 && Map.Header.Lumps[BspDefs.LUMP_LIGHTING].Length > 0; 48 | 49 | GL.Color3(Map.FaceColors[faceIndex]); 50 | 51 | BeginMode mode; 52 | switch (face.NumEdges) 53 | { 54 | case 3: 55 | mode = BeginMode.Triangles; 56 | break; 57 | case 4: 58 | mode = BeginMode.Quads; 59 | break; 60 | default: 61 | mode = BeginMode.Polygon; 62 | break; 63 | } 64 | 65 | GL.Begin(mode); 66 | for (int i = 0; i < Map.Faces[faceIndex].NumEdges; i++) 67 | { 68 | var vNormal = Map.Planes[face.PlaneId].Normal; 69 | var normal = new Vector3(vNormal[0], vNormal[1], vNormal[2]); 70 | 71 | if (Map.Faces[faceIndex].PlaneSide != 0) 72 | normal = normal * -1; 73 | 74 | GL.Normal3(normal.X, normal.Y, normal.Z); 75 | 76 | int iEdge = Map.SurfEdges[face.FirstEdge + i]; // This gives the index into the edge lump 77 | 78 | if (iEdge > 0) 79 | { 80 | var edge = Map.Edges[iEdge]; 81 | var point = Map.Vertices[edge.Vertices[0]].Point; 82 | var vertex = new Vector3(point[0], point[1], point[2]); 83 | 84 | GL.Vertex3(vertex.X, vertex.Y, vertex.Z); 85 | } 86 | else 87 | { 88 | iEdge *= -1; 89 | 90 | var edge = Map.Edges[iEdge]; 91 | var point = Map.Vertices[edge.Vertices[1]].Point; 92 | var vertex = new Vector3(point[0], point[1], point[2]); 93 | 94 | GL.Vertex3(vertex.X, vertex.Y, vertex.Z); 95 | } 96 | } 97 | GL.End(); 98 | } 99 | 100 | protected override void RenderLevel(BspVector cameraPos) 101 | { 102 | // Get the leaf where the camera is in 103 | int cameraLeaf = TraverseTree(cameraPos, 0); 104 | 105 | // Start the render traversal on the static geometry 106 | RenderNode(0, cameraLeaf, cameraPos); 107 | } 108 | 109 | #region BSP Rendering Debug 110 | 111 | private void RenderLeavesOutlines() 112 | { 113 | GL.LineWidth(1.0f); 114 | GL.LineStipple(1, 0xF0F0); 115 | 116 | GL.Enable(EnableCap.LineStipple); 117 | for (int i = 0; i < Map.Leafs.Length; i++) 118 | { 119 | RenderLeafOutlines(i); 120 | } 121 | GL.Disable(EnableCap.LineStipple); 122 | GL.Color3(1.0f, 1.0f, 1.0f); 123 | } 124 | 125 | private void RenderLeafOutlines(int leafIndex) 126 | { 127 | GL.Color3(ColorUtils.GenerateRandomColor(Color.Red)); 128 | 129 | BspLeaf leaf = Map.Leafs[leafIndex]; 130 | 131 | GL.Begin(BeginMode.Lines); 132 | // Draw right face of bounding box 133 | GL.Vertex3(leaf.Maxs[0], leaf.Maxs[1], leaf.Maxs[2]); 134 | GL.Vertex3(leaf.Maxs[0], leaf.Mins[1], leaf.Maxs[2]); 135 | GL.Vertex3(leaf.Maxs[0], leaf.Mins[1], leaf.Maxs[2]); 136 | GL.Vertex3(leaf.Maxs[0], leaf.Mins[1], leaf.Mins[2]); 137 | GL.Vertex3(leaf.Maxs[0], leaf.Mins[1], leaf.Mins[2]); 138 | GL.Vertex3(leaf.Maxs[0], leaf.Maxs[1], leaf.Mins[2]); 139 | GL.Vertex3(leaf.Maxs[0], leaf.Maxs[1], leaf.Mins[2]); 140 | GL.Vertex3(leaf.Maxs[0], leaf.Maxs[1], leaf.Maxs[2]); 141 | 142 | // Draw left face of bounding box 143 | GL.Vertex3(leaf.Mins[0], leaf.Mins[1], leaf.Mins[2]); 144 | GL.Vertex3(leaf.Mins[0], leaf.Maxs[1], leaf.Mins[2]); 145 | GL.Vertex3(leaf.Mins[0], leaf.Maxs[1], leaf.Mins[2]); 146 | GL.Vertex3(leaf.Mins[0], leaf.Maxs[1], leaf.Maxs[2]); 147 | GL.Vertex3(leaf.Mins[0], leaf.Maxs[1], leaf.Maxs[2]); 148 | GL.Vertex3(leaf.Mins[0], leaf.Mins[1], leaf.Maxs[2]); 149 | GL.Vertex3(leaf.Mins[0], leaf.Mins[1], leaf.Maxs[2]); 150 | GL.Vertex3(leaf.Mins[0], leaf.Mins[1], leaf.Mins[2]); 151 | 152 | // Connect the faces 153 | GL.Vertex3(leaf.Mins[0], leaf.Maxs[1], leaf.Maxs[2]); 154 | GL.Vertex3(leaf.Maxs[0], leaf.Maxs[1], leaf.Maxs[2]); 155 | GL.Vertex3(leaf.Mins[0], leaf.Maxs[1], leaf.Mins[2]); 156 | GL.Vertex3(leaf.Maxs[0], leaf.Maxs[1], leaf.Mins[2]); 157 | GL.Vertex3(leaf.Mins[0], leaf.Mins[1], leaf.Mins[2]); 158 | GL.Vertex3(leaf.Maxs[0], leaf.Mins[1], leaf.Mins[2]); 159 | GL.Vertex3(leaf.Mins[0], leaf.Mins[1], leaf.Maxs[2]); 160 | GL.Vertex3(leaf.Maxs[0], leaf.Mins[1], leaf.Maxs[2]); 161 | GL.End(); 162 | } 163 | 164 | #endregion 165 | 166 | private void PreRender(BspTextureData[] textures) 167 | { 168 | var vertexList = new List(); 169 | var normalList = new List(); 170 | 171 | _faceBufferRegions = new FaceBuffer[Map.Faces.Length]; 172 | var elements = 0; 173 | 174 | // for each face 175 | for (var i = 0; i < Map.Faces.Length; i++) 176 | { 177 | var face = Map.Faces[i]; 178 | 179 | _faceBufferRegions[i] = new FaceBuffer 180 | { 181 | Start = elements, 182 | Count = face.NumEdges 183 | }; 184 | 185 | var texInfo = Map.TextureInfos[face.TextureInfo]; 186 | var plane = Map.Planes[face.PlaneId]; 187 | 188 | var normal = plane.Normal; 189 | 190 | for (var j = 0; j < face.NumEdges; j++) 191 | { 192 | var edgeIndex = Map.SurfEdges[face.FirstEdge + j]; // This gives the index into the edge lump 193 | 194 | int vertexIndex; 195 | if (edgeIndex > 0) 196 | { 197 | var edge = Map.Edges[edgeIndex]; 198 | vertexIndex = edge.Vertices[0]; 199 | } 200 | else 201 | { 202 | edgeIndex *= -1; 203 | var edge = Map.Edges[edgeIndex]; 204 | vertexIndex = edge.Vertices[1]; 205 | } 206 | 207 | var vertex = Map.Vertices[vertexIndex].Point; 208 | 209 | // Write to buffers 210 | //vertexList.Add(vertex[0]); 211 | //vertexList.Add(vertex[1]); 212 | //vertexList.Add(vertex[2]); 213 | vertexList.Add(new Vector3(vertex[0], vertex[1], vertex[2])); 214 | 215 | normalList.Add(normal[0]); 216 | normalList.Add(normal[1]); 217 | normalList.Add(normal[2]); 218 | 219 | elements += 1; 220 | } 221 | } 222 | 223 | var vertices = vertexList.ToArray(); 224 | var normals = normalList.ToArray(); 225 | 226 | // Create all buffers 227 | 228 | _vertexBuffer = GL.GenBuffer(); 229 | GL.BindBuffer(BufferTarget.ArrayBuffer, _vertexBuffer); 230 | GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(vertices.Length * BlittableValueType.StrideOf(vertices)), vertices, BufferUsageHint.StaticDraw); 231 | 232 | // Create all textures 233 | 234 | foreach (var textureData in textures) 235 | { 236 | int texture = GL.GenTexture(); 237 | GL.BindTexture(TextureTarget.Texture2D, texture); 238 | GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, textureData.Width, textureData.Height, 0, PixelFormat.Rgba, PixelType.Float, textureData.TextureData); 239 | GL.GenerateMipmap(GenerateMipmapTarget.Texture2D); 240 | } 241 | } 242 | } 243 | } 244 | -------------------------------------------------------------------------------- /Assets/Docs/Unofficial_WAD3_FileSpec.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | The hlbsp Project 8 | 9 | 10 | 11 | 12 |
17 |

Unofficial WAD3 File Spec

18 | 19 |

Table of content

20 |
    21 |
  1. Introduction
  2. 22 |
  3. Header
  4. 23 |
  5. Directory entries
  6. 24 |
  7. Files in a WAD File - Textures
  8. 25 |
26 | 27 |

Introduction

28 | 29 |

30 | The following file specification concerns the WAD3 file format used 31 | Valve's famous GoldSrc Engine. The file extension is ".wad". 32 | Contrary to the BSP v30 file format that has been derived from the Quake 33 | 1 BSP (v29) format, the WAD3 format is tecnically fully compatible with 34 | Quake's WAD2 files. 35 | WAD files are used to store game related files in some kind of archive. 36 | Somehow they seem to contain only textures, although they are capable of 37 | holding different kinds of data. 38 |

39 | 40 |

41 | This file spec uses constructs from the C programming language to 42 | describe the different data structures used in the WAD file format. 43 | Architecture dependent datatypes like integers are replaced by 44 | exact-width integer types of the C99 standard in the stdint.h header 45 | file, to provide more flexibillity when using x64 platforms. 46 | Basic knowledge about textures in the BSP file is recommended. 47 |

48 | 49 |

50 | #include <stdint.h>
51 |  
52 |

Header

53 | 54 |

55 | Like almost every file also a WAD file (WAD3) starts with a specific file header which is constucted as follows: 56 |

57 | 58 |

59 | typedef struct _WADHEADER
60 | {
61 |     char szMagic[4];    // should be WAD2/WAD3
62 |     int32_t nDir;       // number of directory entries
63 |     int32_t nDirOffset; // offset into directory
64 | } WADHEADER;
65 |  
66 |

67 | The first 4 bytes of a WAD archive identify the file (the so-called 68 | magic number) with the 3 character string "WAD" followed by a version 69 | numer as ASCII char. Compatible formats include "WAD3" as well as 70 | "WAD2". 71 | As with the BSP file also a WAD file starts with some kind of directory 72 | containing entries similar to the lumps of the BSP file. 73 | The major difference is that a WAD file may have an arbitrary number of 74 | entries. This value is stored in the nDir member of the header followed 75 | by the offset to the array of directory entries within the file, which 76 | is usually located somewhere at the ned of the WAD file. 77 |

78 | 79 |

Directory entries

80 | 81 |

82 | The directory of a WAD file is basically an array of structures. Every archived file has an associated entry in this directory: 83 |

84 | 85 |

86 | #define MAXTEXTURENAME 16
87 |
88 | typedef struct _WADDIRENTRY
89 | {
90 |     int32_t nFilePos;            // offset in WAD
91 |     int32_t nDiskSize;           // size in file
92 |     int32_t nSize;               // uncompressed size
93 |     int8_t nType;                // type of entry
94 |     bool bCompression;           // 0 if none
95 |     int16_t nDummy;              // not used
96 |     char szName[MAXTEXTURENAME]; // must be null terminated
97 | } WADDIRENTRY;
98 |  
99 |

100 | The first value is the offset of the raw data of the archived file 101 | within the WAD file followed by the size of data used by the it in its 102 | current form. 103 | Additionally nSize stores the size of original file, if it has been 104 | compressed. This is indicated by the bCompression boolean value. If it 105 | is false, no compression is used which is mostly the case. 106 | The nType member would give as information about the type of file, that 107 | is associated with this entry. As WAD files usually contain only 108 | textures, this information may be ignored. 109 | The nDummy short integer is not used when loading textures and i have 110 | not found any information about this member. 111 | Finally the entry contains a name for the file which can be a string of 112 | maximum 16 chars including the zero termination. In case of textures, 113 | this is the name referred by the BSPMIPTEX structs of the BSP file. 114 |

115 | 116 |

Files in a WAD File - Textures

117 | 118 |

119 | The actual files in the WAD archive, the textures, also start with a file header which may look familiar: 120 |

121 | 122 |

123 | #define MAXTEXTURENAME 16
124 | #define MIPLEVELS 4
125 | typedef struct _BSPMIPTEX
126 | {
127 |     char szName[MAXTEXTURENAME];  // Name of texture
128 |     uint32_t nWidth, nHeight;     // Extends of the texture
129 |     uint32_t nOffsets[MIPLEVELS]; // Offsets to texture mipmaps BSPMIPTEX;
130 | } BSPMIPTEX;
131 |  
132 |

133 | This struct equals the one of the BSP file exactly. 134 | The name of the texture as not needed actually, as it equals the file 135 | name in the directory entry. 136 | The next members are of particular interest. They give the size of the 137 | texture in pixel as well as the offsets into the raw texture data. 138 | The first value of the offset array points to the beginning of the 139 | original texture relativly to the local header (the BSPMIPTEX struct). 140 | From this point follows a nWidth * nHeight bytes long array of indexes 141 | (0-255) pointing to colors in a color table. 142 | The other three offsets are used the same way, but with the diference 143 | that the width and height of the image are cut in half with every 144 | further offset. 145 | These represent the so-called mipmap 146 | levels of the original image. 147 | After the last byte of the fourth mipmap there are two dummy bytes 148 | followed by the actual color table consisting of an array of triples of 149 | bytes (RGB values) with 256 elements. 150 | The indexes of the image are plugged into the color table array to 151 | receive the corresponding RGB color value for the pixel. 152 |

153 | 154 | 155 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /BspViewer/SourceMap/BspLoader.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Text; 4 | using BspViewer.Extensions; 5 | using System.Drawing; 6 | using System; 7 | 8 | namespace BspViewer 9 | { 10 | public sealed class BspLoader 11 | { 12 | private string _fileName; 13 | 14 | private BspHeader _header; 15 | private Entities _entities; 16 | private BspModel[] _models; 17 | private BspPlane[] _planes; 18 | private BspFace[] _faces; 19 | private BspVertex[] _vertices; 20 | private BspEdge[] _edges; 21 | private BspLeaf[] _leafs; 22 | private BspNode[] _nodes; 23 | private BspClipNode[] _clipNodes; 24 | private short[] _markSurfaces; 25 | private int[] _surfEdges; 26 | 27 | private BspTextureHeader _textureHeader; 28 | private BspMipTexture[] _mipTextures; 29 | private BspTextureInfo[] _textureInfos; 30 | 31 | private BspVisData _visData; 32 | private bool[][] _vis; 33 | 34 | public BspLoader(string fileName) 35 | { 36 | _fileName = fileName; 37 | } 38 | 39 | public BspMap Load() 40 | { 41 | if(!File.Exists(_fileName)) 42 | { 43 | throw new FileNotFoundException(_fileName); 44 | } 45 | 46 | using (var reader = new BinaryReader(new FileStream(_fileName, FileMode.Open))) 47 | { 48 | _header = ReadHeader(reader); 49 | _models = ReadModels(reader); 50 | _entities = ReadEntities(reader); 51 | _planes = ReadPlanes(reader); 52 | _faces = ReadFaces(reader); 53 | _vertices = ReadVertices(reader); 54 | _edges = ReadEdges(reader); 55 | _leafs = ReadLeafs(reader); 56 | _nodes = ReadNodes(reader); 57 | _clipNodes = ReadClipNodes(reader); 58 | _markSurfaces = ReadMarkSurfaces(reader); 59 | _surfEdges = ReadSurfEdges(reader); 60 | 61 | _textureHeader = ReadTextureHeader(reader); 62 | _mipTextures = ReadMipTextures(reader); 63 | _textureInfos = ReadTextureInfos(reader); 64 | 65 | _visData = ReadVisData(reader); 66 | //_vis = LoadVis(reader); 67 | } 68 | 69 | string name = Path.GetFileNameWithoutExtension(_fileName); 70 | 71 | return new BspMap(name) 72 | { 73 | Header = _header, 74 | Entities = _entities, 75 | Models = _models, 76 | Planes = _planes, 77 | Faces = _faces, 78 | Vertices = _vertices, 79 | Edges = _edges, 80 | Leafs = _leafs, 81 | Nodes = _nodes, 82 | ClipNodes = _clipNodes, 83 | MarkSurfaces = _markSurfaces, 84 | SurfEdges = _surfEdges, 85 | 86 | TextureHeader = _textureHeader, 87 | MipTextures = _mipTextures, 88 | TextureInfos = _textureInfos, 89 | 90 | //VisList = _vis, 91 | FaceColors = CreateRandomFaceColors(), 92 | }; 93 | } 94 | 95 | private BspTextureHeader ReadTextureHeader(BinaryReader reader) 96 | { 97 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_TEXTURES]; 98 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 99 | 100 | int numberOfTextures = reader.ReadInt32(); 101 | int[] mipTexturesOffsets = new int[numberOfTextures]; 102 | 103 | for (int i = 0; i < numberOfTextures; i++) 104 | { 105 | mipTexturesOffsets[i] = reader.ReadInt32(); 106 | } 107 | 108 | return new BspTextureHeader { NumberMipTextures = numberOfTextures, Offsets = mipTexturesOffsets }; 109 | } 110 | 111 | private Color[] CreateRandomFaceColors() 112 | { 113 | var colors = new Color[_faces.Length]; 114 | 115 | for (int i = 0; i < _faces.Length; i++) 116 | { 117 | colors[i] = ColorUtils.GenerateRandomBrushColour(); 118 | } 119 | 120 | return colors; 121 | } 122 | 123 | #region Structure Read 124 | 125 | private BspTextureInfo[] ReadTextureInfos(BinaryReader reader) 126 | { 127 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_TEXINFO]; 128 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 129 | 130 | int numTextureInfos = entitiesLump.Length / 40; 131 | 132 | var textureInfos = new List(); 133 | for (int i = 0; i < numTextureInfos; i++) 134 | { 135 | textureInfos.Add(new BspTextureInfo { Vec3s = reader.ReadSingleArray(), SShift = reader.ReadSingle(), Vec3t = reader.ReadSingleArray(), TShift = reader.ReadSingle(), MipTex = reader.ReadUInt32(), Flags = reader.ReadUInt32() }); 136 | } 137 | 138 | return textureInfos.ToArray(); 139 | } 140 | 141 | private BspMipTexture[] ReadMipTextures(BinaryReader reader) 142 | { 143 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_TEXTURES]; 144 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 145 | 146 | int numberOfTextures = reader.ReadInt32(); 147 | int[] mipTexturesOffset = new int[numberOfTextures]; 148 | 149 | for (int i = 0; i < numberOfTextures; i++) 150 | { 151 | mipTexturesOffset[i] = (entitiesLump.Offset + reader.ReadInt32()); 152 | } 153 | 154 | var mipTextures = new List(); 155 | for (int i = 0; i < numberOfTextures; i++) 156 | { 157 | int textureOffset = mipTexturesOffset[i]; 158 | reader.BaseStream.Seek(textureOffset, SeekOrigin.Begin); 159 | 160 | mipTextures.Add(new BspMipTexture { Name = reader.ReadString(16), Width = reader.ReadUInt32(), Height = reader.ReadUInt32(), Offsets = reader.ReadUInt32Array(4) }); 161 | } 162 | 163 | return mipTextures.ToArray(); 164 | } 165 | 166 | private BspModel[] ReadModels(BinaryReader reader) 167 | { 168 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_MODELS]; 169 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 170 | int numModels = entitiesLump.Length / 64; 171 | 172 | var models = new List(); 173 | for (int i = 0; i < numModels; i++) 174 | { 175 | models.Add(new BspModel { Mins = reader.ReadSingleArray(), Maxs = reader.ReadSingleArray(), Origin = reader.ReadSingleArray(), Nodes = reader.ReadInt32Array(), NumLeafs = reader.ReadInt32(), FirstFace = reader.ReadInt32(), NumFaces = reader.ReadInt32() }); 176 | } 177 | 178 | return models.ToArray(); 179 | } 180 | 181 | private BspVisData ReadVisData(BinaryReader reader) 182 | { 183 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_VISIBILITY]; 184 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 185 | 186 | byte[] vis = reader.ReadBytes(entitiesLump.Length); 187 | 188 | return new BspVisData { CompressedVis = vis }; 189 | } 190 | 191 | private byte[] ReadVisData(BinaryReader reader, int length) 192 | { 193 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_VISIBILITY]; 194 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 195 | 196 | byte[] vis = reader.ReadBytes(length); 197 | 198 | return vis; 199 | } 200 | 201 | private int[] ReadSurfEdges(BinaryReader reader) 202 | { 203 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_SURFEDGES]; 204 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 205 | int numSurfedges = entitiesLump.Length / 4; 206 | 207 | var surfedges = new List(); 208 | for (int i = 0; i < numSurfedges; i++) 209 | { 210 | surfedges.Add(reader.ReadInt32()); 211 | } 212 | 213 | return surfedges.ToArray(); 214 | } 215 | 216 | private short[] ReadMarkSurfaces(BinaryReader reader) 217 | { 218 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_MARKSURFACES]; 219 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 220 | int numMarkSurfaces = entitiesLump.Length / 2; 221 | 222 | var markSurfaces = new List(); 223 | for (int i = 0; i < numMarkSurfaces; i++) 224 | { 225 | markSurfaces.Add(reader.ReadInt16()); 226 | } 227 | 228 | return markSurfaces.ToArray(); 229 | } 230 | 231 | private BspClipNode[] ReadClipNodes(BinaryReader reader) 232 | { 233 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_CLIPNODES]; 234 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 235 | int numClipNodes = entitiesLump.Length / BspClipNode.SizeInBytes; 236 | 237 | var clipNodes = new List(); 238 | for (int i = 0; i < numClipNodes; i++) 239 | { 240 | clipNodes.Add(new BspClipNode { PlaneId = reader.ReadInt32(), Children = reader.ReadInt16Array(2) }); 241 | } 242 | 243 | return clipNodes.ToArray(); 244 | } 245 | 246 | private BspNode[] ReadNodes(BinaryReader reader) 247 | { 248 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_NODES]; 249 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 250 | int numNodes = entitiesLump.Length / BspNode.SizeInBytes; 251 | 252 | var nodes = new List(); 253 | for (int i = 0; i < numNodes; i++) 254 | { 255 | nodes.Add(new BspNode { PlaneId = reader.ReadInt32(), Children = reader.ReadInt16Array(2), Mins = reader.ReadInt16Array(), Maxs = reader.ReadInt16Array(), FirstFace = reader.ReadUInt16(), NumFaces = reader.ReadUInt16() }); 256 | } 257 | 258 | return nodes.ToArray(); 259 | } 260 | 261 | private BspLeaf[] ReadLeafs(BinaryReader reader) 262 | { 263 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_LEAFS]; 264 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 265 | int numLeafs = entitiesLump.Length / BspLeaf.SizeInBytes; 266 | 267 | var leafs = new List(); 268 | for (int i = 0; i < numLeafs; i++) 269 | { 270 | leafs.Add(new BspLeaf { Contents = reader.ReadInt32(), VisOffset = reader.ReadInt32(), Mins = reader.ReadInt16Array(), Maxs = reader.ReadInt16Array(), FirstMarkSurface = reader.ReadUInt16(), NumMarkSurfaces = reader.ReadUInt16(), AmbientLevels = reader.ReadBytes(4) }); 271 | } 272 | 273 | return leafs.ToArray(); 274 | } 275 | 276 | private BspEdge[] ReadEdges(BinaryReader reader) 277 | { 278 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_EDGES]; 279 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 280 | int numEdges = entitiesLump.Length / BspEdge.SizeInBytes; 281 | 282 | var edges = new List(); 283 | for (int i = 0; i < numEdges; i++) 284 | { 285 | edges.Add(new BspEdge { Vertices = reader.ReadUInt16Array() }); 286 | } 287 | 288 | return edges.ToArray(); 289 | } 290 | 291 | private BspVertex[] ReadVertices(BinaryReader reader) 292 | { 293 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_VERTEXES]; 294 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 295 | int numVertices = entitiesLump.Length / BspVertex.SizeInBytes; 296 | 297 | var vertices = new List(); 298 | for (int i = 0; i < numVertices; i++) 299 | { 300 | vertices.Add(new BspVertex { Point = reader.ReadSingleArray() }); 301 | } 302 | 303 | return vertices.ToArray(); 304 | } 305 | 306 | private BspFace[] ReadFaces(BinaryReader reader) 307 | { 308 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_FACES]; 309 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 310 | int numFaces = entitiesLump.Length / BspFace.SizeInBytes; 311 | 312 | var faces = new List(); 313 | for (int i = 0; i < numFaces; i++) 314 | { 315 | faces.Add(new BspFace { PlaneId = reader.ReadInt16(), PlaneSide = reader.ReadInt16(), FirstEdge = reader.ReadInt32(), NumEdges = reader.ReadInt16(), TextureInfo = reader.ReadInt16(), Styles = reader.ReadBytes(4), LightmapOffset = reader.ReadInt32() }); 316 | } 317 | 318 | return faces.ToArray(); 319 | } 320 | 321 | private BspPlane[] ReadPlanes(BinaryReader reader) 322 | { 323 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_PLANES]; 324 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 325 | int numPlanes = entitiesLump.Length / BspPlane.SizeInBytes; 326 | 327 | var planes = new List(); 328 | for (int i = 0; i < numPlanes; i++) 329 | { 330 | planes.Add(new BspPlane { Normal = reader.ReadSingleArray(), Distance = reader.ReadSingle(), Type = reader.ReadInt32() }); 331 | } 332 | 333 | return planes.ToArray(); 334 | } 335 | 336 | private Entities ReadEntities(BinaryReader reader) 337 | { 338 | BspLump entitiesLump = _header.Lumps[BspDefs.LUMP_ENTITIES]; 339 | reader.BaseStream.Seek(entitiesLump.Offset, SeekOrigin.Begin); 340 | 341 | var bytes = reader.ReadBytes(entitiesLump.Length); 342 | string rawEntities = Encoding.ASCII.GetString(bytes); 343 | 344 | var parser = new EntityParser(bytes); 345 | var entities = parser.Parse(); 346 | 347 | return entities; 348 | } 349 | 350 | private BspHeader ReadHeader(BinaryReader reader) 351 | { 352 | var version = reader.ReadInt32(); 353 | 354 | var lumps = new List(); 355 | for (int i = 0; i < 15; i++) 356 | { 357 | lumps.Add(new BspLump { Offset = reader.ReadInt32(), Length = reader.ReadInt32() }); 358 | } 359 | 360 | return new BspHeader { Version = version, Lumps = lumps.ToArray() }; 361 | } 362 | 363 | #endregion 364 | 365 | #region PVS 366 | 367 | // Loads and decompresses the PVS (Potentially Visible Set) from the bsp file. 368 | public bool[][] LoadVis(BinaryReader reader) 369 | { 370 | if (_visData.CompressedVis.Length > 0) 371 | { 372 | var visLeaves = CountVisLeafs(0); 373 | 374 | var visLists = new bool[visLeaves][]; 375 | 376 | for (var i = 0; i < visLeaves; i++) 377 | { 378 | if (_leafs[i + 1].VisOffset >= 0) 379 | visLists[i] = GetPVS(reader, i + 1, visLeaves); 380 | else 381 | visLists[i] = null; 382 | } 383 | 384 | return visLists; 385 | } 386 | 387 | return null; 388 | } 389 | 390 | private int CountVisLeafs(int nodeIndex) 391 | { 392 | if (nodeIndex < 0) 393 | { 394 | // leaf 0 395 | if (nodeIndex == -1) 396 | return 0; 397 | 398 | if (_leafs[~nodeIndex].Contents == BspDefs.CONTENTS_SOLID) 399 | return 0; 400 | 401 | return 1; 402 | } 403 | 404 | var node = _nodes[nodeIndex]; 405 | 406 | return CountVisLeafs(node.Children[0]) + CountVisLeafs(node.Children[1]); 407 | } 408 | 409 | private bool[] GetPVS(BinaryReader reader, int leafIndex, int visLeaves) 410 | { 411 | var list = new bool[_leafs.Length - 1]; 412 | 413 | for (var i = 0; i < list.Length; i++) 414 | list[i] = false; 415 | 416 | var compressed = ReadVisData(reader, _header.Lumps[BspDefs.LUMP_VISIBILITY].Offset + _leafs[leafIndex].VisOffset); 417 | var writeIndex = 0; // Index that moves through the destination bool array (list) 418 | 419 | for (var curByte = 0; writeIndex < visLeaves; curByte++) 420 | { 421 | // Check for a run of 0s 422 | if (compressed[curByte] == 0) 423 | { 424 | // Advance past this run of 0s 425 | curByte++; 426 | // Move the write pointer the number of compressed 0s 427 | writeIndex += 8 * compressed[curByte]; 428 | } 429 | else 430 | { 431 | // Iterate through this byte with bit shifting till the bit has moved beyond the 8th digit 432 | for (var mask = 0x01; mask != 0x0100; writeIndex++, mask <<= 1) 433 | { 434 | // Test a bit of the compressed PVS with the bit mask 435 | if ((compressed[curByte] & mask) == 1 && (writeIndex < visLeaves)) 436 | list[writeIndex] = true; 437 | } 438 | } 439 | } 440 | 441 | return list; 442 | } 443 | 444 | #endregion 445 | } 446 | } -------------------------------------------------------------------------------- /BspViewer/SourceMap/WadLoader.cs: -------------------------------------------------------------------------------- 1 | using BspViewer.Extensions; 2 | using System.IO; 3 | using System.Diagnostics; 4 | using System.Collections.Generic; 5 | using System; 6 | 7 | namespace BspViewer 8 | { 9 | struct MissingTexture 10 | { 11 | public string Name { get; set; } 12 | public int Index { get; set; } 13 | } 14 | 15 | public sealed class WadLoader 16 | { 17 | private BspMap _map; 18 | private string _mapFileName; 19 | private string[] _wadFileNames; 20 | 21 | private WadHeader _header; 22 | 23 | private List _textureLookup; 24 | private List _missingTextures; 25 | 26 | public WadLoader(BspMap map, string mapFileName, string[] wadFileNames) 27 | { 28 | _map = map; 29 | 30 | _mapFileName = mapFileName; 31 | 32 | _wadFileNames = wadFileNames; 33 | } 34 | 35 | public BspTextureData[] Load() 36 | { 37 | using (var mapReader = new BinaryReader(new FileStream(_mapFileName, FileMode.Open))) 38 | { 39 | foreach (var fileName in _wadFileNames) 40 | { 41 | if (!File.Exists(fileName)) 42 | { 43 | throw new FileNotFoundException(fileName); 44 | } 45 | 46 | using (var reader = new BinaryReader(new FileStream(fileName, FileMode.Open))) 47 | { 48 | _header = ReadHeader(reader); 49 | } 50 | 51 | LoadTextures(mapReader); 52 | } 53 | } 54 | 55 | return _textureLookup.ToArray(); 56 | } 57 | 58 | private WadHeader ReadHeader(BinaryReader reader) 59 | { 60 | var header = new WadHeader 61 | { 62 | Magic = reader.ReadString(4), 63 | Dirs = reader.ReadInt32(), 64 | DirOffset = reader.ReadInt32() 65 | }; 66 | 67 | if (header.Magic != "WAD2" && header.Magic != "WAD3") 68 | { 69 | throw new InvalidDataException(); 70 | } 71 | 72 | return header; 73 | } 74 | 75 | #region BSP Textures 76 | 77 | private void LoadTextures(BinaryReader mapReader) 78 | { 79 | // Texture Coordinates 80 | 81 | var textureCoordinates = new List(); 82 | 83 | for (var i = 0; i < _map.Faces.Length; i++) 84 | { 85 | var face = _map.Faces[i]; 86 | var texInfo = _map.TextureInfos[face.TextureInfo]; 87 | 88 | var faceCoords = new List(); 89 | 90 | for (var j = 0; j < face.NumEdges; j++) 91 | { 92 | var edgeIndex = _map.SurfEdges[face.FirstEdge + j]; 93 | 94 | ushort vertexIndex; 95 | if (edgeIndex > 0) 96 | { 97 | var edge = _map.Edges[edgeIndex]; 98 | vertexIndex = edge.Vertices[0]; 99 | } 100 | else 101 | { 102 | edgeIndex *= -1; 103 | var edge = _map.Edges[edgeIndex]; 104 | vertexIndex = edge.Vertices[1]; 105 | } 106 | 107 | var vertex = _map.Vertices[vertexIndex]; 108 | var mipTexture = _map.MipTextures[texInfo.MipTex]; 109 | 110 | var coord = new FaceCoord 111 | { 112 | Vec3s = (MathLib.DotProduct(vertex.Point, texInfo.Vec3s) + texInfo.SShift) / mipTexture.Width, 113 | Vec3t = (MathLib.DotProduct(vertex.Point, texInfo.Vec3t) + texInfo.TShift) / mipTexture.Height 114 | }; 115 | 116 | faceCoords.Add(coord); 117 | } 118 | 119 | textureCoordinates.AddRange(faceCoords); 120 | } 121 | 122 | var whiteTexture = new BspTextureData(); // ToDo 123 | 124 | // Texture images 125 | 126 | _textureLookup = new List(); 127 | _missingTextures = new List(); 128 | 129 | for (var i = 0; i < _map.MipTextures.Length; i++) 130 | { 131 | var mipTexture = _map.MipTextures[i]; 132 | 133 | if (mipTexture.Offsets[0] == 0) 134 | { 135 | // External texture 136 | 137 | // search texture in loaded wads 138 | var texture = LoadTextureFromWad(mipTexture.Name); 139 | 140 | if (texture.TextureData != null) 141 | { 142 | // the texture has been found in a loaded wad 143 | _textureLookup.Add(texture); 144 | 145 | Debug.WriteLine("Texture " + mipTexture.Name + " found"); 146 | } 147 | else 148 | { 149 | // bind simple white texture to do not disturb lightmaps 150 | _textureLookup.Add(whiteTexture); 151 | 152 | // store the name and position of this missing texture, 153 | // so that it can later be loaded to the right position by calling loadMissingTextures() 154 | _missingTextures.Add(new MissingTexture { Name = mipTexture.Name, Index = i }); 155 | 156 | Debug.WriteLine("Texture " + mipTexture.Name + " is missing"); 157 | } 158 | 159 | continue; 160 | } 161 | else 162 | { 163 | // Load internal texture if present 164 | 165 | // Calculate offset of the texture in the bsp file 166 | //var offset = _map.TextureHeader.Offsets[i]; 167 | var offset = _map.Header.Lumps[BspDefs.LUMP_TEXTURES].Offset + _map.TextureHeader.Offsets[i]; 168 | 169 | _textureLookup.Add(FetchTextureAtOffset(mapReader, offset)); 170 | 171 | Debug.WriteLine("Fetched interal texture " + mipTexture.Name); 172 | } 173 | } 174 | } 175 | 176 | private BspTextureData FetchTextureAtOffset(BinaryReader mapReader, long offset) 177 | { 178 | // Seek to the texture beginning 179 | mapReader.BaseStream.Seek(offset, SeekOrigin.Begin); 180 | 181 | // Load texture header 182 | var mipTex = new BspMipTexture() 183 | { 184 | Name = mapReader.ReadString(WadDefs.MAXTEXTURENAME), 185 | Width = mapReader.ReadUInt32(), 186 | Height = mapReader.ReadUInt32(), 187 | Offsets = mapReader.ReadUInt32Array(WadDefs.MIPLEVELS) 188 | }; 189 | 190 | // Fetch color palette 191 | var paletteOffset = mipTex.Offsets[WadDefs.MIPLEVELS - 1] + ((mipTex.Width / 8) * (mipTex.Height / 8)) + 2; 192 | var palette = mapReader.ReadUInt8Array(offset + paletteOffset, 256 * 3); 193 | 194 | // Width and height shrink to half for every level 195 | int width = (int) mipTex.Width; 196 | int height = (int) mipTex.Height; 197 | 198 | // Fetch the indexed texture 199 | var textureIndexes = mapReader.ReadUInt8Array(offset + mipTex.Offsets[0], width * height); 200 | 201 | // Allocate storage for the rgba texture 202 | var textureData = new uint[width * height * 4]; 203 | 204 | // Translate the texture from indexes to rgba 205 | for (var j = 0; j < width * height; j++) 206 | { 207 | var paletteIndex = textureIndexes[j] * 3; 208 | 209 | textureData[j * 4] = palette[paletteIndex]; 210 | textureData[j * 4 + 1] = palette[paletteIndex + 1]; 211 | textureData[j * 4 + 2] = palette[paletteIndex + 2]; 212 | textureData[j * 4 + 3] = 255; // every pixel is totally opaque 213 | } 214 | 215 | if (mipTex.Name.Substring(0, 1) == "{") // this is an alpha texture 216 | { 217 | Debug.WriteLine(mipTex.Name + " is an alpha texture"); 218 | 219 | // Transfere alpha key color to actual alpha values 220 | ApplyAlphaSections(ref textureData, width, height, palette[255 * 3 + 0], palette[255 * 3 + 1], palette[255 * 3 + 2]); 221 | } 222 | 223 | return new BspTextureData(textureData, width, height, mipTex.Name); 224 | } 225 | 226 | private BspTextureData LoadTextureFromWad(string name) 227 | { 228 | return new BspTextureData(); // ToDo 229 | } 230 | 231 | private void ApplyAlphaSections(ref uint[] pixels, int width, int height, uint keyR, uint keyG, uint keyB) 232 | { 233 | // Create an equally sized pixel buffer initialized to the key color 234 | var rgbBuffer = new uint[width * height * 3]; 235 | 236 | for (var y = 0; y < height; y++) 237 | { 238 | for (var x = 0; x < width; x++) 239 | { 240 | var bufIndex = (y * width + x) * 3; 241 | rgbBuffer[bufIndex + 0] = keyR; 242 | rgbBuffer[bufIndex + 1] = keyG; 243 | rgbBuffer[bufIndex + 2] = keyB; 244 | } 245 | } 246 | 247 | // The key color signifies a transparent portion of the texture. Zero alpha for blending and 248 | // to get rid of key colored edges choose the average color of the nearest non key pixels. 249 | 250 | // Interpolate colors for transparent pixels 251 | for (var y = 0; y < height; y++) 252 | { 253 | for (var x = 0; x < width; x++) 254 | { 255 | var index = (y * width + x) * 4; 256 | 257 | if ((pixels[index + 0] == keyR) && 258 | (pixels[index + 1] == keyG) && 259 | (pixels[index + 2] == keyB)) 260 | { 261 | // This is a pixel which should be transparent 262 | 263 | pixels[index + 3] = 0; 264 | 265 | var count = 0; 266 | var colorSum = new float[3]; 267 | colorSum[0] = 0; 268 | colorSum[1] = 0; 269 | colorSum[2] = 0; 270 | 271 | // left above pixel 272 | if ((x > 0) && (y > 0)) 273 | { 274 | var pixelIndex = ((y - 1) * width + (x - 1)) * 4; 275 | if (pixels[pixelIndex + 0] != keyR || 276 | pixels[pixelIndex + 1] != keyG || 277 | pixels[pixelIndex + 2] != keyB) 278 | { 279 | colorSum[0] += pixels[pixelIndex + 0] * MathLib.SQRT2; 280 | colorSum[1] += pixels[pixelIndex + 1] * MathLib.SQRT2; 281 | colorSum[2] += pixels[pixelIndex + 2] * MathLib.SQRT2; 282 | count++; 283 | } 284 | } 285 | 286 | // above pixel 287 | if ((x >= 0) && (y > 0)) 288 | { 289 | var pixelIndex = ((y - 1) * width + x) * 4; 290 | if (pixels[pixelIndex + 0] != keyR || 291 | pixels[pixelIndex + 1] != keyG || 292 | pixels[pixelIndex + 2] != keyB) 293 | { 294 | colorSum[0] += pixels[pixelIndex + 0]; 295 | colorSum[1] += pixels[pixelIndex + 1]; 296 | colorSum[2] += pixels[pixelIndex + 2]; 297 | count++; 298 | } 299 | } 300 | 301 | // right above pixel 302 | if ((x < width - 1) && (y > 0)) 303 | { 304 | var pixelIndex = ((y - 1) * width + (x + 1)) * 4; 305 | if (pixels[pixelIndex + 0] != keyR || 306 | pixels[pixelIndex + 1] != keyG || 307 | pixels[pixelIndex + 2] != keyB) 308 | { 309 | colorSum[0] += pixels[pixelIndex + 0] * MathLib.SQRT2; 310 | colorSum[1] += pixels[pixelIndex + 1] * MathLib.SQRT2; 311 | colorSum[2] += pixels[pixelIndex + 2] * MathLib.SQRT2; 312 | count++; 313 | } 314 | } 315 | 316 | // left pixel 317 | if (x > 0) 318 | { 319 | var pixelIndex = (y * width + (x - 1)) * 4; 320 | if (pixels[pixelIndex + 0] != keyR || 321 | pixels[pixelIndex + 1] != keyG || 322 | pixels[pixelIndex + 2] != keyB) 323 | { 324 | colorSum[0] += pixels[pixelIndex + 0]; 325 | colorSum[1] += pixels[pixelIndex + 1]; 326 | colorSum[2] += pixels[pixelIndex + 2]; 327 | count++; 328 | } 329 | } 330 | 331 | // right pixel 332 | if (x < width - 1) 333 | { 334 | var pixelIndex = (y * width + (x + 1)) * 4; 335 | if (pixels[pixelIndex + 0] != keyR || 336 | pixels[pixelIndex + 1] != keyG || 337 | pixels[pixelIndex + 2] != keyB) 338 | { 339 | colorSum[0] += pixels[pixelIndex + 0]; 340 | colorSum[1] += pixels[pixelIndex + 1]; 341 | colorSum[2] += pixels[pixelIndex + 2]; 342 | count++; 343 | } 344 | } 345 | 346 | // left underneath pixel 347 | if ((x > 0) && (y < height - 1)) 348 | { 349 | var pixelIndex = ((y + 1) * width + (x - 1)) * 4; 350 | if (pixels[pixelIndex + 0] != keyR || 351 | pixels[pixelIndex + 1] != keyG || 352 | pixels[pixelIndex + 2] != keyB) 353 | { 354 | colorSum[0] += pixels[pixelIndex + 0] * MathLib.SQRT2; 355 | colorSum[1] += pixels[pixelIndex + 1] * MathLib.SQRT2; 356 | colorSum[2] += pixels[pixelIndex + 2] * MathLib.SQRT2; 357 | count++; 358 | } 359 | } 360 | 361 | // underneath pixel 362 | if ((x >= 0) && (y < height - 1)) 363 | { 364 | var pixelIndex = ((y + 1) * width + x) * 4; 365 | if (pixels[pixelIndex + 0] != keyR || 366 | pixels[pixelIndex + 1] != keyG || 367 | pixels[pixelIndex + 2] != keyB) 368 | { 369 | colorSum[0] += pixels[pixelIndex + 0]; 370 | colorSum[1] += pixels[pixelIndex + 1]; 371 | colorSum[2] += pixels[pixelIndex + 2]; 372 | count++; 373 | } 374 | } 375 | 376 | // right underneath pixel 377 | if ((x < width - 1) && (y < height - 1)) 378 | { 379 | var pixelIndex = ((y + 1) * width + (x + 1)) * 4; 380 | if (pixels[pixelIndex + 0] != keyR || 381 | pixels[pixelIndex + 1] != keyG || 382 | pixels[pixelIndex + 2] != keyB) 383 | { 384 | colorSum[0] += pixels[pixelIndex + 0] * MathLib.SQRT2; 385 | colorSum[1] += pixels[pixelIndex + 1] * MathLib.SQRT2; 386 | colorSum[2] += pixels[pixelIndex + 2] * MathLib.SQRT2; 387 | count++; 388 | } 389 | } 390 | 391 | if (count > 0) 392 | { 393 | colorSum[0] /= count; 394 | colorSum[1] /= count; 395 | colorSum[2] /= count; 396 | 397 | var bufIndex = (y * width + x) * 3; 398 | rgbBuffer[bufIndex + 0] = (uint) Math.Round(colorSum[0]); 399 | rgbBuffer[bufIndex + 1] = (uint) Math.Round(colorSum[1]); 400 | rgbBuffer[bufIndex + 2] = (uint) Math.Round(colorSum[2]); 401 | } 402 | } 403 | } 404 | } 405 | 406 | // Transfer interpolated colors to the texture 407 | for (var y = 0; y < height; y++) 408 | { 409 | for (var x = 0; x < width; x++) 410 | { 411 | var index = (y * width + x) * 4; 412 | var bufindex = (y * width + x) * 3; 413 | 414 | if ((rgbBuffer[bufindex + 0] != keyR) || 415 | (rgbBuffer[bufindex + 1] != keyG) || 416 | (rgbBuffer[bufindex + 2] != keyB)) 417 | { 418 | pixels[index + 0] = rgbBuffer[bufindex + 0]; 419 | pixels[index + 1] = rgbBuffer[bufindex + 1]; 420 | pixels[index + 2] = rgbBuffer[bufindex + 2]; 421 | } 422 | } 423 | } 424 | } 425 | 426 | #endregion 427 | } 428 | } -------------------------------------------------------------------------------- /BspViewer.Tests/TestData/Entities/ValidEntites.txt: -------------------------------------------------------------------------------- 1 | { 2 | "wad" "\sierra\half-life\cstrike\cstrike.wad;\sierra\half-life\valve\halflife.wad;\windows\desktop\ajawad.wad" 3 | "WaveHeight" "1.5" 4 | "light" "0" 5 | "skyname" "cliff" 6 | "MaxRange" "4096" 7 | "classname" "worldspawn" 8 | } 9 | { 10 | "origin" "216 1216 446" 11 | "_light" "255 255 128 90" 12 | "pitch" "-60" 13 | "classname" "light_environment" 14 | } 15 | { 16 | "origin" "52 892 21" 17 | "angle" "255" 18 | "classname" "info_player_deathmatch" 19 | } 20 | { 21 | "model" "*1" 22 | "origin" "175 162 -105" 23 | "unlocked_sentence" "0" 24 | "locked_sentence" "0" 25 | "unlocked_sound" "0" 26 | "locked_sound" "0" 27 | "health" "0" 28 | "delay" "0" 29 | "dmg" "0" 30 | "lip" "0" 31 | "wait" "3" 32 | "stopsnd" "0" 33 | "movesnd" "9" 34 | "speed" "100" 35 | "rendercolor" "0 0 0" 36 | "renderamt" "0" 37 | "rendermode" "0" 38 | "renderfx" "0" 39 | "angles" "0 0 0" 40 | "distance" "90" 41 | "classname" "func_door_rotating" 42 | } 43 | { 44 | "model" "*2" 45 | "origin" "-85 424 38" 46 | "unlocked_sentence" "0" 47 | "locked_sentence" "0" 48 | "unlocked_sound" "0" 49 | "locked_sound" "0" 50 | "health" "0" 51 | "delay" "0" 52 | "dmg" "0" 53 | "lip" "0" 54 | "wait" "4" 55 | "stopsnd" "0" 56 | "movesnd" "9" 57 | "speed" "100" 58 | "rendercolor" "0 0 0" 59 | "renderamt" "0" 60 | "rendermode" "0" 61 | "renderfx" "0" 62 | "angles" "0 0 0" 63 | "distance" "90" 64 | "classname" "func_door_rotating" 65 | } 66 | { 67 | "model" "*3" 68 | "rendercolor" "0 0 0" 69 | "renderfx" "0" 70 | "skin" "-1" 71 | "renderamt" "255" 72 | "rendermode" "4" 73 | "classname" "func_illusionary" 74 | } 75 | { 76 | "model" "*4" 77 | "classname" "func_ladder" 78 | } 79 | { 80 | "origin" "-88 756 21" 81 | "angle" "289" 82 | "classname" "info_player_deathmatch" 83 | } 84 | { 85 | "origin" "-64 576 21" 86 | "angle" "330" 87 | "classname" "info_player_deathmatch" 88 | } 89 | { 90 | "origin" "148 520 21" 91 | "angle" "340" 92 | "classname" "info_player_deathmatch" 93 | } 94 | { 95 | "origin" "122 731 21" 96 | "angle" "180" 97 | "classname" "info_player_deathmatch" 98 | } 99 | { 100 | "origin" "-78 1023 21" 101 | "angle" "303" 102 | "classname" "info_player_deathmatch" 103 | } 104 | { 105 | "origin" "396 556 21" 106 | "angle" "184" 107 | "classname" "info_player_deathmatch" 108 | } 109 | { 110 | "origin" "254 1028 21" 111 | "angle" "255" 112 | "classname" "info_player_deathmatch" 113 | } 114 | { 115 | "origin" "82 1052 21" 116 | "angle" "264" 117 | "classname" "info_player_deathmatch" 118 | } 119 | { 120 | "origin" "392 -2368 -123" 121 | "classname" "info_player_start" 122 | } 123 | { 124 | "origin" "172 -2272 -123" 125 | "classname" "info_player_start" 126 | } 127 | { 128 | "origin" "-372 -2244 -123" 129 | "angle" "342" 130 | "classname" "info_player_start" 131 | } 132 | { 133 | "origin" "72 -2504 -123" 134 | "classname" "info_player_start" 135 | } 136 | { 137 | "origin" "-124 -2364 -123" 138 | "angle" "342" 139 | "classname" "info_player_start" 140 | } 141 | { 142 | "origin" "428 -2596 -123" 143 | "classname" "info_player_start" 144 | } 145 | { 146 | "origin" "-455 -2047 -123" 147 | "angle" "311" 148 | "classname" "info_player_start" 149 | } 150 | { 151 | "origin" "-134 -2138 -123" 152 | "angle" "338" 153 | "classname" "info_player_start" 154 | } 155 | { 156 | "origin" "116 -2736 -123" 157 | "angle" "29" 158 | "classname" "info_player_start" 159 | } 160 | { 161 | "origin" "-344 -2456 -123" 162 | "classname" "info_player_start" 163 | } 164 | { 165 | "origin" "434 792 -157" 166 | "body" "2" 167 | "gravity" "1" 168 | "model" "models/scientist.mdl" 169 | "angle" "192" 170 | "classname" "hostage_entity" 171 | } 172 | { 173 | "origin" "482 862 -157" 174 | "body" "2" 175 | "gravity" "1" 176 | "model" "models/scientist.mdl" 177 | "angle" "166" 178 | "classname" "hostage_entity" 179 | } 180 | { 181 | "model" "*5" 182 | "classname" "func_ladder" 183 | } 184 | { 185 | "model" "*6" 186 | "renderamt" "255" 187 | "rendermode" "4" 188 | "classname" "func_wall" 189 | } 190 | { 191 | "model" "*7" 192 | "origin" "358 750 38" 193 | "unlocked_sentence" "0" 194 | "locked_sentence" "0" 195 | "unlocked_sound" "0" 196 | "locked_sound" "0" 197 | "health" "0" 198 | "delay" "0" 199 | "dmg" "0" 200 | "lip" "0" 201 | "wait" "4" 202 | "stopsnd" "0" 203 | "movesnd" "9" 204 | "speed" "100" 205 | "rendercolor" "0 0 0" 206 | "renderamt" "0" 207 | "rendermode" "0" 208 | "renderfx" "0" 209 | "angles" "0 0 0" 210 | "distance" "90" 211 | "classname" "func_door_rotating" 212 | } 213 | { 214 | "model" "*8" 215 | "WaveHeight" ".5" 216 | "skin" "-3" 217 | "unlocked_sentence" "0" 218 | "locked_sentence" "0" 219 | "unlocked_sound" "0" 220 | "locked_sound" "0" 221 | "health" "0" 222 | "delay" "0" 223 | "dmg" "0" 224 | "lip" "0" 225 | "wait" "4" 226 | "stopsnd" "0" 227 | "movesnd" "0" 228 | "speed" "100" 229 | "renderamt" "50" 230 | "rendermode" "2" 231 | "classname" "func_water" 232 | } 233 | { 234 | "model" "*9" 235 | "classname" "func_ladder" 236 | } 237 | { 238 | "model" "*10" 239 | "rendercolor" "0 0 0" 240 | "renderamt" "255" 241 | "rendermode" "4" 242 | "classname" "func_wall" 243 | } 244 | { 245 | "model" "*11" 246 | "classname" "func_ladder" 247 | } 248 | { 249 | "model" "*12" 250 | "renderamt" "255" 251 | "rendermode" "4" 252 | "classname" "func_wall" 253 | } 254 | { 255 | "origin" "-72 -2540 446" 256 | "pitch" "-60" 257 | "_light" "255 255 128 90" 258 | "classname" "light_environment" 259 | } 260 | { 261 | "origin" "584 -816 450" 262 | "pitch" "-60" 263 | "_light" "255 255 128 90" 264 | "classname" "light_environment" 265 | } 266 | { 267 | "origin" "292 -2479 -124" 268 | "classname" "info_hostage_rescue" 269 | } 270 | { 271 | "model" "*13" 272 | "skin" "-1" 273 | "renderamt" "255" 274 | "rendermode" "4" 275 | "classname" "func_illusionary" 276 | } 277 | { 278 | "model" "*14" 279 | "classname" "func_ladder" 280 | } 281 | { 282 | "model" "*15" 283 | "unlocked_sentence" "0" 284 | "locked_sentence" "0" 285 | "unlocked_sound" "0" 286 | "locked_sound" "0" 287 | "delay" "0" 288 | "wait" "3" 289 | "lip" "0" 290 | "health" "0" 291 | "target" "CAMERA1" 292 | "speed" "5" 293 | "rendercolor" "0 0 0" 294 | "renderamt" "0" 295 | "rendermode" "0" 296 | "renderfx" "0" 297 | "sounds" "0" 298 | "spawnflags" "33" 299 | "classname" "func_button" 300 | } 301 | { 302 | "origin" "-111 1075 -41" 303 | "deceleration" "500" 304 | "acceleration" "500" 305 | "speed" "0" 306 | "wait" "10" 307 | "targetname" "CAMERA2" 308 | "delay" "0" 309 | "target" "CAMLOOK2" 310 | "classname" "trigger_camera" 311 | } 312 | { 313 | "origin" "160 760 -82" 314 | "targetname" "CAMLOOK2" 315 | "classname" "info_target" 316 | } 317 | { 318 | "model" "*16" 319 | "unlocked_sentence" "0" 320 | "locked_sentence" "0" 321 | "unlocked_sound" "0" 322 | "locked_sound" "0" 323 | "delay" "0" 324 | "wait" "3" 325 | "lip" "0" 326 | "health" "0" 327 | "target" "CAMERA2" 328 | "speed" "5" 329 | "rendercolor" "0 0 0" 330 | "renderamt" "0" 331 | "rendermode" "0" 332 | "renderfx" "0" 333 | "sounds" "0" 334 | "spawnflags" "33" 335 | "classname" "func_button" 336 | } 337 | { 338 | "model" "*17" 339 | "sounds" "0" 340 | "target" "CAMERA3" 341 | "spawnflags" "33" 342 | "classname" "func_button" 343 | } 344 | { 345 | "origin" "-190 -49 139" 346 | "deceleration" "500" 347 | "acceleration" "500" 348 | "speed" "0" 349 | "wait" "10" 350 | "targetname" "CAMERA4" 351 | "delay" "0" 352 | "target" "CAMLOOK4" 353 | "angle" "315" 354 | "classname" "trigger_camera" 355 | } 356 | { 357 | "origin" "460 -295 -147" 358 | "targetname" "CAMLOOK4" 359 | "classname" "info_target" 360 | } 361 | { 362 | "origin" "868 -1392 52" 363 | "deceleration" "500" 364 | "acceleration" "500" 365 | "speed" "0" 366 | "wait" "10" 367 | "targetname" "CAMERA5" 368 | "delay" "0" 369 | "target" "CAMLOOK5" 370 | "angle" "190" 371 | "classname" "trigger_camera" 372 | } 373 | { 374 | "origin" "156 -1544 -136" 375 | "targetname" "CAMLOOK5" 376 | "classname" "info_target" 377 | } 378 | { 379 | "model" "*18" 380 | "unlocked_sentence" "0" 381 | "locked_sentence" "0" 382 | "unlocked_sound" "0" 383 | "locked_sound" "0" 384 | "delay" "0" 385 | "wait" "3" 386 | "lip" "0" 387 | "health" "0" 388 | "target" "CAMERA4" 389 | "speed" "5" 390 | "rendercolor" "0 0 0" 391 | "renderamt" "0" 392 | "rendermode" "0" 393 | "renderfx" "0" 394 | "sounds" "0" 395 | "spawnflags" "33" 396 | "classname" "func_button" 397 | } 398 | { 399 | "model" "*19" 400 | "unlocked_sentence" "0" 401 | "locked_sentence" "0" 402 | "unlocked_sound" "0" 403 | "locked_sound" "0" 404 | "delay" "0" 405 | "wait" "3" 406 | "lip" "0" 407 | "health" "0" 408 | "target" "CAMERA5" 409 | "speed" "5" 410 | "rendercolor" "0 0 0" 411 | "renderamt" "0" 412 | "rendermode" "0" 413 | "renderfx" "0" 414 | "sounds" "0" 415 | "spawnflags" "33" 416 | "classname" "func_button" 417 | } 418 | { 419 | "origin" "328 -1512 450" 420 | "pitch" "-60" 421 | "_light" "255 255 128 90" 422 | "classname" "light_environment" 423 | } 424 | { 425 | "model" "*20" 426 | "origin" "1208 337 -109" 427 | "unlocked_sentence" "0" 428 | "locked_sentence" "0" 429 | "unlocked_sound" "0" 430 | "locked_sound" "0" 431 | "health" "0" 432 | "delay" "0" 433 | "dmg" "0" 434 | "lip" "0" 435 | "wait" "4" 436 | "stopsnd" "0" 437 | "movesnd" "0" 438 | "speed" "100" 439 | "rendercolor" "0 0 0" 440 | "renderamt" "0" 441 | "rendermode" "0" 442 | "renderfx" "0" 443 | "angles" "0 0 0" 444 | "distance" "90" 445 | "classname" "func_door_rotating" 446 | } 447 | { 448 | "model" "*21" 449 | "classname" "func_ladder" 450 | } 451 | { 452 | "model" "*22" 453 | "skin" "-1" 454 | "renderamt" "255" 455 | "rendermode" "4" 456 | "classname" "func_illusionary" 457 | } 458 | { 459 | "origin" "-92 -1491 -259" 460 | "style" "32" 461 | "targetname" "slight" 462 | "_light" "255 255 255 100" 463 | "classname" "light" 464 | } 465 | { 466 | "style" "32" 467 | "origin" "-343 1637 -259" 468 | "targetname" "slight" 469 | "_light" "255 255 255 100" 470 | "angle" "5" 471 | "classname" "light" 472 | } 473 | { 474 | "model" "*23" 475 | "classname" "func_ladder" 476 | } 477 | { 478 | "model" "*24" 479 | "skin" "-1" 480 | "renderamt" "255" 481 | "rendermode" "4" 482 | "classname" "func_illusionary" 483 | } 484 | { 485 | "origin" "1762 264 -326" 486 | "targetname" "CAMLOOK3" 487 | "classname" "info_target" 488 | } 489 | { 490 | "origin" "1744 1119 -250" 491 | "deceleration" "500" 492 | "acceleration" "500" 493 | "speed" "0" 494 | "wait" "10" 495 | "targetname" "CAMERA3" 496 | "delay" "0" 497 | "target" "CAMLOOK3" 498 | "angle" "270" 499 | "classname" "trigger_camera" 500 | } 501 | { 502 | "style" "32" 503 | "origin" "802 1101 -259" 504 | "targetname" "slight" 505 | "_light" "255 255 255 100" 506 | "angle" "88" 507 | "classname" "light" 508 | } 509 | { 510 | "origin" "236 1632 -355" 511 | "preset" "0" 512 | "cspinup" "0" 513 | "lfomodvol" "0" 514 | "lfomodpitch" "0" 515 | "lforate" "0" 516 | "lfotype" "0" 517 | "spindown" "0" 518 | "spinup" "0" 519 | "pitchstart" "100" 520 | "pitch" "100" 521 | "health" "10" 522 | "fadeout" "0" 523 | "fadein" "0" 524 | "volstart" "0" 525 | "message" "ambience/drips.wav" 526 | "spawnflags" "2" 527 | "classname" "ambient_generic" 528 | } 529 | { 530 | "origin" "1761 429 -355" 531 | "lforate" "0" 532 | "lfotype" "0" 533 | "spinup" "0" 534 | "pitchstart" "100" 535 | "pitch" "100" 536 | "fadeout" "0" 537 | "preset" "0" 538 | "cspinup" "0" 539 | "lfomodvol" "0" 540 | "lfomodpitch" "0" 541 | "spindown" "0" 542 | "fadein" "0" 543 | "volstart" "0" 544 | "health" "10" 545 | "message" "ambience/drips.wav" 546 | "spawnflags" "2" 547 | "classname" "ambient_generic" 548 | } 549 | { 550 | "origin" "249 -1493 -355" 551 | "cspinup" "0" 552 | "lfomodvol" "0" 553 | "lfomodpitch" "0" 554 | "lforate" "0" 555 | "lfotype" "0" 556 | "spindown" "0" 557 | "spinup" "0" 558 | "pitchstart" "100" 559 | "pitch" "100" 560 | "fadeout" "0" 561 | "fadein" "0" 562 | "volstart" "0" 563 | "preset" "0" 564 | "health" "10" 565 | "message" "ambience/drips.wav" 566 | "spawnflags" "2" 567 | "classname" "ambient_generic" 568 | } 569 | { 570 | "style" "32" 571 | "origin" "678 -403 -259" 572 | "targetname" "slight" 573 | "_light" "255 255 255 100" 574 | "classname" "light" 575 | } 576 | { 577 | "style" "32" 578 | "origin" "1762 -403 -259" 579 | "targetname" "slight" 580 | "_light" "255 255 255 100" 581 | "angle" "90" 582 | "classname" "light" 583 | } 584 | { 585 | "style" "32" 586 | "origin" "1762 1101 -259" 587 | "targetname" "slight" 588 | "_light" "255 255 255 100" 589 | "angle" "180" 590 | "classname" "light" 591 | } 592 | { 593 | "origin" "802 1637 -259" 594 | "targetname" "slight" 595 | "style" "32" 596 | "_light" "255 255 255 100" 597 | "angle" "183" 598 | "classname" "light" 599 | } 600 | { 601 | "model" "*25" 602 | "skin" "-1" 603 | "rendercolor" "0 0 0" 604 | "renderfx" "0" 605 | "renderamt" "255" 606 | "rendermode" "4" 607 | "classname" "func_illusionary" 608 | } 609 | { 610 | "model" "*26" 611 | "origin" "604 660 -102" 612 | "unlocked_sentence" "0" 613 | "locked_sentence" "0" 614 | "unlocked_sound" "0" 615 | "locked_sound" "0" 616 | "health" "0" 617 | "delay" "0" 618 | "dmg" "0" 619 | "lip" "0" 620 | "wait" "4" 621 | "stopsnd" "0" 622 | "movesnd" "9" 623 | "speed" "100" 624 | "rendercolor" "0 0 0" 625 | "renderamt" "0" 626 | "rendermode" "0" 627 | "renderfx" "0" 628 | "angles" "0 0 0" 629 | "distance" "90" 630 | "classname" "func_door_rotating" 631 | } 632 | { 633 | "model" "*27" 634 | "origin" "297 1095 -105" 635 | "unlocked_sentence" "0" 636 | "locked_sentence" "0" 637 | "unlocked_sound" "0" 638 | "locked_sound" "0" 639 | "health" "0" 640 | "delay" "0" 641 | "dmg" "0" 642 | "lip" "0" 643 | "stopsnd" "0" 644 | "speed" "100" 645 | "rendercolor" "0 0 0" 646 | "renderamt" "0" 647 | "rendermode" "0" 648 | "renderfx" "0" 649 | "wait" "3" 650 | "movesnd" "9" 651 | "angles" "0 0 0" 652 | "distance" "90" 653 | "classname" "func_door_rotating" 654 | } 655 | { 656 | "model" "*28" 657 | "origin" "297 1095 38" 658 | "unlocked_sentence" "0" 659 | "locked_sentence" "0" 660 | "unlocked_sound" "0" 661 | "locked_sound" "0" 662 | "health" "0" 663 | "delay" "0" 664 | "dmg" "0" 665 | "lip" "0" 666 | "wait" "3" 667 | "stopsnd" "0" 668 | "movesnd" "9" 669 | "rendercolor" "0 0 0" 670 | "renderamt" "0" 671 | "rendermode" "0" 672 | "renderfx" "0" 673 | "speed" "100" 674 | "angles" "0 0 0" 675 | "distance" "90" 676 | "classname" "func_door_rotating" 677 | } 678 | { 679 | "model" "*29" 680 | "unlocked_sentence" "0" 681 | "locked_sentence" "0" 682 | "unlocked_sound" "0" 683 | "locked_sound" "0" 684 | "delay" "0" 685 | "wait" "1" 686 | "lip" "0" 687 | "health" "0" 688 | "target" "shack" 689 | "speed" "5" 690 | "rendercolor" "0 0 0" 691 | "renderamt" "0" 692 | "rendermode" "0" 693 | "renderfx" "0" 694 | "sounds" "0" 695 | "spawnflags" "1" 696 | "classname" "func_button" 697 | } 698 | { 699 | "origin" "1024 420 -80" 700 | "targetname" "shack" 701 | "style" "33" 702 | "_light" "242 249 198 100" 703 | "angle" "-2" 704 | "classname" "light" 705 | } 706 | { 707 | "origin" "762 420 -80" 708 | "targetname" "shack" 709 | "style" "33" 710 | "_light" "242 249 198 100" 711 | "angle" "-2" 712 | "classname" "light" 713 | } 714 | { 715 | "origin" "316 866 21" 716 | "angle" "228" 717 | "classname" "info_player_deathmatch" 718 | } 719 | { 720 | "origin" "948 344 -157" 721 | "body" "2" 722 | "gravity" "1" 723 | "model" "models/scientist.mdl" 724 | "angle" "90" 725 | "classname" "hostage_entity" 726 | } 727 | { 728 | "origin" "1111 340 -119" 729 | "targetname" "CAMLOOK1" 730 | "classname" "info_target" 731 | } 732 | { 733 | "origin" "981 258 -157" 734 | "body" "2" 735 | "gravity" "1" 736 | "model" "models/scientist.mdl" 737 | "angle" "82" 738 | "classname" "hostage_entity" 739 | } 740 | { 741 | "origin" "643 566 -62" 742 | "deceleration" "500" 743 | "acceleration" "500" 744 | "speed" "0" 745 | "wait" "10" 746 | "targetname" "CAMERA1" 747 | "delay" "0" 748 | "target" "CAMLOOK1" 749 | "angle" "270" 750 | "classname" "trigger_camera" 751 | } 752 | { 753 | "model" "*30" 754 | "origin" "-265 298 -106" 755 | "unlocked_sentence" "0" 756 | "locked_sentence" "0" 757 | "unlocked_sound" "0" 758 | "locked_sound" "0" 759 | "health" "0" 760 | "delay" "0" 761 | "dmg" "0" 762 | "lip" "0" 763 | "stopsnd" "0" 764 | "rendermode" "0" 765 | "renderfx" "0" 766 | "angles" "0 0 0" 767 | "distance" "90" 768 | "wait" "3" 769 | "movesnd" "9" 770 | "speed" "100" 771 | "rendercolor" "0 0 0" 772 | "renderamt" "0" 773 | "classname" "func_door_rotating" 774 | } 775 | { 776 | "model" "*31" 777 | "explodemagnitude" "0" 778 | "spawnobject" "0" 779 | "explosion" "0" 780 | "material" "0" 781 | "delay" "0" 782 | "health" "1" 783 | "rendercolor" "0 0 0" 784 | "renderfx" "0" 785 | "renderamt" "90" 786 | "rendermode" "2" 787 | "classname" "func_breakable" 788 | } 789 | { 790 | "model" "*32" 791 | "explodemagnitude" "0" 792 | "spawnobject" "0" 793 | "explosion" "0" 794 | "material" "0" 795 | "rendercolor" "0 0 0" 796 | "renderamt" "90" 797 | "rendermode" "2" 798 | "renderfx" "0" 799 | "delay" "0" 800 | "health" "1" 801 | "classname" "func_breakable" 802 | } 803 | { 804 | "model" "*33" 805 | "explodemagnitude" "0" 806 | "spawnobject" "0" 807 | "explosion" "0" 808 | "material" "0" 809 | "delay" "0" 810 | "health" "1" 811 | "renderamt" "90" 812 | "rendermode" "2" 813 | "classname" "func_breakable" 814 | } 815 | { 816 | "model" "*34" 817 | "rendercolor" "0 0 0" 818 | "renderfx" "0" 819 | "delay" "0" 820 | "explodemagnitude" "0" 821 | "spawnobject" "0" 822 | "explosion" "0" 823 | "material" "0" 824 | "health" "1" 825 | "renderamt" "90" 826 | "rendermode" "2" 827 | "classname" "func_breakable" 828 | } 829 | { 830 | "model" "*35" 831 | "explodemagnitude" "0" 832 | "spawnobject" "0" 833 | "explosion" "0" 834 | "material" "0" 835 | "delay" "0" 836 | "rendercolor" "0 0 0" 837 | "renderfx" "0" 838 | "health" "1" 839 | "renderamt" "90" 840 | "rendermode" "2" 841 | "classname" "func_breakable" 842 | } 843 | { 844 | "model" "*36" 845 | "rendercolor" "0 0 0" 846 | "renderfx" "0" 847 | "delay" "0" 848 | "explodemagnitude" "0" 849 | "spawnobject" "0" 850 | "explosion" "0" 851 | "material" "0" 852 | "health" "1" 853 | "renderamt" "90" 854 | "rendermode" "2" 855 | "classname" "func_breakable" 856 | } 857 | { 858 | "model" "*37" 859 | "rendercolor" "0 0 0" 860 | "renderfx" "0" 861 | "delay" "0" 862 | "explodemagnitude" "0" 863 | "spawnobject" "0" 864 | "explosion" "0" 865 | "material" "0" 866 | "health" "1" 867 | "renderamt" "90" 868 | "rendermode" "2" 869 | "classname" "func_breakable" 870 | } 871 | { 872 | "model" "*38" 873 | "origin" "81 -1426 -306" 874 | "_minlight" "0" 875 | "delay" "0" 876 | "wait" "3" 877 | "health" "0" 878 | "speed" "150" 879 | "target" "slight" 880 | "angles" "0 0 0" 881 | "distance" "180" 882 | "sounds" "24" 883 | "spawnflags" "97" 884 | "classname" "func_rot_button" 885 | } 886 | { 887 | "style" "32" 888 | "origin" "99 1637 -250" 889 | "targetname" "slight" 890 | "_light" "255 255 255 100" 891 | "angle" "90" 892 | "classname" "light" 893 | } 894 | { 895 | "style" "32" 896 | "origin" "403 1637 -250" 897 | "targetname" "slight" 898 | "_light" "255 255 255 100" 899 | "angle" "90" 900 | "classname" "light" 901 | } 902 | { 903 | "style" "32" 904 | "origin" "1282 1101 -259" 905 | "targetname" "slight" 906 | "_light" "255 255 255 100" 907 | "angle" "90" 908 | "classname" "light" 909 | } 910 | { 911 | "style" "32" 912 | "origin" "1762 793 -259" 913 | "targetname" "slight" 914 | "_light" "255 255 255 100" 915 | "angle" "90" 916 | "classname" "light" 917 | } 918 | { 919 | "style" "32" 920 | "origin" "1762 -17 -259" 921 | "targetname" "slight" 922 | "_light" "255 255 255 100" 923 | "angle" "90" 924 | "classname" "light" 925 | } 926 | { 927 | "style" "32" 928 | "origin" "1220 -403 -259" 929 | "targetname" "slight" 930 | "_light" "255 255 255 100" 931 | "angle" "90" 932 | "classname" "light" 933 | } 934 | { 935 | "style" "32" 936 | "origin" "678 -947 -259" 937 | "targetname" "slight" 938 | "_light" "255 255 255 100" 939 | "angle" "90" 940 | "classname" "light" 941 | } 942 | { 943 | "style" "32" 944 | "origin" "678 -1491 -259" 945 | "targetname" "slight" 946 | "_light" "255 255 255 100" 947 | "angle" "90" 948 | "classname" "light" 949 | } 950 | { 951 | "style" "32" 952 | "origin" "678 -1219 -309" 953 | "targetname" "slight" 954 | "_light" "255 255 255 100" 955 | "angle" "90" 956 | "classname" "light" 957 | } 958 | { 959 | "style" "32" 960 | "origin" "678 -675 -309" 961 | "targetname" "slight" 962 | "_light" "255 255 255 100" 963 | "angle" "90" 964 | "classname" "light" 965 | } 966 | { 967 | "style" "32" 968 | "origin" "949 -403 -309" 969 | "targetname" "slight" 970 | "_light" "255 255 255 100" 971 | "angle" "90" 972 | "classname" "light" 973 | } 974 | { 975 | "style" "32" 976 | "origin" "1491 -403 -309" 977 | "targetname" "slight" 978 | "_light" "255 255 255 100" 979 | "angle" "90" 980 | "classname" "light" 981 | } 982 | { 983 | "style" "32" 984 | "origin" "1762 -210 -309" 985 | "targetname" "slight" 986 | "_light" "255 255 255 100" 987 | "angle" "90" 988 | "classname" "light" 989 | } 990 | { 991 | "style" "32" 992 | "origin" "1762 183 -309" 993 | "targetname" "slight" 994 | "_light" "255 255 255 100" 995 | "angle" "90" 996 | "classname" "light" 997 | } 998 | { 999 | "style" "32" 1000 | "origin" "1762 620 -309" 1001 | "targetname" "slight" 1002 | "_light" "255 255 255 100" 1003 | "angle" "90" 1004 | "classname" "light" 1005 | } 1006 | { 1007 | "style" "32" 1008 | "origin" "1522 1101 -309" 1009 | "targetname" "slight" 1010 | "_light" "255 255 255 100" 1011 | "angle" "90" 1012 | "classname" "light" 1013 | } 1014 | { 1015 | "style" "32" 1016 | "origin" "1042 1101 -309" 1017 | "targetname" "slight" 1018 | "_light" "255 255 255 100" 1019 | "angle" "90" 1020 | "classname" "light" 1021 | } 1022 | { 1023 | "style" "32" 1024 | "origin" "802 1369 -309" 1025 | "targetname" "slight" 1026 | "_light" "255 255 255 100" 1027 | "angle" "90" 1028 | "classname" "light" 1029 | } 1030 | { 1031 | "style" "32" 1032 | "origin" "1762 947 -309" 1033 | "targetname" "slight" 1034 | "_light" "255 255 255 100" 1035 | "angle" "90" 1036 | "classname" "light" 1037 | } 1038 | { 1039 | "style" "32" 1040 | "origin" "1760 428 -309" 1041 | "targetname" "slight" 1042 | "_light" "255 255 255 80" 1043 | "angle" "90" 1044 | "classname" "light" 1045 | } 1046 | { 1047 | "model" "*39" 1048 | "rendercolor" "0 0 0" 1049 | "renderfx" "0" 1050 | "explodemagnitude" "0" 1051 | "spawnobject" "0" 1052 | "explosion" "0" 1053 | "material" "2" 1054 | "health" "1" 1055 | "delay" "0" 1056 | "renderamt" "255" 1057 | "rendermode" "4" 1058 | "classname" "func_breakable" 1059 | } 1060 | { 1061 | "model" "*40" 1062 | "rendercolor" "0 0 0" 1063 | "renderamt" "0" 1064 | "rendermode" "0" 1065 | "renderfx" "0" 1066 | "skin" "-1" 1067 | "classname" "func_illusionary" 1068 | } 1069 | { 1070 | "model" "*41" 1071 | "target" "boom" 1072 | "rendercolor" "0 0 0" 1073 | "renderamt" "0" 1074 | "rendermode" "0" 1075 | "renderfx" "0" 1076 | "explodemagnitude" "0" 1077 | "spawnobject" "0" 1078 | "explosion" "0" 1079 | "material" "3" 1080 | "health" "100" 1081 | "delay" "0" 1082 | "classname" "func_breakable" 1083 | } 1084 | { 1085 | "origin" "406 930 24" 1086 | "iMagnitude" "60" 1087 | "targetname" "boom" 1088 | "spawnflags" "3" 1089 | "classname" "env_explosion" 1090 | } 1091 | -------------------------------------------------------------------------------- /Assets/Docs/Unofficial_BSPv30_FileSpec.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | The hlbsp Project 8 | 9 | 10 | 11 | 12 |
17 |

Unofficial BSP v30 File Spec

18 | 19 |

Table of content

20 |
    21 |
  1. Introduction
  2. 22 |
  3. Header
  4. 23 |
  5. LUMP_ENTITIES
  6. 24 |
  7. LUMP_PLANES
  8. 25 |
  9. LUMP_TEXTURES
  10. 26 |
  11. LUMP_VERTICES
  12. 27 |
  13. LUMP_VISIBILITY
  14. 28 |
  15. LUMP_NODES
  16. 29 |
  17. LUMP_TEXINFO
  18. 30 |
  19. LUMP_FACES
  20. 31 |
  21. LUMP_LIGHTING
  22. 32 |
  23. LUMP_CLIPNODES
  24. 33 |
  25. LUMP_LEAVES
  26. 34 |
  27. LUMP_MARKSURFACES
  28. 35 |
  29. LUMP_EDGES
  30. 36 |
  31. LUMP_SURFEDGES
  32. 37 |
  33. LUMP_MODELS
  34. 38 |
39 | 40 |

Introduction

41 | 42 |

43 | The following file specification concerns the BSP file format version 44 | 30, as it has been designed by the game developper Valve and used in 45 | their famous GoldSrc Engine. The file extension is ".bsp". 46 |

47 | 48 |

49 | Important: The following informations do NOT rely on any 50 | officially published file specification from Valve Corporation. 51 | The file format is still in use by the proprietary Half-Life Engine 52 | (better known name of the GoldSrc Engine) implying that there is no 53 | public source code of either the file loader or renderer. 54 | The following specification has been put together based on informations 55 | from the open source project Black Engine as well as the compilers included in the Half-Life SDK which also contains their source. 56 |

57 | 58 |

59 | This file spec uses constructs from the C programming language to 60 | describe the different data structures used in the BSP file format. 61 | Architecture dependent datatypes like integers are replaced by 62 | exact-width integer types of the C99 standard in the stdint.h header 63 | file, to provide more flexibillity when using x64 platforms. 64 | Basic knowledge about Binary Space Partitioning 65 | is recommended. 66 | 67 | There is a common struct used to represent a point in 3-dimensional 68 | space which is used throughout the file spec and the code of the hlbsp 69 | project. 70 |

71 | 72 |

73 | #include <stdint.h>
74 |
75 | typedef struct _VECTOR3D
76 | {
77 |     float x, y, z;
78 | } VECTOR3D;
79 |  
80 |

Header

81 | 82 |

83 | Like almost every file also a BSP file starts with a specific file header which is constucted as follows: 84 |

85 | 86 |

87 | #define LUMP_ENTITIES      0
88 | #define LUMP_PLANES        1
89 | #define LUMP_TEXTURES      2
90 | #define LUMP_VERTICES      3
91 | #define LUMP_VISIBILITY    4
92 | #define LUMP_NODES         5
93 | #define LUMP_TEXINFO       6
94 | #define LUMP_FACES         7
95 | #define LUMP_LIGHTING      8
96 | #define LUMP_CLIPNODES     9
97 | #define LUMP_LEAVES       10
98 | #define LUMP_MARKSURFACES 11
99 | #define LUMP_EDGES        12
100 | #define LUMP_SURFEDGES    13
101 | #define LUMP_MODELS       14
102 | #define HEADER_LUMPS      15
103 |
104 | typedef struct _BSPHEADER
105 | {
106 |     int32_t nVersion;           // Must be 30 for a valid HL BSP file
107 |     BSPLUMP lump[HEADER_LUMPS]; // Stores the directory of lumps
108 | } BSPHEADER;
109 |  
110 |

111 | The file header begins with an 32bit integer containing the file version 112 | of the BSP file (the magic number). This should be 30 for a valid BSP 113 | file used by the Half-Life Engine. 114 | Subseqently, there is an array of entries for the so-called lumps. A 115 | lump is more or less a section of the file containing a specific type of 116 | data. The lump entries in the file header address these lumps, accessed 117 | by the 15 predefined indexes. A lump entry struct is defined as 118 | follows: 119 |

120 | 121 |

122 | typedef struct _BSPLUMP
123 | {
124 |     int32_t nOffset; // File offset to data
125 |     int32_t nLength; // Length of data
126 | } BSPLUMP;
127 |  
128 |

129 | To read the different lumps from the given BSP file, every lump entry 130 | file states the beginning of each lump as an offset relativly to the 131 | beginning of the file. Additionally, the lump entry also gives the 132 | length of the addressed lump in bytes. 133 | 134 | The Half-Life BSP compilers also define several constants for the 135 | maximum size of each lump, as they use static, global arrays to hold the 136 | data. The hlbsp project uses malloc() to allocate the required memory 137 | for each lump depending on their actual size. 138 |

139 | 140 |

141 | #define MAX_MAP_HULLS        4
142 |
143 | #define MAX_MAP_MODELS       400
144 | #define MAX_MAP_BRUSHES      4096
145 | #define MAX_MAP_ENTITIES     1024
146 | #define MAX_MAP_ENTSTRING    (128*1024)
147 |
148 | #define MAX_MAP_PLANES       32767
149 | #define MAX_MAP_NODES        32767
150 | #define MAX_MAP_CLIPNODES    32767
151 | #define MAX_MAP_LEAFS        8192
152 | #define MAX_MAP_VERTS        65535
153 | #define MAX_MAP_FACES        65535
154 | #define MAX_MAP_MARKSURFACES 65535
155 | #define MAX_MAP_TEXINFO      8192
156 | #define MAX_MAP_EDGES        256000
157 | #define MAX_MAP_SURFEDGES    512000
158 | #define MAX_MAP_TEXTURES     512
159 | #define MAX_MAP_MIPTEX       0x200000
160 | #define MAX_MAP_LIGHTING     0x200000
161 | #define MAX_MAP_VISIBILITY   0x200000
162 |
163 | #define MAX_MAP_PORTALS     65536
164 |  
165 |

166 | The following sections will focus on every lump of the BSP file. 167 |

168 | 169 |

The Entity Lump (LUMP_ENTITIES)

170 | 171 |

172 | The entity lump is basically a pure ASCII text section. It consists of 173 | the string representations of all entities, which are copied directly 174 | from the input file to the output BSP file by the compiler. 175 | An entity might look like this: 176 |

177 | 178 |

179 | {
180 | "origin" "0 0 -64"
181 | "angles" "0 0 0"
182 | "classname" "info_player_start"
183 | }
184 |  
185 |

186 | Every entity begins and ends with curly brackets. Inbetween there are 187 | the attributes of the entity, one in each line, which are pairs of 188 | strings enclosed by quotes. The first string is the name of the 189 | attribute (the key), the second one its value. The attribute "classname" 190 | is mandatory for every entity specifiying its type and therefore, how 191 | it is interpreted by the engine. 192 |

193 | 194 |

195 | The map compilers also define two constants for the maximum length of key and value: 196 |

197 | 198 |

199 | #define MAX_KEY     32
200 | #define MAX_VALUE   1024
201 |  
202 |

The Planes Lump (LUMP_PLANES)

203 | 204 |

205 | This lump is a simple array of binary data structures: 206 |

207 | 208 |

209 | #define PLANE_X 0     // Plane is perpendicular to given axis
210 | #define PLANE_Y 1
211 | #define PLANE_Z 2
212 | #define PLANE_ANYX 3  // Non-axial plane is snapped to the nearest
213 | #define PLANE_ANYY 4
214 | #define PLANE_ANYZ 5
215 |
216 | typedef struct _BSPPLANE
217 | {
218 |     VECTOR3D vNormal; // The planes normal vector
219 |     float fDist;      // Plane equation is: vNormal * X = fDist
220 |     int32_t nType;    // Plane type, see #defines
221 | } BSPPLANE;
222 |  
223 |

224 | Each of this structures defines a plane in 3-dimensional space by using the Hesse normal form: 225 |

226 | 227 |

228 | normal * point - distance = 0 229 |

230 | 231 |

232 | Where vNormal is the normalized normal vector of the plane and fDist is 233 | the distance of the plane to the origin of the coord system. 234 | Additionally, the structure also saves an integer describing the 235 | orientation of the plane in space. If nType equals PLANE_X, then the 236 | normal of the plane will be parallel to the x axis, meaning the plane is 237 | perpendicular to the x axis. If nType equals PLANE_ANYX, then the 238 | plane's normal is nearer to the x axis then to any other axis. This 239 | information is used by the renderer to speed up some computations. 240 |

241 | 242 |

The Texture Lump (LUMP_TEXTURES)

243 | 244 |

245 | The texture lump is somehow a bit more complex then the other lumps, 246 | because it is possible to save textures directly within the BSP file 247 | instead of storing them in external WAD files. This lump also starts with a small header: 248 |

249 | 250 |

251 | typedef struct _BSPTEXTUREHEADER
252 | {
253 |     uint32_t nMipTextures; // Number of BSPMIPTEX structures
254 | } BSPTEXTUREHEADER;
255 |  
256 |

257 | The header only consists of an unsigned 32bit integer indicating the 258 | number of stored or referenced textures in the texture lump. After the 259 | header follows an array of 32bit offsets pointing to the beginnings of 260 | the seperate textures. 261 |

262 | 263 |

264 | typedef int32_t BSPMIPTEXOFFSET;
265 |  
266 |

267 | Every offset gives the distance in bytes from the beginning of the 268 | texture lump to one of the beginnings of the BSPMIPTEX structure, which 269 | are equal in count to the value given in the texture header. 270 |

271 | 272 |

273 | #define MAXTEXTURENAME 16
274 | #define MIPLEVELS 4
275 | typedef struct _BSPMIPTEX
276 | {
277 |     char szName[MAXTEXTURENAME];  // Name of texture
278 |     uint32_t nWidth, nHeight;     // Extends of the texture
279 |     uint32_t nOffsets[MIPLEVELS]; // Offsets to texture mipmaps BSPMIPTEX;
280 | } BSPMIPTEX;
281 |  
282 |

283 | Each of this structs describes a texture. 284 | The name of the texture is a string and may be 16 characters long 285 | (including the null-character at the end, char equals a 8bit signed 286 | integer). 287 | The name of the texture is needed, if the texture has to be found and 288 | loaded from an external WAD file. Furthermore, the struct contains the 289 | width and height of the texture. 290 | The 4 offsets at the end can either be zero, if the texture is stored in 291 | an external WAD file, or point to the beginnings of the binary texture 292 | data within the texture lump relative to the beginning of it's BSPMIPTEX 293 | struct. 294 |

295 | 296 |

The Vertices Lump (LUMP_VERTICES)

297 | 298 |

299 | This lump simply consists of all vertices of the BSP tree. They are stored as a primitve array of triples of floats. 300 |

301 | 302 |

303 | typedef VECTOR3D BSPVERTEX;
304 |  
305 |

306 | Each of this triples, obviously, represents a point in 3-dimensional space by giving its three coordinates. 307 |

308 | 309 |

The VIS Lump (LUMP_VISIBILITY)

310 | 311 |

312 | The VIS lump contains data, which is irrelevant to the actual BSP tree, 313 | but offers a way to boost up the speed of the renderer significantly. 314 | Especially complex maps profit from the use if this data. This lump 315 | contains the so-called Potentially Visible Sets (PVS) (also called VIS 316 | lists) in the same amout of leaves of the tree, the user can enter 317 | (often referred to as VisLeaves). The visiblilty lists are stored as 318 | sequences of bitfields, which are run-length encoded.
319 | Important: The generation of the VIS data is a very time 320 | consuming process (several hours) and also done by a seperate compiler. 321 | It can therefore be skipped when compiling the map, resulting in BSP 322 | files with no VIS data at all! 323 |

324 | 325 |

The Nodes Lump (LUMP_NODES)

326 | 327 |

328 | This lump is simple again and contains an array of binary structures, the nodes, which are a major part of the BSP tree. 329 |

330 | 331 |

332 | typedef struct _BSPNODE
333 | {
334 |     uint32_t iPlane;            // Index into Planes lump
335 |     int16_t iChildren[2];       // If > 0, then indices into Nodes // otherwise bitwise inverse indices into Leafs
336 |     int16_t nMins[3], nMaxs[3]; // Defines bounding box
337 |     uint16_t firstFace, nFaces; // Index and count into Faces
338 | } BSPNODE;
339 |  
340 |

341 | Every BSPNODE structure represents a node in the BSP tree and every node 342 | equals more or less a division step of the BSP algorithm. Therefore, 343 | each node has an index (iPlane) referring to a plane in the plane lump 344 | which devides the node into its two child nodes. The childnodes are also 345 | stored as indexes. Contrary to the plane index, the node index for the 346 | child is signed. If the index is larger than 0, the index indicates a 347 | child node. If it is equal to or smaller than zero (no valid array 348 | index), the bitwise inversed value of the index gives an index into the 349 | leaves lump. Additionally two points (nMins, nMaxs) span the bounding 350 | box (AABB, axis aligned bounding box) delimitting the space of the node. 351 | Finally firstFace indexes into the face lump and spezifies the first of 352 | nFaces surfaces contained in this node. 353 |

354 | 355 |

The Texinfo Lump (LUMP_TEXINFO)

356 | 357 |

358 | The texinfo lump contains informations about how textures are applied to 359 | surfaces. The lump itself is an array of binary data structures. 360 |

361 | 362 |

363 | typedef struct _BSPTEXTUREINFO
364 | {
365 |     VECTOR3D vS;
366 |     float fSShift;    // Texture shift in s direction
367 |     VECTOR3D vT;
368 |     float fTShift;    // Texture shift in t direction
369 |     uint32_t iMiptex; // Index into textures array
370 |     uint32_t nFlags;  // Texture flags, seem to always be 0
371 | } BSPTEXTUREINFO;
372 |  

373 | This struct is mainly responsible for the calculation of the texture 374 | coordinates (vS, fSShift, vT, fTShift). This values determine the 375 | position of the texture on the surface. The iMiptex integer refers to 376 | the textures in the texture lump and would be the index in an array of 377 | BSPMITEX structs. Finally, there are 4 Bytes used for flags. Somehow 378 | they seem to always be 0; 379 |

380 | 381 |

The Faces Lump (LUMP_FACES)

382 | 383 |

384 | The face lump contains the surfaces of the scene. Once again an array of structs: 385 |

386 | 387 |

388 | typedef struct _BSPFACE
389 | {
390 |     uint16_t iPlane;          // Plane the face is parallel to
391 |     uint16_t nPlaneSide;      // Set if different normals orientation
392 |     uint32_t iFirstEdge;      // Index of the first surfedge
393 |     uint16_t nEdges;          // Number of consecutive surfedges
394 |     uint16_t iTextureInfo;    // Index of the texture info structure
395 |     uint8_t nStyles[4];       // Specify lighting styles
396 |     uint32_t nLightmapOffset; // Offsets into the raw lightmap data
397 | } BSPFACE;
398 |  
399 |

400 | The first number of this data structure is an index into the planes lump 401 | giving a plane which is parallel to this face (meaning they share the 402 | same normal). The second value may be seen as a boolean. If nPlaneSide 403 | equals 0, then the normal vector of this face equals the one of the 404 | parallel plane exactly. Otherwise, the normal of the plane has to be 405 | multiplied by -1 to point into the right direction. Afterwards we have 406 | an index into the surfedges lump, as well as the count of consecutive 407 | surfedges from that position. Furthermore there is an index into the 408 | texture info lump, which is used to find the BSPTEXINFO structure needed 409 | to calculate the texture coordinates for this face. Afterwards, there 410 | are four bytes giving some lighting information (partly used by the 411 | renderer to hide sky surfaces). Finally we have an offset in byes giving 412 | the beginning of the binary lightmap data of this face in the lighting 413 | lump. 414 |

415 | 416 |

The Lightmap Lump (LUMP_LIGHTING)

417 | 418 |

419 | This is one of the largest lumps in the BSP file. The lightmap lump 420 | stores all lightmaps used in the entire map. The lightmaps are arrays of 421 | triples of bytes (3 channel color, RGB) and stored continuously. 422 |

423 | 424 |

The Clipnodes Lump (LUMP_CLIPNODES)

425 | 426 |

427 | This lump contains the so-called clipnodes, which build a second BSP tree used only for collision detection. 428 |

429 | 430 |

431 | typedef struct _BSPCLIPNODE
432 | {
433 |     int32_t iPlane;       // Index into planes
434 |     int16_t iChildren[2]; // negative numbers are contents
435 | } BSPCLIPNODE;
436 |  
437 |

438 | This structure is a reduced form of the BSPNODE struct from the nodes 439 | lump. Also the BSP tree built by the clipnodes is simpler than the one 440 | described by the BSPNODEs to accelerate collision calculations. 441 |

442 | 443 |

The Leaves Lump (LUMP_LEAVES)

444 | 445 |

446 | The leaves lump contains the leaves of the BSP tree. Another array of binary structs: 447 |

448 | 449 |

450 | #define CONTENTS_EMPTY        -1
451 | #define CONTENTS_SOLID        -2
452 | #define CONTENTS_WATER        -3
453 | #define CONTENTS_SLIME        -4
454 | #define CONTENTS_LAVA         -5
455 | #define CONTENTS_SKY          -6
456 | #define CONTENTS_ORIGIN       -7
457 | #define CONTENTS_CLIP         -8
458 | #define CONTENTS_CURRENT_0    -9
459 | #define CONTENTS_CURRENT_90   -10
460 | #define CONTENTS_CURRENT_180  -11
461 | #define CONTENTS_CURRENT_270  -12
462 | #define CONTENTS_CURRENT_UP   -13
463 | #define CONTENTS_CURRENT_DOWN -14
464 | #define CONTENTS_TRANSLUCENT  -15
465 |
466 | typedef struct _BSPLEAF
467 | {
468 |     int32_t nContents;                         // Contents enumeration
469 |     int32_t nVisOffset;                        // Offset into the visibility lump
470 |     int16_t nMins[3], nMaxs[3];                // Defines bounding box
471 |     uint16_t iFirstMarkSurface, nMarkSurfaces; // Index and count into marksurfaces array
472 |     uint8_t nAmbientLevels[4];                 // Ambient sound levels
473 | } BSPLEAF;
474 |  
475 |

476 | The first entry of this struct is the type of the content of this leaf. 477 | It can be one of the predefined values, found in the compiler source 478 | codes, and is litte relevant for the actual rendering process. All the 479 | more important is the next integer containing the offset into the vis 480 | lump. It defines the start of the raw PVS data for this leaf. If this 481 | value equals -1, no VIS lists are available for this leaf, usually if 482 | the map has been built without the VIS compiler. The next two 16bit 483 | integer triples span the bounding box of this leaf. Furthermore, the 484 | struct contains an index pointing into the array of marksurfaces loaded 485 | from the marksufaces lump as well as the number of consecutive 486 | marksurfaces belonging to this leaf. The marksurfaces are looped through 487 | during the rendering process and point to the actual faces. The final 4 488 | bytes somehow spezify the volume of the ambient sounds. 489 |

490 | 491 |

The Marksurfaces Lump (LUMP_MARKSURFACES)

492 | 493 |

494 | The marksurfaces lump is a simple array of short integers. 495 |

496 | 497 |

498 | typedef uint16_t BSPMARKSURFACE;
499 |  
500 |

501 | This lump is a simple table for redirecting the marksurfaces indexes in 502 | the leafs to the actial face indexes. A leaf inserts it's marksurface 503 | indexes into this array and gets the associated faces contained within 504 | this leaf. 505 |

506 | 507 |

The Edges Lump (LUMP_EDGES)

508 | 509 |

510 | The edges are defined as an array of structs: 511 |

512 | 513 |

514 | typedef struct _BSPEDGE
515 | {
516 |     uint16_t iVertex[2]; // Indices into vertex array
517 | } BSPEDGE;
518 |  
519 |

520 | The edges delimit the face and further refer to the vertices of the 521 | face. Each edge is pointing to the start and end vertex of the edge. 522 |

523 | 524 |

The Surfedges Lump (LUMP_SURFEDGES)

525 | 526 |

527 | Another array of integers. 528 |

529 | 530 |

531 | typedef int32_t BSPSURFEDGE;
532 |  
533 |

534 | This lump represents pretty much the same mechanism as the marksurfaces. 535 | A face can insert its surfedge indexes into this array to get the 536 | corresponding edges delimitting the face and further pointing to the 537 | vertexes, which are required for rendering. The index can be positive or 538 | negative. If the value of the surfedge is positive, the first vertex of 539 | the edge is used as vertex for rendering the face, otherwise, the value 540 | is multiplied by -1 and the second vertex of the indexed edge is used. 541 |

542 | 543 |

The Models Lump (LUMP_MODELS)

544 | 545 |

546 | Array of structs: 547 |

548 | 549 |

550 | #define MAX_MAP_HULLS 4
551 |
552 | typedef struct _BSPMODEL
553 | {
554 |     float nMins[3], nMaxs[3];          // Defines bounding box
555 |     VECTOR3D vOrigin;                  // Coordinates to move the // coordinate system
556 |     int32_t iHeadnodes[MAX_MAP_HULLS]; // Index into nodes array
557 |     int32_t nVisLeafs;                 // ???
558 |     int32_t iFirstFace, nFaces;        // Index and count into faces
559 | } BSPMODEL;
560 |  
561 |

562 | A model is kind of a mini BSP tree. Its size is determinded by the 563 | bounding box spaned by the first to members of this struct. The major 564 | difference between a model and the BSP tree holding the scene is that 565 | the models use a local coordinate system for their vertexes and just 566 | state its origin in world coordinates. During rendering the coordinate 567 | system is translated to the origin of the model (glTranslate()) and 568 | moved back after the models BSP tree has been traversed. Furthermore 569 | their are 4 indexes into node arrays. The first one has proofed to index 570 | the root node of the mini BSP tree used for rendering. The other three 571 | indexes could probably be used for collision detection, meaning they 572 | point into the clipnodes, but I am not sure about this. The meaning of 573 | the next value is also somehow unclear to me. Finally their are direct 574 | indexes into the faces array, not taking the redirecting by the 575 | marksurfaces. 576 |

577 |
578 | 579 | 580 | --------------------------------------------------------------------------------