1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 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
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package main

import (
	"encoding/binary"
	"fmt"
	"math"
	"strings"
	"testing"
)

// A cube, written in both STL flavours, is the fixture: it exercises every
// axis, has known dimensions, and lets the two parsers be checked against each
// other rather than against hand-written expectations.

// cubeTriangles returns the 12 triangles of an axis-aligned cube spanning
// [0,size]^3, as flat [9]float32 vertex triples.
func cubeTriangles(size float32) [][9]float32 {
	s := size
	// Eight corners.
	c := [8][3]float32{
		{0, 0, 0}, {s, 0, 0}, {s, s, 0}, {0, s, 0},
		{0, 0, s}, {s, 0, s}, {s, s, s}, {0, s, s},
	}
	quads := [6][4]int{
		{0, 3, 2, 1}, // bottom
		{4, 5, 6, 7}, // top
		{0, 1, 5, 4}, // front
		{2, 3, 7, 6}, // back
		{1, 2, 6, 5}, // right
		{0, 4, 7, 3}, // left
	}
	var out [][9]float32
	for _, q := range quads {
		for _, tri := range [2][3]int{{0, 1, 2}, {0, 2, 3}} {
			var t [9]float32
			for i, vi := range tri {
				v := c[q[vi]]
				t[i*3], t[i*3+1], t[i*3+2] = v[0], v[1], v[2]
			}
			out = append(out, t)
		}
	}
	return out
}

func binaryCubeSTL(size float32, withNormals bool) []byte {
	tris := cubeTriangles(size)
	buf := make([]byte, 84+len(tris)*50)
	copy(buf[:80], "binary cube fixture")
	binary.LittleEndian.PutUint32(buf[80:84], uint32(len(tris)))
	for i, t := range tris {
		off := 84 + i*50
		put := func(n int, v float32) {
			binary.LittleEndian.PutUint32(buf[off+n*4:], math.Float32bits(v))
		}
		if withNormals {
			nx, ny, nz := faceNormal(t)
			put(0, nx)
			put(1, ny)
			put(2, nz)
		}
		for v := 0; v < 9; v++ {
			put(3+v, t[v])
		}
	}
	return buf
}

func asciiCubeSTL(size float32) []byte {
	var b strings.Builder
	b.WriteString("solid cube\n")
	for _, t := range cubeTriangles(size) {
		nx, ny, nz := faceNormal(t)
		fmt.Fprintf(&b, "  facet normal %e %e %e\n    outer loop\n", nx, ny, nz)
		for v := 0; v < 3; v++ {
			fmt.Fprintf(&b, "      vertex %e %e %e\n", t[v*3], t[v*3+1], t[v*3+2])
		}
		b.WriteString("    endloop\n  endfacet\n")
	}
	b.WriteString("endsolid cube\n")
	return []byte(b.String())
}

func TestParseBinarySTL(t *testing.T) {
	m, err := parseSTL(binaryCubeSTL(10, true))
	if err != nil {
		t.Fatalf("parseSTL: %v", err)
	}
	if m.Triangles != 12 {
		t.Errorf("triangles = %d, want 12", m.Triangles)
	}
	if got, want := len(m.Verts), 12*3*vertexStride; got != want {
		t.Errorf("len(Verts) = %d, want %d", got, want)
	}
}

func TestParseASCIISTL(t *testing.T) {
	m, err := parseSTL(asciiCubeSTL(10))
	if err != nil {
		t.Fatalf("parseSTL: %v", err)
	}
	if m.Triangles != 12 {
		t.Errorf("triangles = %d, want 12", m.Triangles)
	}
}

// The two flavours describe the same solid, so after parsing they must yield
// the same buffer. This is the check that keeps the parsers from drifting.
func TestBinaryAndASCIIAgree(t *testing.T) {
	bin, err := parseSTL(binaryCubeSTL(10, true))
	if err != nil {
		t.Fatalf("binary: %v", err)
	}
	asc, err := parseSTL(asciiCubeSTL(10))
	if err != nil {
		t.Fatalf("ascii: %v", err)
	}
	if len(bin.Verts) != len(asc.Verts) {
		t.Fatalf("vertex count differs: binary %d, ascii %d", len(bin.Verts), len(asc.Verts))
	}
	for i := range bin.Verts {
		// The ASCII fixture round-trips through %e, so exact equality is not
		// available; a loose epsilon still catches any structural mismatch.
		if math.Abs(float64(bin.Verts[i]-asc.Verts[i])) > 1e-5 {
			t.Fatalf("vertex %d differs: binary %v, ascii %v", i, bin.Verts[i], asc.Verts[i])
		}
	}
}

