/
write.go
86 lines (68 loc) · 2.08 KB
/
write.go
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
package splat
import (
"encoding/binary"
"fmt"
"io"
"math"
"github.com/EliCDavis/bitlib"
"github.com/EliCDavis/polyform/modeling"
"github.com/EliCDavis/vector/vector3"
)
const SH_C0 = 0.28209479177387814
// https://github.com/antimatter15/splat/blob/main/convert.py#L10
func Write(out io.Writer, mesh modeling.Mesh) error {
if mesh.AttributeLength() == 0 {
return nil
}
requiredAttributes := []string{
modeling.PositionAttribute,
modeling.ScaleAttribute,
modeling.FDCAttribute,
modeling.OpacityAttribute,
modeling.RotationAttribute,
}
if mesh.Topology() != modeling.PointTopology {
return fmt.Errorf("mesh must be point topology, was instead %s", mesh.Topology())
}
for _, attr := range requiredAttributes {
if !mesh.HasVertexAttribute(attr) {
return fmt.Errorf("required attribute not present on mesh: %s", attr)
}
}
count := mesh.PrimitiveCount()
posData := mesh.Float3Attribute(modeling.PositionAttribute)
scaleData := mesh.Float3Attribute(modeling.ScaleAttribute)
fdcData := mesh.Float3Attribute(modeling.FDCAttribute)
opacityData := mesh.Float1Attribute(modeling.OpacityAttribute)
rotationData := mesh.Float4Attribute(modeling.RotationAttribute)
writer := bitlib.NewWriter(out, binary.LittleEndian)
for i := 0; i < count; i++ {
pos := posData.At(i)
writer.Float32(float32(pos.X()))
writer.Float32(float32(pos.Y()))
writer.Float32(float32(pos.Z()))
scale := scaleData.At(i)
writer.Float32(float32(math.Exp(scale.X())))
writer.Float32(float32(math.Exp(scale.Y())))
writer.Float32(float32(math.Exp(scale.Z())))
color := fdcData.
At(i).
Scale(SH_C0).
Add(vector3.Fill(0.5)).
Clamp(0, 1)
writer.Byte(byte(color.X() * 255))
writer.Byte(byte(color.Y() * 255))
writer.Byte(byte(color.Z() * 255))
alpha := 1. / (1 + math.Exp(-opacityData.At(i)))
writer.Byte(byte(alpha * 255))
rot := rotationData.At(i)
writer.Byte(byte(rot.X()*128) + 128)
writer.Byte(byte(rot.Y()*128) + 128)
writer.Byte(byte(rot.Z()*128) + 128)
writer.Byte(byte(rot.W()*128) + 128)
if writer.Error() != nil {
return writer.Error()
}
}
return nil
}