Parcourir la source

implemented collision matrix

danaugrs il y a 7 ans
Parent
commit
7acfffd3da
2 fichiers modifiés avec 100 ajouts et 0 suppressions
  1. 61 0
      physics/collision/matrix.go
  2. 39 0
      physics/collision/matrix_test.go

+ 61 - 0
physics/collision/matrix.go

@@ -0,0 +1,61 @@
+// Copyright 2016 The G3N Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package collision implements collision related algorithms and data structures.
+package collision
+
+// Matrix is a triangular collision matrix indicating which pairs of bodies are colliding.
+type Matrix struct {
+	col [][]bool
+}
+
+// NewMatrix creates and returns a pointer to a new collision Matrix.
+func NewMatrix() *Matrix {
+
+	m := new(Matrix)
+	m.col = make([][]bool, 0)
+	return m
+}
+
+// Set sets whether i and j are colliding.
+func (m *Matrix) Set(i, j int, val bool) {
+
+	var s, l int
+	if i < j {
+		s = i
+		l = j
+	} else {
+		s = j
+		l = i
+	}
+	diff := s + 1 - len(m.col)
+	if diff > 0 {
+		for i := 0; i < diff; i++ {
+			m.col = append(m.col, make([]bool,0))
+		}
+	}
+	for idx := range m.col {
+		diff = l + 1 - len(m.col[idx]) - idx
+		if diff > 0 {
+			for i := 0; i < diff; i++ {
+				m.col[idx] = append(m.col[idx], false)
+			}
+		}
+	}
+	m.col[s][l-s] = val
+}
+
+// Get returns whether i and j are colliding.
+func (m *Matrix) Get(i, j int) bool {
+
+	var s, l int
+	if i < j {
+		s = i
+		l = j
+	} else {
+		s = j
+		l = i
+	}
+	return m.col[s][l-s]
+}

+ 39 - 0
physics/collision/matrix_test.go

@@ -0,0 +1,39 @@
+// Copyright 2016 The G3N Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package collision implements collision related algorithms and data structures.
+package collision
+
+import "testing"
+
+// Test simple matrix operations
+func Test(t *testing.T) {
+
+	m := NewMatrix()
+
+	// m.Get(1, 1) // panics with "runtime error: index out of range" as expected
+
+	m.Set(2,4, true)
+	m.Set(3,2, true)
+	if m.Get(1,1) != false {
+		t.Error("Get failed")
+	}
+	if m.Get(2,4) != true {
+		t.Error("Get failed")
+	}
+	if m.Get(3,2) != true {
+		t.Error("Get failed")
+	}
+
+	m.Set(2,4, false)
+	m.Set(3,2, false)
+	if m.Get(2,4) != false {
+		t.Error("Get failed")
+	}
+	if m.Get(3,2) != false {
+		t.Error("Get failed")
+	}
+
+	// m.Get(100, 100) // panics with "runtime error: index out of range" as expected
+}