// A binary STL whose 80-byte header starts with "solid" is a real-world
// export quirk that a naive prefix check would misparse as ASCII.
func TestBinarySTLWithSolidHeader(t *testing.T) {
	data := binaryCubeSTL(10, true)
	copy(data[:80], "solid created by some exporter")
	if !isBinarySTL(data) {
		t.Fatal("binary STL with 'solid' header detected as ASCII")
	}
	m, err := parseSTL(data)
	if err != nil {
		t.Fatalf("parseSTL: %v", err)
	}
	if m.Triangles != 12 {
		t.Errorf("triangles = %d, want 12", m.Triangles)
	}
}

// Zeroed normals are common in exported files; the parser must derive them
// rather than storing a zero vector, which would render the face unlit.
func TestZeroNormalsAreRecomputed(t *testing.T) {
	m, err := parseSTL(binaryCubeSTL(10, false))
	if err != nil {
		t.Fatalf("parseSTL: %v", err)
	}
	for i := 0; i < len(m.Verts); i += vertexStride {
		nx, ny, nz := m.Verts[i+3], m.Verts[i+4], m.Verts[i+5]
		l := math.Sqrt(float64(nx*nx + ny*ny + nz*nz))
		if math.Abs(l-1) > 1e-4 {
			t.Fatalf("vertex %d has non-unit normal (%v, %v, %v), length %v", i/vertexStride, nx, ny, nz, l)
		}
	}
}

// Normalisation is what lets the viewer use one fixed camera for every model,
// so it must hold regardless of the model's original scale or position.
func TestNormalizeFitsUnitBox(t *testing.T) {
	for _, size := range []float32{0.5, 10, 250} {
		m, err := parseSTL(binaryCubeSTL(size, true))
		if err != nil {
			t.Fatalf("size %v: %v", size, err)
		}
		var minv, maxv [3]float32
		for a := 0; a < 3; a++ {
			minv[a], maxv[a] = math.MaxFloat32, -math.MaxFloat32
		}
		for i := 0; i < len(m.Verts); i += vertexStride {
			for a := 0; a < 3; a++ {
				v := m.Verts[i+a]
				if v < minv[a] {
					minv[a] = v
				}
				if v > maxv[a] {
					maxv[a] = v
				}
			}
		}
		for a := 0; a < 3; a++ {
			if d := maxv[a] - minv[a]; d > 1.0001 {
				t.Errorf("size %v: axis %d extent %v exceeds unit box", size, a, d)
			}
			if c := (minv[a] + maxv[a]) / 2; math.Abs(float64(c)) > 1e-5 {
				t.Errorf("size %v: axis %d not centred (centre %v)", size, a, c)
			}
		}
	}
}

// Malformed input arrives from the network, so the parser must reject it
// rather than panic or return a nonsensical mesh.
func TestParseSTLRejectsGarbage(t *testing.T) {
	cases := map[string][]byte{
		"empty":            {},
		"short":            []byte("solid"),
		"truncated binary": binaryCubeSTL(10, true)[:100],
		"text":             []byte("this is not an STL file at all\njust some prose\n"),
	}
	for name, data := range cases {
		t.Run(name, func(t *testing.T) {
			if _, err := parseSTL(data); err == nil {
				t.Error("expected an error, got nil")
			}
		})
	}
}

func TestPackMeshRoundTrip(t *testing.T) {
	m, err := parseSTL(binaryCubeSTL(10, true))
	if err != nil {
		t.Fatalf("parseSTL: %v", err)
	}
	packed := packMesh(m)
	if got, want := len(packed), len(m.Verts)*4; got != want {
		t.Fatalf("packed length = %d, want %d", got, want)
	}
	for i, want := range m.Verts {
		got := math.Float32frombits(binary.LittleEndian.Uint32(packed[i*4:]))
		if got != want {
			t.Fatalf("float %d: got %v, want %v", i, got, want)
		}
	}
}