Search Results

Search found 736 results on 30 pages for 'degenerate dimension'.

Page 11/30 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • JOGL2 test compiles, but doesn't execute - help?

    - by Chuchinyi
    I have a problem with JOGL2. My JOGL2Template.java compiles fine, but executing it results in the following error: D:\java\java\jogl>javac JOGL2Template.java <== compile ok D:\java\java\jogl>java JOGL2Template <== execute error Exception in thread "main" java.lang.ExceptionInInitializerError at javax.media.opengl.GLProfile.<clinit>(GLProfile.java:1176) at JOGL2Template.<init>(JOGL2Template.java:24) at JOGL2Template.main(JOGL2Template.java:57) Caused by: java.lang.SecurityException: no certificate for gluegen-rt.dll in D:\ java\lib\gluegen-rt-natives-windows-i586.jar at com.jogamp.common.util.JarUtil.validateCertificate(JarUtil.java:350) at com.jogamp.common.util.JarUtil.validateCertificates(JarUtil.java:324) at com.jogamp.common.util.cache.TempJarCache.validateCertificates(TempJa rCache.java:328) at com.jogamp.common.util.cache.TempJarCache.bootstrapNativeLib(TempJarC ache.java:283) at com.jogamp.common.os.Platform$3.run(Platform.java:308) at java.security.AccessController.doPrivileged(Native Method) at com.jogamp.common.os.Platform.loadGlueGenRTImpl(Platform.java:298) at com.jogamp.common.os.Platform.<clinit>(Platform.java:207) ... 3 more Here is the JOGL2Template.java source code: import java.awt.Dimension; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; import com.jogamp.opengl.util.FPSAnimator; import javax.swing.JFrame; /* * JOGL 2.0 Program Template For AWT applications */ public class JOGL2Template extends JFrame implements GLEventListener { private static final int CANVAS_WIDTH = 640; // Width of the drawable private static final int CANVAS_HEIGHT = 480; // Height of the drawable private static final int FPS = 60; // Animator's target frames per second // Constructor to create profile, caps, drawable, animator, and initialize Frame public JOGL2Template() { // Get the default OpenGL profile that best reflect your running platform. GLProfile glp = GLProfile.getDefault(); // Specifies a set of OpenGL capabilities, based on your profile. GLCapabilities caps = new GLCapabilities(glp); // Allocate a GLDrawable, based on your OpenGL capabilities. GLCanvas canvas = new GLCanvas(caps); canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT)); canvas.addGLEventListener(this); // Create a animator that drives canvas' display() at 60 fps. final FPSAnimator animator = new FPSAnimator(canvas, FPS); addWindowListener(new WindowAdapter() { // For the close button @Override public void windowClosing(WindowEvent e) { // Use a dedicate thread to run the stop() to ensure that the // animator stops before program exits. new Thread() { @Override public void run() { animator.stop(); System.exit(0); } }.start(); } }); add(canvas); pack(); setTitle("OpenGL 2 Test"); setVisible(true); animator.start(); // Start the animator } public static void main(String[] args) { new JOGL2Template(); } @Override public void init(GLAutoDrawable drawable) { // Your OpenGL codes to perform one-time initialization tasks // such as setting up of lights and display lists. } @Override public void display(GLAutoDrawable drawable) { // Your OpenGL graphic rendering codes for each refresh. } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) { // Your OpenGL codes to set up the view port, projection mode and view volume. } @Override public void dispose(GLAutoDrawable drawable) { // Hardly used. } } Any ideas what might be the cause of these errors?

    Read the article

  • Rotate a Swing JLabel

    - by Johannes Rössel
    I am currently trying to implement a Swing component, inheriting from JLabel which should simply represent a label that can be oriented vertically. Beginning with this: public class RotatedLabel extends JLabel { public enum Direction { HORIZONTAL, VERTICAL_UP, VERTICAL_DOWN } private Direction direction; I thought it's be a nice idea to just alter the results from getPreferredSize(): @Override public Dimension getPreferredSize() { // swap size for vertical alignments switch (getDirection()) { case VERTICAL_UP: case VERTICAL_DOWN: return new Dimension(super.getPreferredSize().height, super .getPreferredSize().width); default: return super.getPreferredSize(); } } and then simply transform the Graphics object before I offload painting to the original JLabel: @Override protected void paintComponent(Graphics g) { Graphics2D gr = (Graphics2D) g.create(); switch (getDirection()) { case VERTICAL_UP: gr.translate0, getPreferredSize().getHeight()); gr.transform(AffineTransform.getQuadrantRotateInstance(-1)); break; case VERTICAL_DOWN: // TODO break; default: } super.paintComponent(gr); } } It seems to work—somehow—in that the text is now displayed vertically. However, placement and size are off: Actually, the width of the background (orange in this case) is identical with the height of the surrounding JFrame which is ... not quite what I had in mind. Any ideas how to solve that in a proper way? Is delegating rendering to superclasses even encouraged?

    Read the article

  • Variable number of two-dimensional arrays into one big array

    - by qlb
    I have a variable number of two-dimensional arrays. The first dimension is variable, the second dimension is constant. i.e.: Object[][] array0 = { {"tim", "sanchez", 34, 175.5, "bla", "blub", "[email protected]"}, {"alice", "smith", 42, 160.0, "la", "bub", "[email protected]"}, ... }; Object[][] array1 = { {"john", "sdfs", 34, 15.5, "a", "bl", "[email protected]"}, {"joe", "smith", 42, 16.0, "a", "bub", "[email protected]"}, ... }; ... Object[][] arrayi = ... I'm generating these arrays with a for-loop: for (int i = 0; i < filter.length; i++) { MyClass c = new MyClass(filter[i]); //data = c.getData(); } Where "filter" is another array which is filled with information that tells "MyClass" how to fill the arrays. "getData()" gives back one of the i number of arrays. Now I just need to have everything in one big two dimensional array. i.e.: Object[][] arrayComplete = { {"tim", "sanchez", 34, 175.5, "bla", "blub", "[email protected]"}, {"alice", "smith", 42, 160.0, "la", "bub", "[email protected]"}, ... {"john", "sdfs", 34, 15.5, "a", "bl", "[email protected]"}, {"joe", "smith", 42, 16.0, "a", "bub", "[email protected]"}, ... ... }; In the end, I need a 2D array to feed my Swing TableModel. Any idea on how to accomplish this? It's blowing my mind right now.

    Read the article

  • How to get the coordinate of Gridlayout

    - by Jessy
    Hi, I set my JPanel to GridLayout (6,6), with dimension (600,600) Each cell of the grid will display one pictures with different widths and heights. The picture first add to a JLabel, and the JLabel then added to the cells. How can retrieved the coordinate of the pictures in the cells and not the coordinate of cells? So far the out give these coordinate which equal height and width even on screen the pictures showed in different sizes. e.g. java.awt.Rectangle[x=100,y=100,width=100,height=100] java.awt.Rectangle[x=200,y=100,width=100,height=100] java.awt.Rectangle[x=300,y=100,width=100,height=100] The reason why I used GridLayout instead of gridBagLayout is that, I want each pictures to have boundary. If I use GridBagLayout, the grid will expand according to the picture size. I want grid size to be in fix size. JPanel pDraw = new JPanel(new GridLayout(6,6)); pDraw.setPreferredSize(new Dimension(600,600)); for (int i =0; i<(6*6); i++) { //get random number for height and width of the image int x = rand.nextInt(40)+(50); int y = rand.nextInt(40)+(50); ImageIcon icon = createImageIcon("bird.jpg"); //rescale the image according to the size selected Image img = icon.getImage().getScaledInstance(x,y,img.SCALE_SMOOTH); icon.setImage(img ); JLabel label = new JLabel(icon); pDraw.add(label); } for(Component component:components) { //retrieve the coordinate System.out.println(component.getBounds()); }

    Read the article

  • SSAS Cube reprocessing fails - then succeeds if I try again

    - by EdgarVerona
    So I'm basically brand new to the concept of BI, and I've inherited an existing ETL process that is a two step process: 1) Loads the data into a database that is only used by the cube processing 2) Starts off the SSAS cube processing against said database It seems pretty well isolated, but occasionally (once a week, sometimes twice) it will fail with the following exception: "Errors in the OLAP storage engine: The attribute key cannot be found" Now the interesting thing is that: 1) The dimension having the issue is not usually the same one (i.e. there's no single dimension that consistently has this failure) 2) The source table, when I inspect it, does actually contain the attribute key that it says could not be found And, most interestingly... 3) If I then immediately reprocess the dimensions and cubes manually through SSMS, they reprocess successfully and without incident. In both the aforementioned job and when I reprocess them through SSMS, I am using "ProcessFull", so it should be reprocessing them completely. Has anyone run into such an issue? I'm scratching my head about it... because if it was a genuine data integrity issue, reprocessing the cube again wouldn't fix it. What on earth could be happening? I've been tasked with finding out why this happens, but I can neither reproduce it consistently nor can I point to a data integrity problem as the root cause. Thanks for any input you can provide!

    Read the article

  • initialising a 2-dim Array in Scala

    - by Stefan W.
    (Scala 2.7.7:) I don't get used to 2d-Arrays. Arrays are mutable, but how do I specify a 2d-Array which is - let's say of size 3x4. The dimension (2D) is fixed, but the size per dimension shall be initializable. I tried this: class Field (val rows: Int, val cols: Int, sc: java.util.Scanner) { var field = new Array [Char](rows)(cols) for (r <- (1 to rows)) { val line = sc.nextLine () val spl = line.split (" ") field (r) = spl.map (_.charAt (0)) } def put (val rows: Int, val cols: Int, c: Char) = todo () } I get this error: :11: error: value update is not a member of Char field (r) = spl.map (_.charAt (0)) If it would be Java, it would be much more code, but I would know how to do it, so I show what I mean: public class Field { private char[][] field; public Field (int rows, int cols, java.util.Scanner sc) { field = new char [rows][cols]; for (int r = 0; r < rows; ++r) { String line = sc.nextLine (); String[] spl = line.split (" "); for (int c = 0; c < cols; ++c) field [r][c] = spl[c].charAt (0); } } public static void main (String args[]) { new Field (3, 4, new java.util.Scanner ("fraese.fld")); } } and fraese.fld would look, for example, like that: M M M M . M I get some steps wide with val field = new Array Array [Char] but how would I then implement 'put'? Or is there a better way to implement the 2D-Array. Yes, I could use a one-dim-Array, and work with put (y, x, c) = field (y * width + x) = c but I would prefer a notation which looks more 2d-ish.

    Read the article

  • drawing to a JPanel without inheritance

    - by g.rocket
    Right now I'm working on a program that throws up a bunch of separate (generated at runtime) images, each in their own window. To do this i've tried this approach: public void display(){ JFrame window = new JFrame("NetPart"); JPanel canvas = new JPanel(); window.getContentPane().add(canvas); Graphics g = canvas.getGraphics(); Dimension d = getSize(); System.out.println(d); draw(g,new Point(d.minX*50,d.maxY*50), 50); window.setSize(d.size(50)); window.setResizable(false); window.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); window.setVisible(true); } public void draw(Graphics g, Point startLoc, int scale){ // generate and draw the image } public Dimension getSize(){ //returns my own dimensions class } However, this throws a NullPointerException in draw, claiming that the graphics is null. is there any way to externally draw to a JPanel from outside it (not inherit from JPanel and override PaintComponent)? Any help would be appreciated.

    Read the article

  • Improving my first Clojure program

    - by StackedCrooked
    After a few weekends exploring Clojure I came up with this program. It allows you to move a little rectangle in a window. Here's the code: (import java.awt.Color) (import java.awt.Dimension) (import java.awt.event.KeyListener) (import javax.swing.JFrame) (import javax.swing.JPanel) (def x (ref 0)) (def y (ref 0)) (def panel (proxy [JPanel KeyListener] [] (getPreferredSize [] (Dimension. 100 100)) (keyPressed [e] (let [keyCode (.getKeyCode e)] (if (== 37 keyCode) (dosync (alter x dec)) (if (== 38 keyCode) (dosync (alter y dec)) (if (== 39 keyCode) (dosync (alter x inc)) (if (== 40 keyCode) (dosync (alter y inc)) (println keyCode))))))) (keyReleased [e]) (keyTyped [e]))) (doto panel (.setFocusable true) (.addKeyListener panel)) (def frame (JFrame. "Test")) (doto frame (.add panel) (.pack) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.setVisible true)) (defn drawRectangle [p] (doto (.getGraphics p) (.setColor (java.awt.Color/WHITE)) (.fillRect 0 0 100 100) (.setColor (java.awt.Color/BLUE)) (.fillRect (* 10 (deref x)) (* 10 (deref y)) 10 10))) (loop [] (drawRectangle panel) (Thread/sleep 10) (recur)) Despite being an experienced C++ programmer I found it very challenging to write even a simple application in a language that uses a radically different style than what I'm used to. On top of that, this code probably sucks. I suspect the globalness of the various values is a bad thing. It's also not clear to me if it's appropriate to use references here for the x and y values. Any hints for improving this code are welcome.

    Read the article

  • Problem painting JLabel class to another JPanel class

    - by jjpotter
    I have created a class that extends JLabel to use as my object moving around a JPanel for a game. import javax.swing.*; public class Head extends JLabel { int xpos; int ypos; int xvel; int yvel; ImageIcon chickie = new ImageIcon("C:\\Users\\jjpotter.MSDOM1\\Pictures\\clavalle.jpg"); JLabel myLabel = new JLabel(chickie); public Head(int xpos, int ypos, int xvel, int yvel){ this.xpos = xpos; this.ypos = ypos; this.xvel = xvel; this.yvel = yvel; } public void draw(){ myLabel.setLocation(xpos, ypos); } public double getXpos() { return xpos; } public double getYpos() { return ypos; } public int getXvel() { return xvel; } public int getYvel() { return yvel; } public void setPos(int x, int y){ xpos = x; ypos = y; } } I am then trying to add it onto my JPanel. From here I will randomly have it increment its x and y coordinates to float it around the screen. I can not get it to paint itself onto the JPanel. I know there is a key concept I am missing here that involves painting components on different panels. Here is what I have in my GamePanel class import java.awt.Dimension; import java.util.Random; import javax.swing.*; public class GamePanel extends JPanel { Random myRand = new Random(); Head head = new Head(20,20,0,0); public GamePanel(){ this.setSize(new Dimension(640, 480)); this.add(head); } } Any suggestions on how to get this to add to the JPanel? Also, is this a good way to go about having the picture float around the screen randomly for a game?

    Read the article

  • What algorithm can I use to determine points within a semi-circle?

    - by khayman218
    I have a list of two-dimensional points and I want to obtain which of them fall within a semi-circle. Originally, the target shape was a rectangle aligned with the x and y axis. So the current algorithm sorts the pairs by their X coord and binary searches to the first one that could fall within the rectangle. Then it iterates over each point sequentially. It stops when it hits one that is beyond both the X and Y upper-bound of the target rectangle. This does not work for a semi-circle as you cannot determine an effective upper/lower x and y bounds for it. The semi-circle can have any orientation. Worst case, I will find the least value of a dimension (say x) in the semi-circle, binary search to the first point which is beyond it and then sequentially test the points until I get beyond the upper bound of that dimension. Basically testing an entire band's worth of points on the grid. The problem being this will end up checking many points which are not within the bounds.

    Read the article

  • OpenMP in Fortran

    - by user345293
    I very rarely use fortran, however I have been tasked with taking legacy code rewriting it to run in parallel. I'm using gfortran for my compiler choice. I found some excellent resources at https://computing.llnl.gov/tutorials/openMP/ as well as a few others. My problem is this, before I add any OpenMP directives, if I simply compile the legacy program: gfortran Example1.F90 -o Example1 everything works, but turning on the openmp compiler option even without adding directives: gfortran -openmp Example1.F90 -o Example1 ends up with a Segmentation fault when I run the legacy program. Using smaller test programs that I wrote, I've successfully compiled other programs with -openmp that run on multiple threads, but I'm rather at a loss why enabling the option alone and no directives is resulting in a seg fault. I apologize if my question is rather simple. I could post code but it is rather long. It faults as I assign initial values: REAL, DIMENSION(da,da) :: uconsold REAL, DIMENSION(da,da,dr,dk) :: uconsolde ... uconsold=0.0 uconsolde=0.0 The first assignment to "uconsold" works fine, the second seems to be the source of the fault as when I comment the line out the next several lines execute merrily until "uconsolde" is used again. Thank you for any help in this matter.

    Read the article

  • How to convert a rectangle to TRBL CSS rect value?

    - by VLostBoy
    I'm not quite sure how to put this, but here goes... The css clip attribute is defined like so: rect(top, right, bottom, left). However, I'm exploring the use of a custom Rectangle 'class' to encapsulate some operations. The rectangle class has the attributes height, width and x, y. The x and y values are encapsulated in a Point object, and the height and width are encapsulated in a Dimension object, the rectangle being a composite of a point (its top-left location) and a dimension (width and height). So far so good. I though it would be pretty simple on the basis of having the rectangles x, y, width and height values to define the css rect attribute in terms of top, right, bottom, left, but I've become hopelessly confused- I've been googling for a while, and I can't seem to find any documentation as to what the TRBL values actually are or what they represent. For example, should I be thinking in terms of co-ordinates, in which case, surely I can describe the rectangle as a css rect using the rectangles x position for Top, x position + width for Right, the rectangles height + y for Bottom and its y position for Left... but thats a load of BS, surely? Also, surely rect is actually an inset, or have I just inverted my understanding of clip? I'd appreciate some advice. What I want to be able to do is (i) Define a rectangle using x, y, width and height (ii)Express the rectangle in TRBL form so that I can manipulate a divs clipping behaviour (iii)Change x, y, width or height and recalculate in terms of TRBL and goto (ii) I appreciate there are some other factors here, and some intermediary transforms to be done, but I've confused myself pretty badly- Can anyone give me some pointers?

    Read the article

  • Question about array subscripting in C#

    - by Michael J
    Back in the old days of C, one could use array subscripting to address storage in very useful ways. For example, one could declare an array as such. This array represents an EEPROM image with 8 bit words. BYTE eepromImage[1024] = { ... }; And later refer to that array as if it were really multi-dimensional storage BYTE mpuImage[2][512] = eepromImage; I'm sure I have the syntax wrong, but I hope you get the idea. Anyway, this projected a two dimension image of what is really single dimensional storage. The two dimensional projection represents the EEPROM image when loaded into the memory of an MPU with 16 bit words. In C one could reference the storage multi-dimensionaly and change values and the changed values would show up in the real (single dimension) storage almost as if by magic. Is it possible to do this same thing using C#? Our current solution uses multiple arrays and event handlers to keep things synchronized. This kind of works but it is additional complexity that we would like to avoid if there is a better way.

    Read the article

  • XBMC won't live boot

    - by Chris
    I'm trying to run XBMC on a Dell Dimension 4300S (stock parts). I cannot get it to finish a live boot. It gets stuck on "restarting openbsd secure shell server sshd" [see picture]. Any ideas?

    Read the article

  • Error Trying To Use Microsoft LifeCam VX-3000

    - by Brian
    Hello, I bought a Microsoft LifeCam VX-3000 web camera for may parent's Dell Dimension 3000 computer running XP SP 3, and I cannot get it to run. THe installation ran successfully, but when I try to run it, I get the error: Faulting application lifecam.exe, version 3.21.263.0, faulting module kernel32.dll, version 5.1.2600.5781, fault address 0x00012afb. The microsoft help link really didn't help... how do I even resolve this type of error? Thanks.

    Read the article

  • Windows 7 Goes to Sleep in conflict with Power Option Setting

    - by Decker
    My Del Dimension E521 running Windows 7 puts itself in sleep mode each night -- despite the fact that I have chosen a power option that specifies NEVER Each morning I find the monitor blank and I have to hit the power button on the PC at which point Windows "resumes". The system event log shows this: Source: Microsoft-Windows-Kernel-Power Date: 3/27/2010 3:21:10 AM Description: The system is entering sleep. Sleep Reason: System Idle My specific power options are: Turn off Display : 20 Minutes Put the computer to sleep : Never Is there some other setting coming into play here?

    Read the article

  • how to run/compile java code from JTextArea at Runtime? ----urgent!!! college project

    - by Lokesh Kumar
    I have a JInternalFrame painted with a BufferedImage and contained in the JDesktopPane of a JFrame.I also have a JTextArea where i want to write some java code (function) that takes the current JInternalFrame's painted BufferedImage as an input and after doing some manipulation on this input it returns another manipulated BufferedImage that paints the JInternalFrame with new manipulated Image again!!. Manipulation java code of JTextArea:- public BufferedImage customOperation(BufferedImage CurrentInputImg) { Color colOld; Color colNew; BufferedImage manipulated=new BufferedImage(CurrentInputImg.getWidth(),CurrentInputImg.getHeight(),BufferedImage.TYPE_INT_ARGB); //make all Red pixels of current image black for(int i=0;i< CurrentInputImg.getWidth();i++) { for(int j=0;j< CurrentInputImg.getHeight(),j++) { colOld=new Color(CurrentInputImg.getRGB(i,j)); colNew=new Color(0,colOld.getGreen(),colOld.getBlue(),colOld.getAlpha()); manipulated.setRGB(i,j,colNew.getRGB()); } } return manipulated; } so,how can i run/compile this JTextArea java code at runtime and get a new manipulated image for painting on JInternalFrame???????   Here is my Main class: (This class is not actual one but i have created it for u for basic interfacing containing JTextArea,JInternalFrame,Apply Button) import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.JInternalFrame; import javax.swing.JDesktopPane; import java.awt.image.*; import javax.imageio.*; import java.io.*; import java.io.File; import java.util.*; class MyCustomOperationSystem extends JFrame **{** public JInternalFrame ImageFrame; public BufferedImage CurrenFrameImage; public MyCustomOperationSystem() **{** setTitle("My Custom Image Operations"); setSize((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(),(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()); JDesktopPane desktop=new JDesktopPane(); desktop.setPreferredSize(new Dimension((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(),(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight())); try{ CurrenFrameImage=ImageIO.read(new File("c:/Lokesh.png")); }catch(Exception exp) { System.out.println("Error in Loading Image"); } ImageFrame=new JInternalFrame("Image Frame",true,true,false,true); ImageFrame.setMinimumSize(new Dimension(CurrenFrameImage.getWidth()+10,CurrenFrameImage.getHeight()+10)); ImageFrame.getContentPane().add(CreateImagePanel()); ImageFrame.setLayer(1); ImageFrame.setLocation(100,100); ImageFrame.setVisible(true); desktop.setOpaque(true); desktop.setBackground(Color.darkGray); desktop.add(ImageFrame); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().add("Center",desktop); this.getContentPane().add("South",ControlPanel()); pack(); setVisible(true); **}** public JPanel CreateImagePanel(){ JPanel tempPanel=new JPanel(){ public void paintComponent(Graphics g) { g.drawImage(CurrenFrameImage,0,0,this); } }; tempPanel.setPreferredSize(new Dimension(CurrenFrameImage.getWidth(),CurrenFrameImage.getHeight())); return tempPanel; } public JPanel ControlPanel(){ JPanel controlPan=new JPanel(new FlowLayout(FlowLayout.LEFT)); JButton customOP=new JButton("Custom Operation"); customOP.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evnt){ JFrame CodeFrame=new JFrame("Write your Code Here"); JTextArea codeArea=new JTextArea("Your Java Code Here",100,70); JScrollPane codeScrollPan=new JScrollPane(codeArea,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); CodeFrame.add(codeScrollPan); CodeFrame.setVisible(true); } }); JButton Apply=new JButton("Apply Code"); Apply.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ // What should I do!!! Here!!!!!!!!!!!!!!! } }); controlPan.add(customOP); controlPan.add(Apply); return controlPan; } public static void main(String s[]) { new MyCustomOperationSystem(); } } Note: in above class JInternalFrame (ImageFrame) is not visible even i have declared it visible. so, ImageFrame is not visible while compiling and running above class. U have to identify this problem before running it.

    Read the article

  • Setting up functional Tests in Flex

    - by Dan Monego
    I'm setting up a functional test suite for an application that loads an external configuration file. Right now, I'm using flexunit's addAsync function to load it and then again to test if the contents point to services that exist and can be accessed. The trouble with this is that having this kind of two (or more) stage method means that I'm running all of my tests in the context of one test with dozens of asserts, which seems like a kind of degenerate way to use the framework, and makes bugs harder to find. Is there a way to have something like an asynchronous setup? Is there another testing framework that handles this better?

    Read the article

  • JScrollPane content to image

    - by Sebastian Ikaros Rizzo
    I'm trying to save the main viewport and headers of a JScrollPane (larger than screen) to PNG image files. I created 3 classes extending JPanel (MainTablePanel, MapsHeaderPanel and ItemsHeaderPanel) and set them to the viewports. Each of them has this method: public BufferedImage createImage() { BufferedImage bi = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); paint(g); g.dispose(); return bi; } Each class has also a paint method, which paints the background and then call the super.paint() to paint some label. For example: public void paint(Graphics g){ g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(new Color(255, 255, 0, 50)); // for loop that paints some vertical yellow lines for(int i=0; i<getWidth(); i+=K.mW){ g.fillRect(i-1, 0, 2, getHeight()); if(i%(K.mW*5)==0){ g.fillRect(i-2, 0, 4, getHeight()); } } // called to pain some rotated JLabels super.paint(g); } From an external JFrame I then tried to save them to PNG file, using this code: BufferedImage tableImg = mainTableP.createImage(); BufferedImage topImg = mapsHeaderP.createImage(); BufferedImage leftImg = itemsHeaderP.createImage(); ImageIO.write(tableImg, "png", new File(s.homeDir+"/table.png")); ImageIO.write(topImg, "png", new File(s.homeDir+"/top.png")); ImageIO.write(leftImg, "png", new File(s.homeDir+"/left.png")); This is a screenshot of the application running: screenshot And this is the header exported: top If I comment the "super.paint(g)" instruction, I obtain a correct image (thus without all JLables, clearly). It seems like the second paint (super.paint(g)) is painted shifted into the BufferedImage and taking elements outside its JPanel. Somebody could explain me this behaviour? Thank you. ========== EDIT for SSCCE ==================================== This should compile. You can execute it as it is, and in c:\ you'll find two images (top.png and left.png) that should be the same as the two headers. Unfortunately, they are not. Background is not painted. Moreover (especially if you look at left.png) you can see that the labels are painted twice and shifted (note, for example, "Left test 21"). import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import javax.swing.*; public class Main { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setLayout(null); frame.setSize(800, 600); JScrollPane scrollP = new JScrollPane(); scrollP.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollP.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); MyPanel top = new MyPanel(); for(int i=0; i<30; i++){ JLabel label = new JLabel("Test "+i); label.setOpaque(false); label.setBounds(50*i, 40, 50, 20); label.setForeground(Color.GREEN); top.add(label); } top.setLayout(null); top.setOpaque(false); top.setPreferredSize(new Dimension(50*30, 200)); top.validate(); MyPanel left = new MyPanel(); for(int i=0; i<30; i++){ JLabel label = new JLabel("Left test "+i); label.setBounds(0, 50*i, 100, 20); label.setForeground(Color.RED); left.add(label); } left.setLayout(null); left.setOpaque(false); left.setPreferredSize(new Dimension(200, 50*30)); MyPanel center = new MyPanel(); center.setLayout(null); center.setOpaque(false); center.setPreferredSize(new Dimension(50*30, 50*30)); scrollP.setViewportView(center); scrollP.setColumnHeaderView(top); scrollP.setRowHeaderView(left); scrollP.setBounds(0, 50, 750, 500); frame.add(scrollP); frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); try{ BufferedImage topImg = top.createImage(); ImageIO.write(topImg, "png", new File("C:/top.png")); BufferedImage leftImg = left.createImage(); ImageIO.write(leftImg, "png", new File("C:/left.png")); }catch(Exception e){ e.printStackTrace(); } } } class MyPanel extends JPanel{ public void paint(Graphics g){ g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(new Color(255, 255, 0, 50)); for(int i=0; i<getWidth(); i+=50){ g.fillRect(i-1, 0, 2, getHeight()); } super.paint(g); // COMMENT this line to obtain background images } public BufferedImage createImage() { BufferedImage bi = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); paint(g); g.dispose(); return bi; } }

    Read the article

  • paintComponent method is not displaying anything on the panel

    - by Captain Gh0st
    I have been trying to debug this for hours. The program is supposed to be a grapher that graphs coordinates, but i cannot get anything to display not even a random line, but if i put a print statement there it works. It is a problem with the paintComponent Method. When I out print statement before g.drawLine then it prints, but it doesn't draw any lines even if i put a random line with coordinates (1,3), (2,4). import java.awt.*; import java.util.*; import javax.swing.*; public abstract class XYGrapher { abstract public Coordinate xyStart(); abstract public double xRange(); abstract public double yRange(); abstract public Coordinate getPoint(int pointNum); public class Paint extends JPanel { public void paintGraph(Graphics g, int xPixel1, int yPixel1, int xPixel2, int yPixel2) { super.paintComponent(g); g.setColor(Color.black); g.drawLine(xPixel1, yPixel1, xPixel2, yPixel2); } public void paintXAxis(Graphics g, int xPixel, int pixelsWide, int pixelsHigh) { super.paintComponent(g); g.setColor(Color.green); g.drawLine(xPixel, 0, xPixel, pixelsHigh); } public void paintYAxis(Graphics g, int yPixel, int pixelsWide, int pixelsHigh) { super.paintComponent(g); g.setColor(Color.green); g.drawLine(0, yPixel, pixelsWide, yPixel); } } public void drawGraph(int xPixelStart, int yPixelStart, int pixelsWide, int pixelsHigh) { JFrame frame = new JFrame(); Paint panel = new Paint(); panel.setPreferredSize(new Dimension(pixelsWide, pixelsHigh)); panel.setMinimumSize(new Dimension(pixelsWide, pixelsHigh)); panel.setMaximumSize(new Dimension(pixelsWide, pixelsHigh)); frame.setLocation(frame.getToolkit().getScreenSize().width / 2 - pixelsWide / 2, frame.getToolkit().getScreenSize().height / 2 - pixelsHigh / 2); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.add(panel); frame.pack(); frame.setVisible(true); double xRange = xRange(); double yRange = yRange(); Coordinate xyStart = xyStart(); int xPixel = xPixelStart - (int) (xyStart.getX() * (pixelsWide / xRange)); int yPixel = yPixelStart + (int) ((xyStart.getY() + yRange) * (pixelsHigh / yRange)); System.out.println(xPixel + " " + yPixel); if(yPixel > 0 && (yPixel < pixelsHigh)) { System.out.println("y"); panel.paintYAxis(panel.getGraphics(), yPixel, pixelsWide, pixelsHigh); } if(xPixel > 0 && (xPixel < pixelsHigh)) { System.out.println("x"); panel.paintXAxis(panel.getGraphics(), xPixel, pixelsWide, pixelsHigh); } for(int i = 0; i>=0; i++) { Coordinate point1 = getPoint(i); Coordinate point2 = getPoint(i+1); if(point2 == null) { break; } else { if(point1.drawFrom() && point2.drawTo()) { int xPixel1 = (int) (xPixelStart + (point1.getX() - xyStart.getX()) * (pixelsWide / xRange)); int yPixel1 = (int) (yPixelStart + (xyStart.getY() + yRange-point1.getY()) * (pixelsHigh / yRange)); int xPixel2 = (int) (xPixelStart + (point2.getX() - xyStart.getX()) * (pixelsWide / xRange)); int yPixel2 = (int) (yPixelStart + (xyStart.getY() + yRange - point2.getY()) * (pixelsHigh / yRange)); panel.paintGraph(panel.getGraphics(), xPixel1, yPixel1, xPixel2, yPixel2); } } } frame.pack(); } } This is how i am testing it is supposed to be a square, but nothing shows up. public class GrapherTester extends XYGrapher { public Coordinate xyStart() { return new Coordinate(-2,2); } public double xRange() { return 4; } public double yRange() { return 4; } public Coordinate getPoint(int pointNum) { switch(pointNum) { case 0: return new Coordinate(-1,-1); case 1: return new Coordinate(1,-1); case 2: return new Coordinate(1,1); case 3: return new Coordinate(-1,1); case 4: return new Coordinate(-1,-1); } return null; } public static void main(String[] args) { new GrapherTester().drawGraph(100, 100, 500, 500); } } Coordinate class so if any of you want to run and try it out. That is all you would need. public class Coordinate { float x; float y; boolean drawTo; boolean drawFrom; Coordinate(double x, double y) { this.x = (float) x; this.y = (float) y; drawFrom = true; drawTo = true; } Coordinate(double x, double y, boolean drawFrom, boolean drawTo) { this.x = (float) x; this.y = (float) y; this.drawFrom = drawFrom; this.drawTo = drawTo; } public double getX() { return x; } public double getY() { return y; } public boolean drawTo() { return drawTo; } public boolean drawFrom() { return drawFrom; } }

    Read the article

  • Calling class in Java after editing file used in as source for table

    - by user2892290
    I'm currently working on a project, I'll try to subrscibe first. I save data into text file, that I use as a source for browser of that data. The browser is based on table that contains the data. I have to rewrite the source file everytime I delete or edit data. That's where the problem comes in. After deleting or editing data I call a method to create the table again, but the table never creates. Is it possibly made by editing the file and calling the method right after that? If I restart my app the table is successfully created with right data. Take in note that I don't get any error message. This is the method I use for loading data from source file: try (BufferedReader input1 = new BufferedReader(new FileReader("./src/data.src"))) { int lines = 0; while (input1.read() != -1) { if (!(input1.readLine()).equals("")) { lines++; } } input1.close(); if (lines == 0) { JOptionPane.showMessageDialog(null, "No data to load, create a note first!"); new Writer().build(frame); } else { try (BufferedReader input = new BufferedReader(new FileReader("./src/data.src"))) { Game[] g = new Game[lines]; String currentLine; String[] help; int counter = 0; while (lines > 0) { currentLine = input.readLine(); help = currentLine.split("#"); g[counter] = new Game(help[0],help[1], help[2], help[3], help[4], help[5], help[6], help[7], help[8], help[9]); counter++; lines--; } input.close(); final JButton bButton = new backButton().create(frame, mPanel); build(g, frame, bButton); mPanel.add(panel); mPanel.add(panel2); mPanel.add(searchPanel); mPanel.add(bButton); bButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); panel.removeAll(); frame.setCursor(Cursor.getDefaultCursor()); } }); mPanel.setPreferredSize(new Dimension(1000, 750)); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); frame.setLayout(new FlowLayout()); frame.add(mPanel); frame.pack(); JMenuBar menuBar = new Menu().create(frame, mPanel); frame.setJMenuBar(menuBar); frame.setVisible(true); Rectangle rec = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); int width = (int) rec.getWidth(); int height = (int) rec.getHeight(); frame.setBounds(1, 3, width, height); frame.addComponentListener(new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { frame.setLocation(1, 3); } }); And this is the method I use for creating the table: String[][] tableData = new String[g.length][9]; for (int i = 0; i < tableData.length; i++) { tableData[i][0] = g[i].getChampion(); tableData[i][1] = g[i].getRole(); tableData[i][2] = g[i].getEnemy(); tableData[i][3] = g[i].getDifficulty(); tableData[i][4] = g[i].getResult(); tableData[i][5] = g[i].getScore(); tableData[i][6] = g[i].getGameType(); tableData[i][7] = g[i].getPoints(); tableData[i][8] = g[i].getLeague(); } final JLabel searchLabel = new JLabel("Search for champion played."); final JButton searchButton = new JButton("Search"); final JTextField searchText = new JTextField(20); frame.setTitle("LoL Notepad - reading your notes"); JTable table = new JTable(tableData, columnNames); final JScrollPane scrollPane = new JScrollPane(table); scrollPane.setPreferredSize(new Dimension(980, 500)); panel2.setPreferredSize(new Dimension(1000, 550)); panel2.setVisible(false); panel2.setBorder(new EmptyBorder(10, 10, 10, 10)); panel3.setVisible(false); panel.setLayout(new FlowLayout()); panel.add(scrollPane); searchPanel.add(searchLabel); searchPanel.add(searchText); searchPanel.add(searchButton); searchButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); search(g, searchText.getText(), frame, bButton); frame.setCursor(Cursor.getDefaultCursor()); } catch (IOException ex) { Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex); } } }); table.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.getClickCount() == 1) { JTable target = (JTable) e.getSource(); panel.setVisible(false); searchPanel.setVisible(false); bButton.setVisible(false); int row = target.getSelectedRow(); specific(row, g, frame, bButton); } } });

    Read the article

  • A Taxonomy of Numerical Methods v1

    - by JoshReuben
    Numerical Analysis – When, What, (but not how) Once you understand the Math & know C++, Numerical Methods are basically blocks of iterative & conditional math code. I found the real trick was seeing the forest for the trees – knowing which method to use for which situation. Its pretty easy to get lost in the details – so I’ve tried to organize these methods in a way that I can quickly look this up. I’ve included links to detailed explanations and to C++ code examples. I’ve tried to classify Numerical methods in the following broad categories: Solving Systems of Linear Equations Solving Non-Linear Equations Iteratively Interpolation Curve Fitting Optimization Numerical Differentiation & Integration Solving ODEs Boundary Problems Solving EigenValue problems Enjoy – I did ! Solving Systems of Linear Equations Overview Solve sets of algebraic equations with x unknowns The set is commonly in matrix form Gauss-Jordan Elimination http://en.wikipedia.org/wiki/Gauss%E2%80%93Jordan_elimination C++: http://www.codekeep.net/snippets/623f1923-e03c-4636-8c92-c9dc7aa0d3c0.aspx Produces solution of the equations & the coefficient matrix Efficient, stable 2 steps: · Forward Elimination – matrix decomposition: reduce set to triangular form (0s below the diagonal) or row echelon form. If degenerate, then there is no solution · Backward Elimination –write the original matrix as the product of ints inverse matrix & its reduced row-echelon matrix à reduce set to row canonical form & use back-substitution to find the solution to the set Elementary ops for matrix decomposition: · Row multiplication · Row switching · Add multiples of rows to other rows Use pivoting to ensure rows are ordered for achieving triangular form LU Decomposition http://en.wikipedia.org/wiki/LU_decomposition C++: http://ganeshtiwaridotcomdotnp.blogspot.co.il/2009/12/c-c-code-lu-decomposition-for-solving.html Represent the matrix as a product of lower & upper triangular matrices A modified version of GJ Elimination Advantage – can easily apply forward & backward elimination to solve triangular matrices Techniques: · Doolittle Method – sets the L matrix diagonal to unity · Crout Method - sets the U matrix diagonal to unity Note: both the L & U matrices share the same unity diagonal & can be stored compactly in the same matrix Gauss-Seidel Iteration http://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method C++: http://www.nr.com/forum/showthread.php?t=722 Transform the linear set of equations into a single equation & then use numerical integration (as integration formulas have Sums, it is implemented iteratively). an optimization of Gauss-Jacobi: 1.5 times faster, requires 0.25 iterations to achieve the same tolerance Solving Non-Linear Equations Iteratively find roots of polynomials – there may be 0, 1 or n solutions for an n order polynomial use iterative techniques Iterative methods · used when there are no known analytical techniques · Requires set functions to be continuous & differentiable · Requires an initial seed value – choice is critical to convergence à conduct multiple runs with different starting points & then select best result · Systematic - iterate until diminishing returns, tolerance or max iteration conditions are met · bracketing techniques will always yield convergent solutions, non-bracketing methods may fail to converge Incremental method if a nonlinear function has opposite signs at 2 ends of a small interval x1 & x2, then there is likely to be a solution in their interval – solutions are detected by evaluating a function over interval steps, for a change in sign, adjusting the step size dynamically. Limitations – can miss closely spaced solutions in large intervals, cannot detect degenerate (coinciding) solutions, limited to functions that cross the x-axis, gives false positives for singularities Fixed point method http://en.wikipedia.org/wiki/Fixed-point_iteration C++: http://books.google.co.il/books?id=weYj75E_t6MC&pg=PA79&lpg=PA79&dq=fixed+point+method++c%2B%2B&source=bl&ots=LQ-5P_taoC&sig=lENUUIYBK53tZtTwNfHLy5PEWDk&hl=en&sa=X&ei=wezDUPW1J5DptQaMsIHQCw&redir_esc=y#v=onepage&q=fixed%20point%20method%20%20c%2B%2B&f=false Algebraically rearrange a solution to isolate a variable then apply incremental method Bisection method http://en.wikipedia.org/wiki/Bisection_method C++: http://numericalcomputing.wordpress.com/category/algorithms/ Bracketed - Select an initial interval, keep bisecting it ad midpoint into sub-intervals and then apply incremental method on smaller & smaller intervals – zoom in Adv: unaffected by function gradient à reliable Disadv: slow convergence False Position Method http://en.wikipedia.org/wiki/False_position_method C++: http://www.dreamincode.net/forums/topic/126100-bisection-and-false-position-methods/ Bracketed - Select an initial interval , & use the relative value of function at interval end points to select next sub-intervals (estimate how far between the end points the solution might be & subdivide based on this) Newton-Raphson method http://en.wikipedia.org/wiki/Newton's_method C++: http://www-users.cselabs.umn.edu/classes/Summer-2012/csci1113/index.php?page=./newt3 Also known as Newton's method Convenient, efficient Not bracketed – only a single initial guess is required to start iteration – requires an analytical expression for the first derivative of the function as input. Evaluates the function & its derivative at each step. Can be extended to the Newton MutiRoot method for solving multiple roots Can be easily applied to an of n-coupled set of non-linear equations – conduct a Taylor Series expansion of a function, dropping terms of order n, rewrite as a Jacobian matrix of PDs & convert to simultaneous linear equations !!! Secant Method http://en.wikipedia.org/wiki/Secant_method C++: http://forum.vcoderz.com/showthread.php?p=205230 Unlike N-R, can estimate first derivative from an initial interval (does not require root to be bracketed) instead of inputting it Since derivative is approximated, may converge slower. Is fast in practice as it does not have to evaluate the derivative at each step. Similar implementation to False Positive method Birge-Vieta Method http://mat.iitm.ac.in/home/sryedida/public_html/caimna/transcendental/polynomial%20methods/bv%20method.html C++: http://books.google.co.il/books?id=cL1boM2uyQwC&pg=SA3-PA51&lpg=SA3-PA51&dq=Birge-Vieta+Method+c%2B%2B&source=bl&ots=QZmnDTK3rC&sig=BPNcHHbpR_DKVoZXrLi4nVXD-gg&hl=en&sa=X&ei=R-_DUK2iNIjzsgbE5ID4Dg&redir_esc=y#v=onepage&q=Birge-Vieta%20Method%20c%2B%2B&f=false combines Horner's method of polynomial evaluation (transforming into lesser degree polynomials that are more computationally efficient to process) with Newton-Raphson to provide a computational speed-up Interpolation Overview Construct new data points for as close as possible fit within range of a discrete set of known points (that were obtained via sampling, experimentation) Use Taylor Series Expansion of a function f(x) around a specific value for x Linear Interpolation http://en.wikipedia.org/wiki/Linear_interpolation C++: http://www.hamaluik.com/?p=289 Straight line between 2 points à concatenate interpolants between each pair of data points Bilinear Interpolation http://en.wikipedia.org/wiki/Bilinear_interpolation C++: http://supercomputingblog.com/graphics/coding-bilinear-interpolation/2/ Extension of the linear function for interpolating functions of 2 variables – perform linear interpolation first in 1 direction, then in another. Used in image processing – e.g. texture mapping filter. Uses 4 vertices to interpolate a value within a unit cell. Lagrange Interpolation http://en.wikipedia.org/wiki/Lagrange_polynomial C++: http://www.codecogs.com/code/maths/approximation/interpolation/lagrange.php For polynomials Requires recomputation for all terms for each distinct x value – can only be applied for small number of nodes Numerically unstable Barycentric Interpolation http://epubs.siam.org/doi/pdf/10.1137/S0036144502417715 C++: http://www.gamedev.net/topic/621445-barycentric-coordinates-c-code-check/ Rearrange the terms in the equation of the Legrange interpolation by defining weight functions that are independent of the interpolated value of x Newton Divided Difference Interpolation http://en.wikipedia.org/wiki/Newton_polynomial C++: http://jee-appy.blogspot.co.il/2011/12/newton-divided-difference-interpolation.html Hermite Divided Differences: Interpolation polynomial approximation for a given set of data points in the NR form - divided differences are used to approximately calculate the various differences. For a given set of 3 data points , fit a quadratic interpolant through the data Bracketed functions allow Newton divided differences to be calculated recursively Difference table Cubic Spline Interpolation http://en.wikipedia.org/wiki/Spline_interpolation C++: https://www.marcusbannerman.co.uk/index.php/home/latestarticles/42-articles/96-cubic-spline-class.html Spline is a piecewise polynomial Provides smoothness – for interpolations with significantly varying data Use weighted coefficients to bend the function to be smooth & its 1st & 2nd derivatives are continuous through the edge points in the interval Curve Fitting A generalization of interpolating whereby given data points may contain noise à the curve does not necessarily pass through all the points Least Squares Fit http://en.wikipedia.org/wiki/Least_squares C++: http://www.ccas.ru/mmes/educat/lab04k/02/least-squares.c Residual – difference between observed value & expected value Model function is often chosen as a linear combination of the specified functions Determines: A) The model instance in which the sum of squared residuals has the least value B) param values for which model best fits data Straight Line Fit Linear correlation between independent variable and dependent variable Linear Regression http://en.wikipedia.org/wiki/Linear_regression C++: http://www.oocities.org/david_swaim/cpp/linregc.htm Special case of statistically exact extrapolation Leverage least squares Given a basis function, the sum of the residuals is determined and the corresponding gradient equation is expressed as a set of normal linear equations in matrix form that can be solved (e.g. using LU Decomposition) Can be weighted - Drop the assumption that all errors have the same significance –-> confidence of accuracy is different for each data point. Fit the function closer to points with higher weights Polynomial Fit - use a polynomial basis function Moving Average http://en.wikipedia.org/wiki/Moving_average C++: http://www.codeproject.com/Articles/17860/A-Simple-Moving-Average-Algorithm Used for smoothing (cancel fluctuations to highlight longer-term trends & cycles), time series data analysis, signal processing filters Replace each data point with average of neighbors. Can be simple (SMA), weighted (WMA), exponential (EMA). Lags behind latest data points – extra weight can be given to more recent data points. Weights can decrease arithmetically or exponentially according to distance from point. Parameters: smoothing factor, period, weight basis Optimization Overview Given function with multiple variables, find Min (or max by minimizing –f(x)) Iterative approach Efficient, but not necessarily reliable Conditions: noisy data, constraints, non-linear models Detection via sign of first derivative - Derivative of saddle points will be 0 Local minima Bisection method Similar method for finding a root for a non-linear equation Start with an interval that contains a minimum Golden Search method http://en.wikipedia.org/wiki/Golden_section_search C++: http://www.codecogs.com/code/maths/optimization/golden.php Bisect intervals according to golden ratio 0.618.. Achieves reduction by evaluating a single function instead of 2 Newton-Raphson Method Brent method http://en.wikipedia.org/wiki/Brent's_method C++: http://people.sc.fsu.edu/~jburkardt/cpp_src/brent/brent.cpp Based on quadratic or parabolic interpolation – if the function is smooth & parabolic near to the minimum, then a parabola fitted through any 3 points should approximate the minima – fails when the 3 points are collinear , in which case the denominator is 0 Simplex Method http://en.wikipedia.org/wiki/Simplex_algorithm C++: http://www.codeguru.com/cpp/article.php/c17505/Simplex-Optimization-Algorithm-and-Implemetation-in-C-Programming.htm Find the global minima of any multi-variable function Direct search – no derivatives required At each step it maintains a non-degenerative simplex – a convex hull of n+1 vertices. Obtains the minimum for a function with n variables by evaluating the function at n-1 points, iteratively replacing the point of worst result with the point of best result, shrinking the multidimensional simplex around the best point. Point replacement involves expanding & contracting the simplex near the worst value point to determine a better replacement point Oscillation can be avoided by choosing the 2nd worst result Restart if it gets stuck Parameters: contraction & expansion factors Simulated Annealing http://en.wikipedia.org/wiki/Simulated_annealing C++: http://code.google.com/p/cppsimulatedannealing/ Analogy to heating & cooling metal to strengthen its structure Stochastic method – apply random permutation search for global minima - Avoid entrapment in local minima via hill climbing Heating schedule - Annealing schedule params: temperature, iterations at each temp, temperature delta Cooling schedule – can be linear, step-wise or exponential Differential Evolution http://en.wikipedia.org/wiki/Differential_evolution C++: http://www.amichel.com/de/doc/html/ More advanced stochastic methods analogous to biological processes: Genetic algorithms, evolution strategies Parallel direct search method against multiple discrete or continuous variables Initial population of variable vectors chosen randomly – if weighted difference vector of 2 vectors yields a lower objective function value then it replaces the comparison vector Many params: #parents, #variables, step size, crossover constant etc Convergence is slow – many more function evaluations than simulated annealing Numerical Differentiation Overview 2 approaches to finite difference methods: · A) approximate function via polynomial interpolation then differentiate · B) Taylor series approximation – additionally provides error estimate Finite Difference methods http://en.wikipedia.org/wiki/Finite_difference_method C++: http://www.wpi.edu/Pubs/ETD/Available/etd-051807-164436/unrestricted/EAMPADU.pdf Find differences between high order derivative values - Approximate differential equations by finite differences at evenly spaced data points Based on forward & backward Taylor series expansion of f(x) about x plus or minus multiples of delta h. Forward / backward difference - the sums of the series contains even derivatives and the difference of the series contains odd derivatives – coupled equations that can be solved. Provide an approximation of the derivative within a O(h^2) accuracy There is also central difference & extended central difference which has a O(h^4) accuracy Richardson Extrapolation http://en.wikipedia.org/wiki/Richardson_extrapolation C++: http://mathscoding.blogspot.co.il/2012/02/introduction-richardson-extrapolation.html A sequence acceleration method applied to finite differences Fast convergence, high accuracy O(h^4) Derivatives via Interpolation Cannot apply Finite Difference method to discrete data points at uneven intervals – so need to approximate the derivative of f(x) using the derivative of the interpolant via 3 point Lagrange Interpolation Note: the higher the order of the derivative, the lower the approximation precision Numerical Integration Estimate finite & infinite integrals of functions More accurate procedure than numerical differentiation Use when it is not possible to obtain an integral of a function analytically or when the function is not given, only the data points are Newton Cotes Methods http://en.wikipedia.org/wiki/Newton%E2%80%93Cotes_formulas C++: http://www.siafoo.net/snippet/324 For equally spaced data points Computationally easy – based on local interpolation of n rectangular strip areas that is piecewise fitted to a polynomial to get the sum total area Evaluate the integrand at n+1 evenly spaced points – approximate definite integral by Sum Weights are derived from Lagrange Basis polynomials Leverage Trapezoidal Rule for default 2nd formulas, Simpson 1/3 Rule for substituting 3 point formulas, Simpson 3/8 Rule for 4 point formulas. For 4 point formulas use Bodes Rule. Higher orders obtain more accurate results Trapezoidal Rule uses simple area, Simpsons Rule replaces the integrand f(x) with a quadratic polynomial p(x) that uses the same values as f(x) for its end points, but adds a midpoint Romberg Integration http://en.wikipedia.org/wiki/Romberg's_method C++: http://code.google.com/p/romberg-integration/downloads/detail?name=romberg.cpp&can=2&q= Combines trapezoidal rule with Richardson Extrapolation Evaluates the integrand at equally spaced points The integrand must have continuous derivatives Each R(n,m) extrapolation uses a higher order integrand polynomial replacement rule (zeroth starts with trapezoidal) à a lower triangular matrix set of equation coefficients where the bottom right term has the most accurate approximation. The process continues until the difference between 2 successive diagonal terms becomes sufficiently small. Gaussian Quadrature http://en.wikipedia.org/wiki/Gaussian_quadrature C++: http://www.alglib.net/integration/gaussianquadratures.php Data points are chosen to yield best possible accuracy – requires fewer evaluations Ability to handle singularities, functions that are difficult to evaluate The integrand can include a weighting function determined by a set of orthogonal polynomials. Points & weights are selected so that the integrand yields the exact integral if f(x) is a polynomial of degree <= 2n+1 Techniques (basically different weighting functions): · Gauss-Legendre Integration w(x)=1 · Gauss-Laguerre Integration w(x)=e^-x · Gauss-Hermite Integration w(x)=e^-x^2 · Gauss-Chebyshev Integration w(x)= 1 / Sqrt(1-x^2) Solving ODEs Use when high order differential equations cannot be solved analytically Evaluated under boundary conditions RK for systems – a high order differential equation can always be transformed into a coupled first order system of equations Euler method http://en.wikipedia.org/wiki/Euler_method C++: http://rosettacode.org/wiki/Euler_method First order Runge–Kutta method. Simple recursive method – given an initial value, calculate derivative deltas. Unstable & not very accurate (O(h) error) – not used in practice A first-order method - the local error (truncation error per step) is proportional to the square of the step size, and the global error (error at a given time) is proportional to the step size In evolving solution between data points xn & xn+1, only evaluates derivatives at beginning of interval xn à asymmetric at boundaries Higher order Runge Kutta http://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods C++: http://www.dreamincode.net/code/snippet1441.htm 2nd & 4th order RK - Introduces parameterized midpoints for more symmetric solutions à accuracy at higher computational cost Adaptive RK – RK-Fehlberg – estimate the truncation at each integration step & automatically adjust the step size to keep error within prescribed limits. At each step 2 approximations are compared – if in disagreement to a specific accuracy, the step size is reduced Boundary Value Problems Where solution of differential equations are located at 2 different values of the independent variable x à more difficult, because cannot just start at point of initial value – there may not be enough starting conditions available at the end points to produce a unique solution An n-order equation will require n boundary conditions – need to determine the missing n-1 conditions which cause the given conditions at the other boundary to be satisfied Shooting Method http://en.wikipedia.org/wiki/Shooting_method C++: http://ganeshtiwaridotcomdotnp.blogspot.co.il/2009/12/c-c-code-shooting-method-for-solving.html Iteratively guess the missing values for one end & integrate, then inspect the discrepancy with the boundary values of the other end to adjust the estimate Given the starting boundary values u1 & u2 which contain the root u, solve u given the false position method (solving the differential equation as an initial value problem via 4th order RK), then use u to solve the differential equations. Finite Difference Method For linear & non-linear systems Higher order derivatives require more computational steps – some combinations for boundary conditions may not work though Improve the accuracy by increasing the number of mesh points Solving EigenValue Problems An eigenvalue can substitute a matrix when doing matrix multiplication à convert matrix multiplication into a polynomial EigenValue For a given set of equations in matrix form, determine what are the solution eigenvalue & eigenvectors Similar Matrices - have same eigenvalues. Use orthogonal similarity transforms to reduce a matrix to diagonal form from which eigenvalue(s) & eigenvectors can be computed iteratively Jacobi method http://en.wikipedia.org/wiki/Jacobi_method C++: http://people.sc.fsu.edu/~jburkardt/classes/acs2_2008/openmp/jacobi/jacobi.html Robust but Computationally intense – use for small matrices < 10x10 Power Iteration http://en.wikipedia.org/wiki/Power_iteration For any given real symmetric matrix, generate the largest single eigenvalue & its eigenvectors Simplest method – does not compute matrix decomposition à suitable for large, sparse matrices Inverse Iteration Variation of power iteration method – generates the smallest eigenvalue from the inverse matrix Rayleigh Method http://en.wikipedia.org/wiki/Rayleigh's_method_of_dimensional_analysis Variation of power iteration method Rayleigh Quotient Method Variation of inverse iteration method Matrix Tri-diagonalization Method Use householder algorithm to reduce an NxN symmetric matrix to a tridiagonal real symmetric matrix vua N-2 orthogonal transforms     Whats Next Outside of Numerical Methods there are lots of different types of algorithms that I’ve learned over the decades: Data Mining – (I covered this briefly in a previous post: http://geekswithblogs.net/JoshReuben/archive/2007/12/31/ssas-dm-algorithms.aspx ) Search & Sort Routing Problem Solving Logical Theorem Proving Planning Probabilistic Reasoning Machine Learning Solvers (eg MIP) Bioinformatics (Sequence Alignment, Protein Folding) Quant Finance (I read Wilmott’s books – interesting) Sooner or later, I’ll cover the above topics as well.

    Read the article

  • Help with Collision Resolution?

    - by Milo
    I'm trying to learn about physics by trying to make a simplified GTA 2 clone. My only problem is collision resolution. Everything else works great. I have a rigid body class and from there cars and a wheel class: class RigidBody extends Entity { //linear private Vector2D velocity = new Vector2D(); private Vector2D forces = new Vector2D(); private OBB2D predictionRect = new OBB2D(new Vector2D(), 1.0f, 1.0f, 0.0f); private float mass; private Vector2D deltaVec = new Vector2D(); private Vector2D v = new Vector2D(); //angular private float angularVelocity; private float torque; private float inertia; //graphical private Vector2D halfSize = new Vector2D(); private Bitmap image; private Matrix mat = new Matrix(); private float[] Vector2Ds = new float[2]; private Vector2D tangent = new Vector2D(); private static Vector2D worldRelVec = new Vector2D(); private static Vector2D relWorldVec = new Vector2D(); private static Vector2D pointVelVec = new Vector2D(); public RigidBody() { //set these defaults so we don't get divide by zeros mass = 1.0f; inertia = 1.0f; setLayer(LAYER_OBJECTS); } protected void rectChanged() { if(getWorld() != null) { getWorld().updateDynamic(this); } } //intialize out parameters public void initialize(Vector2D halfSize, float mass, Bitmap bitmap) { //store physical parameters this.halfSize = halfSize; this.mass = mass; image = bitmap; inertia = (1.0f / 20.0f) * (halfSize.x * halfSize.x) * (halfSize.y * halfSize.y) * mass; RectF rect = new RectF(); float scalar = 10.0f; rect.left = (int)-halfSize.x * scalar; rect.top = (int)-halfSize.y * scalar; rect.right = rect.left + (int)(halfSize.x * 2.0f * scalar); rect.bottom = rect.top + (int)(halfSize.y * 2.0f * scalar); setRect(rect); predictionRect.set(rect); } public void setLocation(Vector2D position, float angle) { getRect().set(position, getWidth(), getHeight(), angle); rectChanged(); } public void setPredictionLocation(Vector2D position, float angle) { getPredictionRect().set(position, getWidth(), getHeight(), angle); } public void setPredictionCenter(Vector2D center) { getPredictionRect().moveTo(center); } public void setPredictionAngle(float angle) { predictionRect.setAngle(angle); } public Vector2D getPosition() { return getRect().getCenter(); } public OBB2D getPredictionRect() { return predictionRect; } @Override public void update(float timeStep) { doUpdate(false,timeStep); } public void doUpdate(boolean prediction, float timeStep) { //integrate physics //linear Vector2D acceleration = Vector2D.scalarDivide(forces, mass); if(prediction) { Vector2D velocity = Vector2D.add(this.velocity, Vector2D.scalarMultiply(acceleration, timeStep)); Vector2D c = getRect().getCenter(); c = Vector2D.add(getRect().getCenter(), Vector2D.scalarMultiply(velocity , timeStep)); setPredictionCenter(c); //forces = new Vector2D(0,0); //clear forces } else { velocity.x += (acceleration.x * timeStep); velocity.y += (acceleration.y * timeStep); //velocity = Vector2D.add(velocity, Vector2D.scalarMultiply(acceleration, timeStep)); Vector2D c = getRect().getCenter(); v.x = getRect().getCenter().getX() + (velocity.x * timeStep); v.y = getRect().getCenter().getY() + (velocity.y * timeStep); deltaVec.x = v.x - c.x; deltaVec.y = v.y - c.y; deltaVec.normalize(); setCenter(v.x, v.y); forces.x = 0; //clear forces forces.y = 0; } //angular float angAcc = torque / inertia; if(prediction) { float angularVelocity = this.angularVelocity + angAcc * timeStep; setPredictionAngle(getAngle() + angularVelocity * timeStep); //torque = 0; //clear torque } else { angularVelocity += angAcc * timeStep; setAngle(getAngle() + angularVelocity * timeStep); torque = 0; //clear torque } } public void updatePrediction(float timeStep) { doUpdate(true, timeStep); } //take a relative Vector2D and make it a world Vector2D public Vector2D relativeToWorld(Vector2D relative) { mat.reset(); Vector2Ds[0] = relative.x; Vector2Ds[1] = relative.y; mat.postRotate(JMath.radToDeg(getAngle())); mat.mapVectors(Vector2Ds); relWorldVec.x = Vector2Ds[0]; relWorldVec.y = Vector2Ds[1]; return new Vector2D(Vector2Ds[0], Vector2Ds[1]); } //take a world Vector2D and make it a relative Vector2D public Vector2D worldToRelative(Vector2D world) { mat.reset(); Vector2Ds[0] = world.x; Vector2Ds[1] = world.y; mat.postRotate(JMath.radToDeg(-getAngle())); mat.mapVectors(Vector2Ds); return new Vector2D(Vector2Ds[0], Vector2Ds[1]); } //velocity of a point on body public Vector2D pointVelocity(Vector2D worldOffset) { tangent.x = -worldOffset.y; tangent.y = worldOffset.x; return Vector2D.add( Vector2D.scalarMultiply(tangent, angularVelocity) , velocity); } public void applyForce(Vector2D worldForce, Vector2D worldOffset) { //add linear force forces.x += worldForce.x; forces.y += worldForce.y; //add associated torque torque += Vector2D.cross(worldOffset, worldForce); } @Override public void draw( GraphicsContext c) { c.drawRotatedScaledBitmap(image, getPosition().x, getPosition().y, getWidth(), getHeight(), getAngle()); } public Vector2D getVelocity() { return velocity; } public void setVelocity(Vector2D velocity) { this.velocity = velocity; } public Vector2D getDeltaVec() { return deltaVec; } } Vehicle public class Wheel { private Vector2D forwardVec; private Vector2D sideVec; private float wheelTorque; private float wheelSpeed; private float wheelInertia; private float wheelRadius; private Vector2D position = new Vector2D(); public Wheel(Vector2D position, float radius) { this.position = position; setSteeringAngle(0); wheelSpeed = 0; wheelRadius = radius; wheelInertia = (radius * radius) * 1.1f; } public void setSteeringAngle(float newAngle) { Matrix mat = new Matrix(); float []vecArray = new float[4]; //forward Vector vecArray[0] = 0; vecArray[1] = 1; //side Vector vecArray[2] = -1; vecArray[3] = 0; mat.postRotate(newAngle / (float)Math.PI * 180.0f); mat.mapVectors(vecArray); forwardVec = new Vector2D(vecArray[0], vecArray[1]); sideVec = new Vector2D(vecArray[2], vecArray[3]); } public void addTransmissionTorque(float newValue) { wheelTorque += newValue; } public float getWheelSpeed() { return wheelSpeed; } public Vector2D getAnchorPoint() { return position; } public Vector2D calculateForce(Vector2D relativeGroundSpeed, float timeStep, boolean prediction) { //calculate speed of tire patch at ground Vector2D patchSpeed = Vector2D.scalarMultiply(Vector2D.scalarMultiply( Vector2D.negative(forwardVec), wheelSpeed), wheelRadius); //get velocity difference between ground and patch Vector2D velDifference = Vector2D.add(relativeGroundSpeed , patchSpeed); //project ground speed onto side axis Float forwardMag = new Float(0.0f); Vector2D sideVel = velDifference.project(sideVec); Vector2D forwardVel = velDifference.project(forwardVec, forwardMag); //calculate super fake friction forces //calculate response force Vector2D responseForce = Vector2D.scalarMultiply(Vector2D.negative(sideVel), 2.0f); responseForce = Vector2D.subtract(responseForce, forwardVel); float topSpeed = 500.0f; //calculate torque on wheel wheelTorque += forwardMag * wheelRadius; //integrate total torque into wheel wheelSpeed += wheelTorque / wheelInertia * timeStep; //top speed limit (kind of a hack) if(wheelSpeed > topSpeed) { wheelSpeed = topSpeed; } //clear our transmission torque accumulator wheelTorque = 0; //return force acting on body return responseForce; } public void setTransmissionTorque(float newValue) { wheelTorque = newValue; } public float getTransmissionTourque() { return wheelTorque; } public void setWheelSpeed(float speed) { wheelSpeed = speed; } } //our vehicle object public class Vehicle extends RigidBody { private Wheel [] wheels = new Wheel[4]; private boolean throttled = false; public void initialize(Vector2D halfSize, float mass, Bitmap bitmap) { //front wheels wheels[0] = new Wheel(new Vector2D(halfSize.x, halfSize.y), 0.45f); wheels[1] = new Wheel(new Vector2D(-halfSize.x, halfSize.y), 0.45f); //rear wheels wheels[2] = new Wheel(new Vector2D(halfSize.x, -halfSize.y), 0.75f); wheels[3] = new Wheel(new Vector2D(-halfSize.x, -halfSize.y), 0.75f); super.initialize(halfSize, mass, bitmap); } public void setSteering(float steering) { float steeringLock = 0.13f; //apply steering angle to front wheels wheels[0].setSteeringAngle(steering * steeringLock); wheels[1].setSteeringAngle(steering * steeringLock); } public void setThrottle(float throttle, boolean allWheel) { float torque = 85.0f; throttled = true; //apply transmission torque to back wheels if (allWheel) { wheels[0].addTransmissionTorque(throttle * torque); wheels[1].addTransmissionTorque(throttle * torque); } wheels[2].addTransmissionTorque(throttle * torque); wheels[3].addTransmissionTorque(throttle * torque); } public void setBrakes(float brakes) { float brakeTorque = 15.0f; //apply brake torque opposing wheel vel for (Wheel wheel : wheels) { float wheelVel = wheel.getWheelSpeed(); wheel.addTransmissionTorque(-wheelVel * brakeTorque * brakes); } } public void doUpdate(float timeStep, boolean prediction) { for (Wheel wheel : wheels) { float wheelVel = wheel.getWheelSpeed(); //apply negative force to naturally slow down car if(!throttled && !prediction) wheel.addTransmissionTorque(-wheelVel * 0.11f); Vector2D worldWheelOffset = relativeToWorld(wheel.getAnchorPoint()); Vector2D worldGroundVel = pointVelocity(worldWheelOffset); Vector2D relativeGroundSpeed = worldToRelative(worldGroundVel); Vector2D relativeResponseForce = wheel.calculateForce(relativeGroundSpeed, timeStep,prediction); Vector2D worldResponseForce = relativeToWorld(relativeResponseForce); applyForce(worldResponseForce, worldWheelOffset); } //no throttling yet this frame throttled = false; if(prediction) { super.updatePrediction(timeStep); } else { super.update(timeStep); } } @Override public void update(float timeStep) { doUpdate(timeStep,false); } public void updatePrediction(float timeStep) { doUpdate(timeStep,true); } public void inverseThrottle() { float scalar = 0.2f; for(Wheel wheel : wheels) { wheel.setTransmissionTorque(-wheel.getTransmissionTourque() * scalar); wheel.setWheelSpeed(-wheel.getWheelSpeed() * 0.1f); } } } And my big hack collision resolution: private void update() { camera.setPosition((vehicle.getPosition().x * camera.getScale()) - ((getWidth() ) / 2.0f), (vehicle.getPosition().y * camera.getScale()) - ((getHeight() ) / 2.0f)); //camera.move(input.getAnalogStick().getStickValueX() * 15.0f, input.getAnalogStick().getStickValueY() * 15.0f); if(input.isPressed(ControlButton.BUTTON_GAS)) { vehicle.setThrottle(1.0f, false); } if(input.isPressed(ControlButton.BUTTON_STEAL_CAR)) { vehicle.setThrottle(-1.0f, false); } if(input.isPressed(ControlButton.BUTTON_BRAKE)) { vehicle.setBrakes(1.0f); } vehicle.setSteering(input.getAnalogStick().getStickValueX()); //vehicle.update(16.6666666f / 1000.0f); boolean colided = false; vehicle.updatePrediction(16.66666f / 1000.0f); List<Entity> buildings = world.queryStaticSolid(vehicle,vehicle.getPredictionRect()); if(buildings.size() > 0) { colided = true; } if(!colided) { vehicle.update(16.66f / 1000.0f); } else { Vector2D delta = vehicle.getDeltaVec(); vehicle.setVelocity(Vector2D.negative(vehicle.getVelocity().multiply(0.2f)). add(delta.multiply(-1.0f))); vehicle.inverseThrottle(); } } Here is OBB public class OBB2D { // Corners of the box, where 0 is the lower left. private Vector2D corner[] = new Vector2D[4]; private Vector2D center = new Vector2D(); private Vector2D extents = new Vector2D(); private RectF boundingRect = new RectF(); private float angle; //Two edges of the box extended away from corner[0]. private Vector2D axis[] = new Vector2D[2]; private double origin[] = new double[2]; public OBB2D(Vector2D center, float w, float h, float angle) { set(center,w,h,angle); } public OBB2D(float left, float top, float width, float height) { set(new Vector2D(left + (width / 2), top + (height / 2)),width,height,0.0f); } public void set(Vector2D center,float w, float h,float angle) { Vector2D X = new Vector2D( (float)Math.cos(angle), (float)Math.sin(angle)); Vector2D Y = new Vector2D((float)-Math.sin(angle), (float)Math.cos(angle)); X = X.multiply( w / 2); Y = Y.multiply( h / 2); corner[0] = center.subtract(X).subtract(Y); corner[1] = center.add(X).subtract(Y); corner[2] = center.add(X).add(Y); corner[3] = center.subtract(X).add(Y); computeAxes(); extents.x = w / 2; extents.y = h / 2; computeDimensions(center,angle); } private void computeDimensions(Vector2D center,float angle) { this.center.x = center.x; this.center.y = center.y; this.angle = angle; boundingRect.left = Math.min(Math.min(corner[0].x, corner[3].x), Math.min(corner[1].x, corner[2].x)); boundingRect.top = Math.min(Math.min(corner[0].y, corner[1].y),Math.min(corner[2].y, corner[3].y)); boundingRect.right = Math.max(Math.max(corner[1].x, corner[2].x), Math.max(corner[0].x, corner[3].x)); boundingRect.bottom = Math.max(Math.max(corner[2].y, corner[3].y),Math.max(corner[0].y, corner[1].y)); } public void set(RectF rect) { set(new Vector2D(rect.centerX(),rect.centerY()),rect.width(),rect.height(),0.0f); } // Returns true if other overlaps one dimension of this. private boolean overlaps1Way(OBB2D other) { for (int a = 0; a < axis.length; ++a) { double t = other.corner[0].dot(axis[a]); // Find the extent of box 2 on axis a double tMin = t; double tMax = t; for (int c = 1; c < corner.length; ++c) { t = other.corner[c].dot(axis[a]); if (t < tMin) { tMin = t; } else if (t > tMax) { tMax = t; } } // We have to subtract off the origin // See if [tMin, tMax] intersects [0, 1] if ((tMin > 1 + origin[a]) || (tMax < origin[a])) { // There was no intersection along this dimension; // the boxes cannot possibly overlap. return false; } } // There was no dimension along which there is no intersection. // Therefore the boxes overlap. return true; } //Updates the axes after the corners move. Assumes the //corners actually form a rectangle. private void computeAxes() { axis[0] = corner[1].subtract(corner[0]); axis[1] = corner[3].subtract(corner[0]); // Make the length of each axis 1/edge length so we know any // dot product must be less than 1 to fall within the edge. for (int a = 0; a < axis.length; ++a) { axis[a] = axis[a].divide((axis[a].length() * axis[a].length())); origin[a] = corner[0].dot(axis[a]); } } public void moveTo(Vector2D center) { Vector2D centroid = (corner[0].add(corner[1]).add(corner[2]).add(corner[3])).divide(4.0f); Vector2D translation = center.subtract(centroid); for (int c = 0; c < 4; ++c) { corner[c] = corner[c].add(translation); } computeAxes(); computeDimensions(center,angle); } // Returns true if the intersection of the boxes is non-empty. public boolean overlaps(OBB2D other) { if(right() < other.left()) { return false; } if(bottom() < other.top()) { return false; } if(left() > other.right()) { return false; } if(top() > other.bottom()) { return false; } if(other.getAngle() == 0.0f && getAngle() == 0.0f) { return true; } return overlaps1Way(other) && other.overlaps1Way(this); } public Vector2D getCenter() { return center; } public float getWidth() { return extents.x * 2; } public float getHeight() { return extents.y * 2; } public void setAngle(float angle) { set(center,getWidth(),getHeight(),angle); } public float getAngle() { return angle; } public void setSize(float w,float h) { set(center,w,h,angle); } public float left() { return boundingRect.left; } public float right() { return boundingRect.right; } public float bottom() { return boundingRect.bottom; } public float top() { return boundingRect.top; } public RectF getBoundingRect() { return boundingRect; } public boolean overlaps(float left, float top, float right, float bottom) { if(right() < left) { return false; } if(bottom() < top) { return false; } if(left() > right) { return false; } if(top() > bottom) { return false; } return true; } }; What I do is when I predict a hit on the car, I force it back. It does not work that well and seems like a bad idea. What could I do to have more proper collision resolution. Such that if I hit a wall I will never get stuck in it and if I hit the side of a wall I can steer my way out of it. Thanks I found this nice ppt. It talks about pulling objects apart and calculating new velocities. How could I calc new velocities in my case? http://www.google.ca/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=0CC8QFjAB&url=http%3A%2F%2Fcoitweb.uncc.edu%2F~tbarnes2%2FGameDesignFall05%2FSlides%2FCh4.2-CollDet.ppt&ei=x4ucULy5M6-N0QGRy4D4Cg&usg=AFQjCNG7FVDXWRdLv8_-T5qnFyYld53cTQ&cad=rja

    Read the article

  • C++ Pointers: Number of levels of Indirection

    - by A B
    In a C++ program that doesn't contain legacy C code, is there a guideline regarding the maximum number of levels of indirection that should be used in the source code? I know that in C (as opposed to C++), some programmers have used pointers to pointers for a multiple dimension array, but for the case of arrays, there are data structures in C++ that can be used to avoid the pointers to pointers. Are users who still create pointers to pointers (or more than this) trying to use pointers to pointers only for performance ETC. reasons? I have tried NOT to use any more than a pointer to a pointer, only in the case that a pointer needed modification; does anyone have any other official or unofficial guidelines or rules regarding the number of levels of indirection?

    Read the article

  • Micro QR Code Generator with minimal error correction

    - by Florian Peschka
    I am searching a Micro QR Code Generator that fulfills the following requirements: At least 20 characters encoded Minimal error correction (required to get the 20 characters stuffed in) I already searched google, but it seems all micro qr generators automatically use maximum error correction, which is very unhandy for my task, as we need the 20 characters completety. I can't use standard QR because there are certain requirements that need the code to be smaller than a certain dimension when printed... I hope someone can help me. PS: I'm not sure that this is the right board to post this question on, so feel free to redirect me to a better board if you have an idea. PPS: If nothing can be found and I'm forced to write one on my own: Where can I find detailed information on how to write a QR code generator?

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >