Java-Gaming.org
Play Revenge of the Titans! The situation is critical. We need fancy commanders to defend Earth, the moon, Mars!
Featured games (78)
games approved by the League of Dukes
Games in Showcase (406)
games submitted by our members
Games in WIP (293)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Complex Angles, you don't need trig  (Read 361 times)
0 Members and 1 Guest are viewing this topic.
Offline delt0r

JGO Coder


Medals: 18


Computers can do that?


« Posted 2013-03-14 17:45:31 »

So I offered some of my code and was called on it. Turns out my core code is now all 3d with Quaternions etc. However 2d is even easier to avoid trig and even inverse trig. Done right you don't need all that many sqrts, but even then they are pretty fast.

The idea is simple. A complex number simply represents a unit vector in the direction the angle represents. Turns out complex multiplication is the same as adding angles and complex division is the same as subtracting angles. Since if we start with normalized values we end up with normalized values. Sure there is a little error. You can see that with the java2d demo that is included. You can even compare angles to see which is larger or smaller. Like atan2 angles are implied to be signed +-PI.

In the example the sweeping line is red when smaller than angle to the mouse and blue when larger. It turns green when its in the "acceptance cone", in this case +-8deg. Finally the funny cyan lines demonstrate interpolation.

Sorry i can't work out how to put this in a scroll box.

This code has not been unit tested. Use any way you want. I take no responsibility for this code, use at your own risk. And its in the public domain.

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  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
282  
283  
284  
285  
286  
287  
288  
289  
290  
291  
292  
293  
294  
295  
296  
297  
298  
299  
300  
301  
302  
303  
304  
305  
306  
307  
308  
309  
310  
311  
312  
313  
314  
315  
316  
317  
318  
319  
320  
321  
322  
323  
324  
325  
326  
327  
328  
329  
330  
import static java.lang.Math.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
 * other code has too much noise. This is suppose to be clean and make it easy for the jgo use. I use a demo java2d example. We use the convention that x is the
 * real axis and y is the imaginary axis.
 *
 * Note that i assume things are normalized a lot. Since this always represents an angle then this should always have unit length.
 *
 * Numerical errors for doubles are rather low. But they will eventrually accumulate. But its not like you need to normalize after every operation.
 *
 * Some degen cases are not checked. In particular you can create a NaN,NaN angle if you create an angle with 0,0.
 *
 * @author bob
 *
 */

public class ComplexAngle implements Comparable<ComplexAngle> {
   /**
    * Warning these are mutatable.
    */

   public static final ComplexAngle DELTA_ANGLE = createAngle(PI * 2 / 720);//1/2 def
  public static final ComplexAngle RIGHT_ANGLE=createAngle(PI/2);
                                                                                   
   private double real = 1;
   private double imag = 0;

   private ComplexAngle(double r, double i) {
      real = r;
      imag = i;
   }

   public static ComplexAngle angleTo(Point2D from, Point2D to) {
      return createAngle(to.getX() - from.getX(), to.getY() - from.getY());
   }

   public static ComplexAngle createAngle(double x, double y) {
      ComplexAngle ca = new ComplexAngle(x, y);
      ca.normalize();
      return ca;
   }
   
   public static ComplexAngle createAngle(double rad) {
      ComplexAngle ca = new ComplexAngle(Math.cos(rad), Math.sin(rad));
     
      return ca;
   }

   public ComplexAngle addAngleThis(ComplexAngle c) {
      return multiplyThis(c);
   }

   public ComplexAngle addAngle(ComplexAngle c) {
      return multiply(c);
   }

   /**
    * adds angles.
    *
    * @param c
    */

   public ComplexAngle multiplyThis(ComplexAngle c) {
      double nr = real * c.real - imag * c.imag;
      double ni = real * c.imag + imag * c.real;
      real = nr;
      imag = ni;
      // Normalized since both should be length 1. This adds the angles.
     return this;
   }

   public ComplexAngle multiply(ComplexAngle c) {
      double nr = real * c.real - imag * c.imag;
      double ni = real * c.imag + imag * c.real;
      return new ComplexAngle(nr, ni);
   }

   public ComplexAngle subtractAngleThis(ComplexAngle c) {
      return divideThis(c);
   }

   public ComplexAngle subtractAngle(ComplexAngle c) {
      return divide(c);
   }

