solver.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package physics implements a basic physics engine.
  5. package solver
  6. import (
  7. "github.com/g3n/engine/physics/equation"
  8. "github.com/g3n/engine/math32"
  9. )
  10. // ISolver is the interface type for all constraint solvers.
  11. type ISolver interface {
  12. Solve(dt float32, nBodies int) *Solution // Solve should return the number of iterations performed
  13. AddEquation(eq equation.IEquation)
  14. RemoveEquation(eq equation.IEquation) bool
  15. ClearEquations()
  16. }
  17. // Solution represents a solver solution
  18. type Solution struct {
  19. VelocityDeltas []math32.Vector3
  20. AngularVelocityDeltas []math32.Vector3
  21. Iterations int
  22. }
  23. // Constraint equation solver base class.
  24. type Solver struct {
  25. Solution
  26. equations []equation.IEquation // All equations to be solved
  27. }
  28. // AddEquation adds an equation to the solver.
  29. func (s *Solver) AddEquation(eq equation.IEquation) {
  30. s.equations = append(s.equations, eq)
  31. }
  32. // RemoveEquation removes the specified equation from the solver.
  33. // Returns true if found, false otherwise.
  34. func (s *Solver) RemoveEquation(eq equation.IEquation) bool {
  35. for pos, current := range s.equations {
  36. if current == eq {
  37. copy(s.equations[pos:], s.equations[pos+1:])
  38. s.equations[len(s.equations)-1] = nil
  39. s.equations = s.equations[:len(s.equations)-1]
  40. return true
  41. }
  42. }
  43. return false
  44. }
  45. // ClearEquations removes all equations from the solver.
  46. func (s *Solver) ClearEquations() {
  47. s.equations = s.equations[0:0]
  48. }