From 78401edeb890f54d579a654aeba41bb4edd21203 Mon Sep 17 00:00:00 2001 From: Markus Walther Date: Tue, 7 Dec 2021 22:03:12 +0000 Subject: [PATCH] implement Bsp.CRC32() - aka CRC_MapFile() --- .gitattributes | 1 + crc.go | 38 ++++++++++++++++++++++++++++++++++++++ crc_test.go | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 .gitattributes create mode 100644 crc.go create mode 100644 crc_test.go diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..bf70ec9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.bsp.gz filter=lfs diff=lfs merge=lfs -text diff --git a/crc.go b/crc.go new file mode 100644 index 0000000..7a1fb95 --- /dev/null +++ b/crc.go @@ -0,0 +1,38 @@ +package bsp + +import ( + "hash/crc32" + "sort" +) + +func (bsp *Bsp) CRC32() (uint32, error) { + const lumpCount = 64 + + crc := crc32.NewIEEE() + + lumpList := make([]LumpId, lumpCount) + for i := 0; i < lumpCount; i++ { + lumpList[i] = LumpId(i) + } + + sort.Slice(lumpList, func(i, j int) bool { + return bsp.header.Lumps[lumpList[i]].Offset < bsp.header.Lumps[lumpList[j]].Offset + }) + + for i := 0; i < lumpCount; i++ { + l := lumpList[i] + if l == LumpEntities { + continue + } + + _, err := crc.Write(bsp.RawLump(l).raw) + if err != nil { + return 0, err + } + } + + // see CRC32_Final + res := crc.Sum32() ^ 0xFFFFFFFF + + return res, nil +} diff --git a/crc_test.go b/crc_test.go new file mode 100644 index 0000000..fa31181 --- /dev/null +++ b/crc_test.go @@ -0,0 +1,37 @@ +package bsp_test + +import ( + "compress/gzip" + "os" + "testing" + + "github.com/galaco/bsp" +) + +func TestBsp_Crc(t *testing.T) { + f, err := os.Open("ar_baggage.bsp.gz") + if err != nil { + t.Error(err) + } + + gzR, err := gzip.NewReader(f) + if err != nil { + t.Error(err) + } + + bspF, err := bsp.ReadFromStream(gzR) + if err != nil { + t.Error(err) + } + + res, err := bspF.CRC32() + if err != nil { + t.Error("unexpected error:", err) + } + + const expected = 2836609078 + + if res != expected { + t.Errorf("CRC incorrect, expected %d got %d", expected, res) + } +}