// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0. package spatialaudio import ( "encoding/json" "fmt" "math" "strings" ) const SceneTopic = "sverse.spatial.scene.v1" const SceneAckTopic = "sverse.spatial.scene.ack.v1" const MaxSceneBytes = 15000 type OcclusionConfig struct { Enabled bool `yaml:"enabled,omitempty"` MaxObjects int `yaml:"max_objects,omitempty"` } // Size is [width, height] in metres along local X/Y; local +Z is the // normal of a zero-thickness rectangle. Rotation is a unit quaternion xyzw. // Transmission is an amplitude multiplier, not a power ratio or dB value. type Obstacle struct { Priority *int `json:"priority,omitempty"` ID string `json:"id"` Center [3]float64 `json:"center"` Size []float64 `json:"size"` Rotation [4]float64 `json:"rotation"` Transmission *float64 `json:"transmission"` } type Scene struct { Adaptive *bool `json:"adaptive,omitempty"` HRTF *bool `json:"hrtf,omitempty"` Version int `json:"version"` Revision uint64 `json:"revision"` LocationID string `json:"location_id"` Enabled bool `json:"enabled"` Objects []Obstacle `json:"objects"` } type occluder struct { priority int center Vec3 half [2]float64 axes [3]Vec3 transmission float64 } type CompiledScene struct { Adaptive *bool HRTF *bool Revision uint64 Enabled bool Objects []occluder } func ParseScene(payload []byte, maxObjects int) (*CompiledScene, error) { if len(payload) == 0 || len(payload) > MaxSceneBytes { return nil, fmt.Errorf("scene exceeds %d bytes", MaxSceneBytes) } var scene Scene if err := json.Unmarshal(payload, &scene); err != nil { return nil, fmt.Errorf("invalid scene JSON: %w", err) } if scene.Version != 1 || scene.Revision == 0 || scene.Revision >= 1<<53 || strings.TrimSpace(scene.LocationID) == "" || len(scene.LocationID) > 100 { return nil, fmt.Errorf("invalid scene version, revision or location_id") } if len(scene.Objects) > maxObjects { return nil, fmt.Errorf("scene exceeds %d objects", maxObjects) } compiled := &CompiledScene{Revision: scene.Revision, Enabled: scene.Enabled, HRTF: scene.HRTF, Adaptive: scene.Adaptive} ids := make(map[string]bool, len(scene.Objects)) for _, object := range scene.Objects { priority := 100 if object.Priority != nil { priority = *object.Priority } if priority < 0 || priority > 100 { return nil, fmt.Errorf("invalid priority for obstacle %q", object.ID) } if strings.TrimSpace(object.ID) == "" || len(object.ID) > 64 || ids[object.ID] { return nil, fmt.Errorf("empty or duplicate obstacle id") } ids[object.ID] = true if len(object.Size) != 2 { return nil, fmt.Errorf("obstacle %q: size must contain width and height; volumetric walls are unsupported", object.ID) } for i := 0; i < 3; i++ { if !finite(object.Center[i]) || math.Abs(object.Center[i]) >= 1e7 { return nil, fmt.Errorf("invalid bounds for obstacle %q", object.ID) } } for _, size := range object.Size { if !finite(size) || size < 1e-4 || size > 1e6 { return nil, fmt.Errorf("invalid size for obstacle %q", object.ID) } } if object.Transmission == nil || !finite(*object.Transmission) || *object.Transmission < 0 || *object.Transmission > 1 { return nil, fmt.Errorf("invalid transmission for obstacle %q", object.ID) } q := Quaternion{object.Rotation[0], object.Rotation[1], object.Rotation[2], object.Rotation[3]} if !(Pose{Rotation: q}).Valid() { return nil, fmt.Errorf("invalid rotation for obstacle %q", object.ID) } n := math.Sqrt(q.X*q.X + q.Y*q.Y + q.Z*q.Z + q.W*q.W) q.X /= n q.Y /= n q.Z /= n q.W /= n compiled.Objects = append(compiled.Objects, occluder{ priority: priority, center: Vec3{object.Center[0], object.Center[1], object.Center[2]}, half: [2]float64{object.Size[0] / 2, object.Size[1] / 2}, axes: [3]Vec3{ {1 - 2*(q.Y*q.Y+q.Z*q.Z), 2 * (q.X*q.Y + q.Z*q.W), 2 * (q.X*q.Z - q.Y*q.W)}, q.Right(), {2 * (q.X*q.Z + q.Y*q.W), 2 * (q.Y*q.Z - q.X*q.W), 1 - 2*(q.X*q.X+q.Y*q.Y)}, }, transmission: *object.Transmission, }) } return compiled, nil } // Intersect a finite segment with a two-sided plane, then check the rectangle. // Parallel/coplanar segments do not cross the wall. Endpoint and edge contact // count when the segment is not parallel; no volume or thickness is involved. func (o occluder) intersects(a, b Vec3) bool { start := Vec3{a.X - o.center.X, a.Y - o.center.Y, a.Z - o.center.Z} delta := Vec3{b.X - a.X, b.Y - a.Y, b.Z - a.Z} dot := func(v, axis Vec3) float64 { return v.X*axis.X + v.Y*axis.Y + v.Z*axis.Z } distance := dot(start, o.axes[2]) denominator := dot(delta, o.axes[2]) if math.Abs(denominator) < 1e-10 { return false } t := -distance / denominator if t < 0 || t > 1 { return false } point := Vec3{start.X + t*delta.X, start.Y + t*delta.Y, start.Z + t*delta.Z} return math.Abs(dot(point, o.axes[0])) <= o.half[0]+1e-8 && math.Abs(dot(point, o.axes[1])) <= o.half[1]+1e-8 } func (s *CompiledScene) Transmission(a, b Vec3) float64 { return s.transmission(a, b, 0) } func (s *CompiledScene) activeObjects(minPriority int) int { if s == nil || !s.Enabled { return 0 } n := 0 for _, object := range s.Objects { if object.priority >= minPriority { n++ } } return n } func (s *CompiledScene) transmission(a, b Vec3, minPriority int) float64 { if s == nil || !s.Enabled { return 1 } gain := 1.0 for _, object := range s.Objects { if object.priority < minPriority { continue } if object.transmission < 1 && object.intersects(a, b) { gain *= object.transmission if gain == 0 { break } } } return gain }