   /**
    * subtracts angles.
    *
    * @param c
    */

   public ComplexAngle divideThis(ComplexAngle c) {
      double nr = real * c.real + imag * c.imag;
      double ni = c.real * imag - c.imag * real;
      // since we assume normalized we don't need to divide by
     // c.real*c.real+c.imag*c.imag, since that is 1.
     real = nr;
      imag = ni;
      return this;
   }

   public ComplexAngle divide(ComplexAngle c) {
      double nr = real * c.real + imag * c.imag;
      double ni = c.real * imag - c.imag * real;
      return new ComplexAngle(nr, ni);
   }

   /**
    * compare the angle. If o is bigger that means its a bigger angle. Note this is signed angles.
    *
    * So we are comparing y/x >=<  y'/x'. To avoid degenrancy with x->0 we rearange for y*x' >=< y'*x
    */

   @Override
   public int compareTo(ComplexAngle o) {
      double a = imag*o.real;
      double b = o.imag*real;
      if (a > b)
         return 1;
      if (a < b)
         return -1;
      return 0;
   }

   /**
    * note that we are using signed angles +-PI
    *
    * @param coneHalfAngle
    * @param from
    * @param to
    * @return
    */

   public boolean isInConeAngle(ComplexAngle coneHalfAngle, ComplexAngle angle) {
      // need to "rotate" our gun to match the ship
     ComplexAngle larger = this.addAngle(coneHalfAngle);
      ComplexAngle smaller = this.subtractAngle(coneHalfAngle);
      return larger.compareTo(angle) > 0 && smaller.compareTo(angle) < 0;// signed angles

   }

   /**
    * to show the round of errors.
    *
    * @return
    */

   public double length() {
      return sqrt(real * real + imag * imag);
   }

   /**
    * I hope this is normalized... Or there will be trouble.
    *
    * @return
    */

   public double cos() {
      return real;
   }

   /**
    * we are normlaized... Right!
    *
    * @return
    */

   public double sin() {
      return imag;
   }

   public double tan() {
      return imag / real;
   }

   /**
    *
    * @return a rotation matrix
    */

   public AffineTransform getRotationTransform() {
      double cos = real;
      double sin = -imag;//for the left handed coords for java2d. Note that a gl matrix would have this +
     return new AffineTransform(new double[] { cos, -sin, sin, cos});
   }

   /**
    * degenrate cases when angles are PI apart.
    * @param c
    * @param t
    * @return
    */

   public ComplexAngle interpolate(ComplexAngle c, double t) {
      double oneMinusT = 1 - t;
      double r = real * oneMinusT + c.real * t;
      double i = imag * oneMinusT + c.imag * t;
      ComplexAngle ca = new ComplexAngle(r, i);
      ca.normalize();// typically required here.
     return ca;
   }

   public void normalize() {
      double n = 1.0 / Math.sqrt(real * real + imag * imag);
      real *= n;
      imag *= n;
   }
   
   @Override
   public String toString() {
      return "ComplexAngle("+real+","+imag+"):"+length();
   }
   
   public static class Example extends JPanel implements MouseMotionListener{
     
      Point2D mouse=new Point2D.Double(0,0);
      ComplexAngle sweep=ComplexAngle.createAngle(1, 0);
      Point2D center=new Point2D.Double(100,100);
      ComplexAngle cone=ComplexAngle.createAngle(PI*2/45);//8 deg
     double t=.5;
      double dt=.02;
     
      public Example() {
         addMouseMotionListener(this);
         setBackground(Color.white);
         
      }
     
      @Override
      protected void paintComponent(Graphics g) {
         super.paintComponent(g);
         Graphics2D g2d=(Graphics2D)g;
     
         t+=dt;
         if(t>1){
            t=1;
            dt=-dt;
         }else if(t<0){
            t=0;
            dt=-dt;
         }
         
         ComplexAngle lookAt=ComplexAngle.angleTo(center, mouse);
   
         AffineTransform rotation=lookAt.getRotationTransform();
         AffineTransform af=AffineTransform.getTranslateInstance(center.getX(), center.getY());
         af.concatenate(rotation);
         
         AffineTransform oldTransform=g2d.getTransform();
         g2d.setTransform(af);
         g2d.setColor(Color.BLACK);
         paintDude(g2d);
         
         //now for sweeper.
        if(sweep.compareTo(lookAt)<0){
            sweep.addAngleThis(ComplexAngle.DELTA_ANGLE);
            g2d.setColor(Color.RED);
         }else{
            sweep.subtractAngleThis(ComplexAngle.DELTA_ANGLE);
            g2d.setColor(Color.BLUE);
         }
         if(lookAt.isInConeAngle(cone, sweep)){
            g2d.setColor(Color.GREEN);
         }
         
         System.out.println(sweep);
         
         g2d.setTransform(oldTransform);
         
         drawLine(g2d,center,sweep,200);
         
         g2d.setColor(Color.GRAY);
         drawLine(g2d,center,lookAt.addAngle(cone),100);
         drawLine(g2d,center,lookAt.subtractAngle(cone),100);
         
         g2d.setColor(Color.CYAN);
         drawLine(g2d,center,sweep.interpolate(sweep.addAngle(ComplexAngle.RIGHT_ANGLE),t),50);
         drawLine(g2d,center,sweep.interpolate(sweep.subtractAngle(ComplexAngle.RIGHT_ANGLE),t),50);
         
      }
     
      /**
       * paints a circle with a line from 0,0 to 10,0
       */

      private void paintDude(Graphics2D g2d){
         g2d.draw(new Ellipse2D.Double(-10,-5,20,10));
         g2d.drawLine(0, 0, 30, 0);
         
      }
     
      private void drawLine(Graphics2D g2d,Point2D from,ComplexAngle angle,double l){
         //here we use the example that a complex number can just be interpreted as a unit vector in the direction its pointing.
        //this is why, if we are normalized cos and sin are just the real and imag parts respectively.
        g2d.drawLine((int)from.getX(),(int)from.getY(),(int)(l*angle.cos()+from.getX()), (int)(l*angle.sin()+from.getY()));
         
      }
     
      @Override
      public void mouseDragged(MouseEvent e) {
         center=new Point2D.Double(e.getX(),e.getY());
         
      }
     
      @Override
      public void mouseMoved(MouseEvent e) {
         mouse=new Point2D.Double(e.getX(),e.getY());
         
      }
     
   }

   public static void main(String[] args) {
      JFrame frame=new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
      frame.setSize(500,500);
     
      Example example=new Example();
      frame.add(example);
      frame.setVisible(true);
      ((Graphics2D)example.getGraphics()).addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
      while(true){
         try {
            Thread.sleep(16);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
         example.repaint();
      }
   }
}

I have no special talents. I am only passionately curious.--Albert Einstein
Offline relminator

Senior Member


Medals: 3
Projects: 1



« Reply #1 - Posted 2013-05-22 04:25:20 »

This is quite cool! 
Pages: [1]
  ignore  |  Print  
 
 

Play Revenge of the Titans! The situation is critical. We need fancy commanders to defend Earth, the moon, Mars!
 
Browse for soundtracks for your game!

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

The invasion has landed! On Mars! And you're there to beat 'em!
cubemaster21 (84 views)
2013-05-17 21:29:12

alaslipknot (92 views)
2013-05-16 21:24:48

gouessej (123 views)
2013-05-16 00:53:38

gouessej (117 views)
2013-05-16 00:17:58

theagentd (127 views)
2013-05-15 15:01:13

theagentd (114 views)
2013-05-15 15:00:54

StreetDoggy (158 views)
2013-05-14 15:56:26

kutucuk (180 views)
2013-05-12 17:10:36

kutucuk (180 views)
2013-05-12 15:36:09

UnluckyDevil (187 views)
2013-05-12 05:09:57
Complex number cookbook
by Roquen
2013-04-24 12:47:31

2D Dynamic Lighting
by Oskuro
2013-04-17 16:46:12

2D Dynamic Lighting
by Oskuro
2013-04-17 16:45:57

2D Dynamic Lighting
by Oskuro
2013-04-17 16:23:20

Noise (bandpassed white)
by Roquen
2013-04-05 17:36:01

Noise (bandpassed white)
by Roquen
2013-04-03 16:17:38

Java Data structures
by Roquen
2013-03-29 13:21:12

Topic Request
by kutucuk
2013-03-22 21:42:01
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!
Page created in 0.871 seconds with 20 queries.