idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
38,000
public boolean isControllerUp ( int controller ) { if ( controller >= getControllerCount ( ) ) { return false ; } if ( controller == ANY_CONTROLLER ) { for ( int i = 0 ; i < controllers . size ( ) ; i ++ ) { if ( isControllerUp ( i ) ) { return true ; } } return false ; } return ( ( Controller ) controllers . get ( controller ) ) . getYAxisValue ( ) < - 0.5f || ( ( Controller ) controllers . get ( controller ) ) . getPovY ( ) < - 0.5f ; }
Check if the controller has the up direction pressed
38,001
public boolean isButtonPressed ( int index , int controller ) { if ( controller >= getControllerCount ( ) ) { return false ; } if ( controller == ANY_CONTROLLER ) { for ( int i = 0 ; i < controllers . size ( ) ; i ++ ) { if ( isButtonPressed ( index , i ) ) { return true ; } } return false ; } return ( ( Controller ) controllers . get ( controller ) ) . isButtonPressed ( index ) ; }
Check if controller button is pressed
38,002
public void initControllers ( ) throws SlickException { if ( controllersInited ) { return ; } controllersInited = true ; try { Controllers . create ( ) ; int count = Controllers . getControllerCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { Controller controller = Controllers . getController ( i ) ; if ( ( controller . getButtonCount ( ) >= 3 ) && ( controller . getButtonCount ( ) < MAX_BUTTONS ) ) { controllers . add ( controller ) ; } } Log . info ( "Found " + controllers . size ( ) + " controllers" ) ; for ( int i = 0 ; i < controllers . size ( ) ; i ++ ) { Log . info ( i + " : " + ( ( Controller ) controllers . get ( i ) ) . getName ( ) ) ; } } catch ( LWJGLException e ) { if ( e . getCause ( ) instanceof ClassNotFoundException ) { throw new SlickException ( "Unable to create controller - no jinput found - add jinput.jar to your classpath" ) ; } throw new SlickException ( "Unable to create controllers" ) ; } catch ( NoClassDefFoundError e ) { } }
Initialise the controllers system
38,003
public void considerDoubleClick ( int button , int x , int y ) { if ( doubleClickTimeout == 0 ) { clickX = x ; clickY = y ; clickButton = button ; doubleClickTimeout = System . currentTimeMillis ( ) + doubleClickDelay ; fireMouseClicked ( button , x , y , 1 ) ; } else { if ( clickButton == button ) { if ( ( System . currentTimeMillis ( ) < doubleClickTimeout ) ) { fireMouseClicked ( button , x , y , 2 ) ; doubleClickTimeout = 0 ; } } } }
Notification that the mouse has been pressed and hence we should consider what we re doing with double clicking
38,004
private void fireControlPress ( int index , int controllerIndex ) { consumed = false ; for ( int i = 0 ; i < controllerListeners . size ( ) ; i ++ ) { ControllerListener listener = ( ControllerListener ) controllerListeners . get ( i ) ; if ( listener . isAcceptingInput ( ) ) { switch ( index ) { case LEFT : listener . controllerLeftPressed ( controllerIndex ) ; break ; case RIGHT : listener . controllerRightPressed ( controllerIndex ) ; break ; case UP : listener . controllerUpPressed ( controllerIndex ) ; break ; case DOWN : listener . controllerDownPressed ( controllerIndex ) ; break ; default : listener . controllerButtonPressed ( controllerIndex , ( index - BUTTON1 ) + 1 ) ; break ; } if ( consumed ) { break ; } } } }
Fire an event indicating that a control has been pressed
38,005
private void fireControlRelease ( int index , int controllerIndex ) { consumed = false ; for ( int i = 0 ; i < controllerListeners . size ( ) ; i ++ ) { ControllerListener listener = ( ControllerListener ) controllerListeners . get ( i ) ; if ( listener . isAcceptingInput ( ) ) { switch ( index ) { case LEFT : listener . controllerLeftReleased ( controllerIndex ) ; break ; case RIGHT : listener . controllerRightReleased ( controllerIndex ) ; break ; case UP : listener . controllerUpReleased ( controllerIndex ) ; break ; case DOWN : listener . controllerDownReleased ( controllerIndex ) ; break ; default : listener . controllerButtonReleased ( controllerIndex , ( index - BUTTON1 ) + 1 ) ; break ; } if ( consumed ) { break ; } } } }
Fire an event indicating that a control has been released
38,006
private boolean isControlDwn ( int index , int controllerIndex ) { switch ( index ) { case LEFT : return isControllerLeft ( controllerIndex ) ; case RIGHT : return isControllerRight ( controllerIndex ) ; case UP : return isControllerUp ( controllerIndex ) ; case DOWN : return isControllerDown ( controllerIndex ) ; } if ( index >= BUTTON1 ) { return isButtonPressed ( ( index - BUTTON1 ) , controllerIndex ) ; } throw new RuntimeException ( "Unknown control index" ) ; }
Check if a particular control is currently pressed
38,007
private void fireMouseClicked ( int button , int x , int y , int clickCount ) { consumed = false ; for ( int i = 0 ; i < mouseListeners . size ( ) ; i ++ ) { MouseListener listener = ( MouseListener ) mouseListeners . get ( i ) ; if ( listener . isAcceptingInput ( ) ) { listener . mouseClicked ( button , x , y , clickCount ) ; if ( consumed ) { break ; } } } }
Notify listeners that the mouse button has been clicked
38,008
protected IntBuffer createIntBuffer ( int size ) { ByteBuffer temp = ByteBuffer . allocateDirect ( 4 * size ) ; temp . order ( ByteOrder . nativeOrder ( ) ) ; return temp . asIntBuffer ( ) ; }
Creates an integer buffer to hold specified ints - strictly a utility method
38,009
public void setTextureData ( int srcPixelFormat , int componentCount , int minFilter , int magFilter , ByteBuffer textureBuffer ) { reloadData = new ReloadData ( ) ; reloadData . srcPixelFormat = srcPixelFormat ; reloadData . componentCount = componentCount ; reloadData . minFilter = minFilter ; reloadData . magFilter = magFilter ; reloadData . textureBuffer = textureBuffer ; }
Set the texture data that this texture can be reloaded from
38,010
public static void write ( Image image , String format , String dest , boolean writeAlpha ) throws SlickException { try { write ( image , format , new FileOutputStream ( dest ) , writeAlpha ) ; } catch ( IOException e ) { throw new SlickException ( "Unable to write to the destination: " + dest , e ) ; } }
Write an image out to a file on the local file system .
38,011
public Vector2f pointAt ( float t ) { float a = 1 - t ; float b = t ; float f1 = a * a * a ; float f2 = 3 * a * a * b ; float f3 = 3 * a * b * b ; float f4 = b * b * b ; float nx = ( p1 . x * f1 ) + ( c1 . x * f2 ) + ( c2 . x * f3 ) + ( p2 . x * f4 ) ; float ny = ( p1 . y * f1 ) + ( c1 . y * f2 ) + ( c2 . y * f3 ) + ( p2 . y * f4 ) ; return new Vector2f ( nx , ny ) ; }
Get the point at a particular location on the curve
38,012
public void toAngelCodeText ( PrintStream out , String imageName ) { out . println ( "info face=\"" + fontName + "\" size=" + size + " bold=0 italic=0 charset=\"" + setName + "\" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1" ) ; out . println ( "common lineHeight=" + lineHeight + " base=26 scaleW=" + width + " scaleH=" + height + " pages=1 packed=0" ) ; out . println ( "page id=0 file=\"" + imageName + "\"" ) ; out . println ( "chars count=" + chars . size ( ) ) ; for ( int i = 0 ; i < chars . size ( ) ; i ++ ) { CharData c = ( CharData ) chars . get ( i ) ; out . println ( "char id=" + c . getID ( ) + " x=" + c . getX ( ) + " y=" + c . getY ( ) + " width=" + c . getWidth ( ) + " height=" + c . getHeight ( ) + " xoffset=0 yoffset=" + c . getYOffset ( ) + " xadvance=" + c . getXAdvance ( ) + " page=0 chnl=0 " ) ; } out . println ( "kernings count=" + kerning . size ( ) ) ; for ( int i = 0 ; i < kerning . size ( ) ; i ++ ) { KerningData k = ( KerningData ) kerning . get ( i ) ; out . println ( "kerning first=" + k . first + " second=" + k . second + " amount=" + k . offset ) ; } }
Output this data set as an angel code data file
38,013
public void addCharacter ( int code , int xadvance , int x , int y , int width , int height , int yoffset ) { chars . add ( new CharData ( code , xadvance , x , y , width , height , size + yoffset ) ) ; }
Add a character to the data set
38,014
public void addKerning ( int first , int second , int offset ) { kerning . add ( new KerningData ( first , second , offset ) ) ; }
Add some kerning data
38,015
public float [ ] getEffectAt ( float x , float y , boolean colouredLights ) { float dx = ( x - xpos ) ; float dy = ( y - ypos ) ; float distance2 = ( dx * dx ) + ( dy * dy ) ; float effect = 1 - ( distance2 / ( strength * strength ) ) ; if ( effect < 0 ) { effect = 0 ; } if ( colouredLights ) { return new float [ ] { col . r * effect , col . g * effect , col . b * effect } ; } else { return new float [ ] { effect , effect , effect } ; } }
Get the effect the light should apply to a given location
38,016
public Image getSubImage ( int x , int y ) { init ( ) ; if ( ( x < 0 ) || ( x >= subImages . length ) ) { throw new RuntimeException ( "SubImage out of sheet bounds: " + x + "," + y ) ; } if ( ( y < 0 ) || ( y >= subImages [ 0 ] . length ) ) { throw new RuntimeException ( "SubImage out of sheet bounds: " + x + "," + y ) ; } return subImages [ x ] [ y ] ; }
Get the sub image cached in this sprite sheet
38,017
public Image getSprite ( int x , int y ) { target . init ( ) ; initImpl ( ) ; if ( ( x < 0 ) || ( x >= subImages . length ) ) { throw new RuntimeException ( "SubImage out of sheet bounds: " + x + "," + y ) ; } if ( ( y < 0 ) || ( y >= subImages [ 0 ] . length ) ) { throw new RuntimeException ( "SubImage out of sheet bounds: " + x + "," + y ) ; } return target . getSubImage ( x * ( tw + spacing ) + margin , y * ( th + spacing ) + margin , tw , th ) ; }
Get a sprite at a particular cell on the sprite sheet
38,018
public void renderInUse ( int x , int y , int sx , int sy ) { subImages [ sx ] [ sy ] . drawEmbedded ( x , y , tw , th ) ; }
Render a sprite when this sprite sheet is in use .
38,019
public void setTextureSize ( int width , int height ) { setPreferredSize ( new Dimension ( width , height ) ) ; setSize ( new Dimension ( width , height ) ) ; this . width = width ; this . height = height ; }
Set the size of the sprite sheet
38,020
public void setRadius ( float radius ) { if ( radius != this . radius ) { pointsDirty = true ; this . radius = radius ; setRadii ( radius , radius ) ; } }
Set the radius of this circle
38,021
public boolean intersects ( Shape shape ) { if ( shape instanceof Circle ) { Circle other = ( Circle ) shape ; float totalRad2 = getRadius ( ) + other . getRadius ( ) ; if ( Math . abs ( other . getCenterX ( ) - getCenterX ( ) ) > totalRad2 ) { return false ; } if ( Math . abs ( other . getCenterY ( ) - getCenterY ( ) ) > totalRad2 ) { return false ; } totalRad2 *= totalRad2 ; float dx = Math . abs ( other . getCenterX ( ) - getCenterX ( ) ) ; float dy = Math . abs ( other . getCenterY ( ) - getCenterY ( ) ) ; return totalRad2 >= ( ( dx * dx ) + ( dy * dy ) ) ; } else if ( shape instanceof Rectangle ) { return intersects ( ( Rectangle ) shape ) ; } else { return super . intersects ( shape ) ; } }
Check if this circle touches another
38,022
public boolean contains ( float x , float y ) { float xDelta = x - getCenterX ( ) , yDelta = y - getCenterY ( ) ; return xDelta * xDelta + yDelta * yDelta < getRadius ( ) * getRadius ( ) ; }
Check if a point is contained by this circle
38,023
private boolean contains ( Line line ) { return contains ( line . getX1 ( ) , line . getY1 ( ) ) && contains ( line . getX2 ( ) , line . getY2 ( ) ) ; }
Check if circle contains the line
38,024
private boolean intersects ( Rectangle other ) { Rectangle box = other ; Circle circle = this ; if ( box . contains ( x + radius , y + radius ) ) { return true ; } float x1 = box . getX ( ) ; float y1 = box . getY ( ) ; float x2 = box . getX ( ) + box . getWidth ( ) ; float y2 = box . getY ( ) + box . getHeight ( ) ; Line [ ] lines = new Line [ 4 ] ; lines [ 0 ] = new Line ( x1 , y1 , x2 , y1 ) ; lines [ 1 ] = new Line ( x2 , y1 , x2 , y2 ) ; lines [ 2 ] = new Line ( x2 , y2 , x1 , y2 ) ; lines [ 3 ] = new Line ( x1 , y2 , x1 , y1 ) ; float r2 = circle . getRadius ( ) * circle . getRadius ( ) ; Vector2f pos = new Vector2f ( circle . getCenterX ( ) , circle . getCenterY ( ) ) ; for ( int i = 0 ; i < 4 ; i ++ ) { float dis = lines [ i ] . distanceSquared ( pos ) ; if ( dis < r2 ) { return true ; } } return false ; }
Check if this circle touches a rectangle
38,025
private boolean intersects ( Line other ) { Vector2f lineSegmentStart = new Vector2f ( other . getX1 ( ) , other . getY1 ( ) ) ; Vector2f lineSegmentEnd = new Vector2f ( other . getX2 ( ) , other . getY2 ( ) ) ; Vector2f circleCenter = new Vector2f ( getCenterX ( ) , getCenterY ( ) ) ; Vector2f closest ; Vector2f segv = lineSegmentEnd . copy ( ) . sub ( lineSegmentStart ) ; Vector2f ptv = circleCenter . copy ( ) . sub ( lineSegmentStart ) ; float segvLength = segv . length ( ) ; float projvl = ptv . dot ( segv ) / segvLength ; if ( projvl < 0 ) { closest = lineSegmentStart ; } else if ( projvl > segvLength ) { closest = lineSegmentEnd ; } else { Vector2f projv = segv . copy ( ) . scale ( projvl / segvLength ) ; closest = lineSegmentStart . copy ( ) . add ( projv ) ; } boolean intersects = circleCenter . copy ( ) . sub ( closest ) . lengthSquared ( ) <= getRadius ( ) * getRadius ( ) ; return intersects ; }
Check if circle touches a line .
38,026
public static Audio getAudio ( String format , InputStream in ) throws IOException { init ( ) ; if ( format . equals ( AIF ) ) { return SoundStore . get ( ) . getAIF ( in ) ; } if ( format . equals ( WAV ) ) { return SoundStore . get ( ) . getWAV ( in ) ; } if ( format . equals ( OGG ) ) { return SoundStore . get ( ) . getOgg ( in ) ; } throw new IOException ( "Unsupported format for non-streaming Audio: " + format ) ; }
Get audio data in a playable state by loading the complete audio into memory .
38,027
public static Audio getStreamingAudio ( String format , URL url ) throws IOException { init ( ) ; if ( format . equals ( OGG ) ) { return SoundStore . get ( ) . getOggStream ( url ) ; } if ( format . equals ( MOD ) ) { return SoundStore . get ( ) . getMOD ( url . openStream ( ) ) ; } if ( format . equals ( XM ) ) { return SoundStore . get ( ) . getMOD ( url . openStream ( ) ) ; } throw new IOException ( "Unsupported format for streaming Audio: " + format ) ; }
Get audio data in a playable state by setting up a stream that can be piped into OpenAL - i . e . streaming audio
38,028
public static WaveData create ( AudioInputStream ais ) { AudioFormat audioformat = ais . getFormat ( ) ; int channels = 0 ; if ( audioformat . getChannels ( ) == 1 ) { if ( audioformat . getSampleSizeInBits ( ) == 8 ) { channels = AL10 . AL_FORMAT_MONO8 ; } else if ( audioformat . getSampleSizeInBits ( ) == 16 ) { channels = AL10 . AL_FORMAT_MONO16 ; } else { throw new RuntimeException ( "Illegal sample size" ) ; } } else if ( audioformat . getChannels ( ) == 2 ) { if ( audioformat . getSampleSizeInBits ( ) == 8 ) { channels = AL10 . AL_FORMAT_STEREO8 ; } else if ( audioformat . getSampleSizeInBits ( ) == 16 ) { channels = AL10 . AL_FORMAT_STEREO16 ; } else { throw new RuntimeException ( "Illegal sample size" ) ; } } else { throw new RuntimeException ( "Only mono or stereo is supported" ) ; } byte [ ] buf = new byte [ audioformat . getChannels ( ) * ( int ) ais . getFrameLength ( ) * audioformat . getSampleSizeInBits ( ) / 8 ] ; int read = 0 , total = 0 ; try { while ( ( read = ais . read ( buf , total , buf . length - total ) ) != - 1 && total < buf . length ) { total += read ; } } catch ( IOException ioe ) { return null ; } ByteBuffer buffer = convertAudioBytes ( buf , audioformat . getSampleSizeInBits ( ) == 16 ) ; WaveData wavedata = new WaveData ( buffer , channels , ( int ) audioformat . getSampleRate ( ) ) ; try { ais . close ( ) ; } catch ( IOException ioe ) { } return wavedata ; }
Creates a WaveData container from the specified stream
38,029
public static void defineMask ( ) { GL . glDepthMask ( true ) ; GL . glClearDepth ( 1 ) ; GL . glClear ( SGL . GL_DEPTH_BUFFER_BIT ) ; GL . glDepthFunc ( SGL . GL_ALWAYS ) ; GL . glEnable ( SGL . GL_DEPTH_TEST ) ; GL . glDepthMask ( true ) ; GL . glColorMask ( false , false , false , false ) ; }
Start defining the screen mask . After calling this use graphics functions to mask out the area
38,030
public static void finishDefineMask ( ) { GL . glDepthMask ( false ) ; GL . glColorMask ( true , true , true , true ) ; }
Finish defining the screen mask
38,031
public static void resetMask ( ) { GL . glDepthMask ( true ) ; GL . glClearDepth ( 0 ) ; GL . glClear ( SGL . GL_DEPTH_BUFFER_BIT ) ; GL . glDepthMask ( false ) ; GL . glDisable ( SGL . GL_DEPTH_TEST ) ; }
Reset the masked area - should be done after you ve finished rendering
38,032
private static Font createFont ( String ttfFileRef ) throws SlickException { try { return Font . createFont ( Font . TRUETYPE_FONT , ResourceLoader . getResourceAsStream ( ttfFileRef ) ) ; } catch ( FontFormatException ex ) { throw new SlickException ( "Invalid font: " + ttfFileRef , ex ) ; } catch ( IOException ex ) { throw new SlickException ( "Error reading font: " + ttfFileRef , ex ) ; } }
Utility to create a Java font for a TTF file reference
38,033
private void initializeFont ( Font baseFont , int size , boolean bold , boolean italic ) { Map attributes = baseFont . getAttributes ( ) ; attributes . put ( TextAttribute . SIZE , new Float ( size ) ) ; attributes . put ( TextAttribute . WEIGHT , bold ? TextAttribute . WEIGHT_BOLD : TextAttribute . WEIGHT_REGULAR ) ; attributes . put ( TextAttribute . POSTURE , italic ? TextAttribute . POSTURE_OBLIQUE : TextAttribute . POSTURE_REGULAR ) ; try { attributes . put ( TextAttribute . class . getDeclaredField ( "KERNING" ) . get ( null ) , TextAttribute . class . getDeclaredField ( "KERNING_ON" ) . get ( null ) ) ; } catch ( Exception ignored ) { } font = baseFont . deriveFont ( attributes ) ; FontMetrics metrics = GlyphPage . getScratchGraphics ( ) . getFontMetrics ( font ) ; ascent = metrics . getAscent ( ) ; descent = metrics . getDescent ( ) ; leading = metrics . getLeading ( ) ; char [ ] chars = " " . toCharArray ( ) ; GlyphVector vector = font . layoutGlyphVector ( GlyphPage . renderContext , chars , 0 , chars . length , Font . LAYOUT_LEFT_TO_RIGHT ) ; spaceWidth = vector . getGlyphLogicalBounds ( 0 ) . getBounds ( ) . width ; }
Initialise the font to be used based on configuration
38,034
private void loadSettings ( HieroSettings settings ) { paddingTop = settings . getPaddingTop ( ) ; paddingLeft = settings . getPaddingLeft ( ) ; paddingBottom = settings . getPaddingBottom ( ) ; paddingRight = settings . getPaddingRight ( ) ; paddingAdvanceX = settings . getPaddingAdvanceX ( ) ; paddingAdvanceY = settings . getPaddingAdvanceY ( ) ; glyphPageWidth = settings . getGlyphPageWidth ( ) ; glyphPageHeight = settings . getGlyphPageHeight ( ) ; effects . addAll ( settings . getEffects ( ) ) ; }
Load the hiero setting and configure the unicode font s rendering
38,035
public void addFigure ( Figure figure ) { figures . add ( figure ) ; figureMap . put ( figure . getData ( ) . getAttribute ( NonGeometricData . ID ) , figure ) ; String fillRef = figure . getData ( ) . getAsReference ( NonGeometricData . FILL ) ; Gradient gradient = getGradient ( fillRef ) ; if ( gradient != null ) { if ( gradient . isRadial ( ) ) { for ( int i = 0 ; i < InkscapeLoader . RADIAL_TRIANGULATION_LEVEL ; i ++ ) { figure . getShape ( ) . increaseTriangulation ( ) ; } } } }
Add a figure to the diagram
38,036
public void removeFigure ( Figure figure ) { figures . remove ( figure ) ; figureMap . remove ( figure . getData ( ) . getAttribute ( "id" ) ) ; }
Remove a figure from the diagram
38,037
public void resolve ( Diagram diagram ) { if ( ref == null ) { return ; } Gradient other = diagram . getGradient ( ref ) ; for ( int i = 0 ; i < other . steps . size ( ) ; i ++ ) { steps . add ( other . steps . get ( i ) ) ; } }
Resolve the gradient reference
38,038
public void genImage ( ) { if ( image == null ) { ImageBuffer buffer = new ImageBuffer ( 128 , 16 ) ; for ( int i = 0 ; i < 128 ; i ++ ) { Color col = getColorAt ( i / 128.0f ) ; for ( int j = 0 ; j < 16 ; j ++ ) { buffer . setRGBA ( i , j , col . getRedByte ( ) , col . getGreenByte ( ) , col . getBlueByte ( ) , col . getAlphaByte ( ) ) ; } } image = buffer . getImage ( ) ; } }
Generate the image used for texturing the gradient across shapes
38,039
public Color getColorAt ( float p ) { if ( p <= 0 ) { return ( ( Step ) steps . get ( 0 ) ) . col ; } if ( p > 1 ) { return ( ( Step ) steps . get ( steps . size ( ) - 1 ) ) . col ; } for ( int i = 1 ; i < steps . size ( ) ; i ++ ) { Step prev = ( ( Step ) steps . get ( i - 1 ) ) ; Step current = ( ( Step ) steps . get ( i ) ) ; if ( p <= current . location ) { float dis = current . location - prev . location ; p -= prev . location ; float v = p / dis ; Color c = new Color ( 1 , 1 , 1 , 1 ) ; c . a = ( prev . col . a * ( 1 - v ) ) + ( current . col . a * ( v ) ) ; c . r = ( prev . col . r * ( 1 - v ) ) + ( current . col . r * ( v ) ) ; c . g = ( prev . col . g * ( 1 - v ) ) + ( current . col . g * ( v ) ) ; c . b = ( prev . col . b * ( 1 - v ) ) + ( current . col . b * ( v ) ) ; return c ; } } return Color . black ; }
Get the intepolated colour at the given location on the gradient
38,040
public void setDisplayMode ( int width , int height , boolean fullscreen ) throws SlickException { if ( ( this . width == width ) && ( this . height == height ) && ( isFullscreen ( ) == fullscreen ) ) { return ; } try { targetDisplayMode = null ; if ( fullscreen ) { DisplayMode [ ] modes = Display . getAvailableDisplayModes ( ) ; int freq = 0 ; for ( int i = 0 ; i < modes . length ; i ++ ) { DisplayMode current = modes [ i ] ; if ( ( current . getWidth ( ) == width ) && ( current . getHeight ( ) == height ) ) { if ( ( targetDisplayMode == null ) || ( current . getFrequency ( ) >= freq ) ) { if ( ( targetDisplayMode == null ) || ( current . getBitsPerPixel ( ) > targetDisplayMode . getBitsPerPixel ( ) ) ) { targetDisplayMode = current ; freq = targetDisplayMode . getFrequency ( ) ; } } if ( ( current . getBitsPerPixel ( ) == originalDisplayMode . getBitsPerPixel ( ) ) && ( current . getFrequency ( ) == originalDisplayMode . getFrequency ( ) ) ) { targetDisplayMode = current ; break ; } } } } else { targetDisplayMode = new DisplayMode ( width , height ) ; } if ( targetDisplayMode == null ) { throw new SlickException ( "Failed to find value mode: " + width + "x" + height + " fs=" + fullscreen ) ; } this . width = width ; this . height = height ; Display . setDisplayMode ( targetDisplayMode ) ; Display . setFullscreen ( fullscreen ) ; if ( Display . isCreated ( ) ) { initGL ( ) ; enterOrtho ( ) ; } if ( targetDisplayMode . getBitsPerPixel ( ) == 16 ) { InternalTextureLoader . get ( ) . set16BitMode ( ) ; } } catch ( LWJGLException e ) { throw new SlickException ( "Unable to setup mode " + width + "x" + height + " fullscreen=" + fullscreen , e ) ; } getDelta ( ) ; }
Set the display mode to be used
38,041
public void setFullscreen ( boolean fullscreen ) throws SlickException { if ( isFullscreen ( ) == fullscreen ) { return ; } if ( ! fullscreen ) { try { Display . setFullscreen ( fullscreen ) ; } catch ( LWJGLException e ) { throw new SlickException ( "Unable to set fullscreen=" + fullscreen , e ) ; } } else { setDisplayMode ( width , height , fullscreen ) ; } getDelta ( ) ; }
Indicate whether we want to be in fullscreen mode . Note that the current display mode must be valid as a fullscreen mode for this to work
38,042
private void tryCreateDisplay ( PixelFormat format ) throws LWJGLException { if ( SHARED_DRAWABLE == null ) { Display . create ( format ) ; } else { Display . create ( format , SHARED_DRAWABLE ) ; } }
Try creating a display with the given format
38,043
public void start ( ) throws SlickException { try { setup ( ) ; getDelta ( ) ; while ( running ( ) ) { gameLoop ( ) ; } } finally { destroy ( ) ; } if ( forceExit ) { System . exit ( 0 ) ; } }
Start running the game
38,044
protected void setup ( ) throws SlickException { if ( targetDisplayMode == null ) { setDisplayMode ( 640 , 480 , false ) ; } Display . setTitle ( game . getTitle ( ) ) ; Log . info ( "LWJGL Version: " + Sys . getVersion ( ) ) ; Log . info ( "OriginalDisplayMode: " + originalDisplayMode ) ; Log . info ( "TargetDisplayMode: " + targetDisplayMode ) ; AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { try { PixelFormat format = new PixelFormat ( 8 , 8 , stencil ? 8 : 0 , samples ) ; tryCreateDisplay ( format ) ; supportsMultiSample = true ; } catch ( Exception e ) { Display . destroy ( ) ; try { PixelFormat format = new PixelFormat ( 8 , 8 , stencil ? 8 : 0 ) ; tryCreateDisplay ( format ) ; alphaSupport = false ; } catch ( Exception e2 ) { Display . destroy ( ) ; try { tryCreateDisplay ( new PixelFormat ( ) ) ; } catch ( Exception e3 ) { Log . error ( e3 ) ; } } } return null ; } } ) ; if ( ! Display . isCreated ( ) ) { throw new SlickException ( "Failed to initialise the LWJGL display" ) ; } initSystem ( ) ; enterOrtho ( ) ; try { getInput ( ) . initControllers ( ) ; } catch ( SlickException e ) { Log . info ( "Controllers not available" ) ; } catch ( Throwable e ) { Log . info ( "Controllers not available" ) ; } try { game . init ( this ) ; } catch ( SlickException e ) { Log . error ( e ) ; running = false ; } }
Setup the environment
38,045
protected void gameLoop ( ) throws SlickException { int delta = getDelta ( ) ; if ( ! Display . isVisible ( ) && updateOnlyOnVisible ) { try { Thread . sleep ( 100 ) ; } catch ( Exception e ) { } } else { try { updateAndRender ( delta ) ; } catch ( SlickException e ) { Log . error ( e ) ; running = false ; return ; } } updateFPS ( ) ; Display . update ( ) ; if ( Display . isCloseRequested ( ) ) { if ( game . closeRequested ( ) ) { running = false ; } } }
Strategy for overloading game loop context handling
38,046
static NonGeometricData getNonGeometricData ( Element element ) { String meta = getMetaData ( element ) ; NonGeometricData data = new InkscapeNonGeometricData ( meta , element ) ; data . addAttribute ( NonGeometricData . ID , element . getAttribute ( "id" ) ) ; data . addAttribute ( NonGeometricData . FILL , getStyle ( element , NonGeometricData . FILL ) ) ; data . addAttribute ( NonGeometricData . STROKE , getStyle ( element , NonGeometricData . STROKE ) ) ; data . addAttribute ( NonGeometricData . OPACITY , getStyle ( element , NonGeometricData . OPACITY ) ) ; data . addAttribute ( NonGeometricData . STROKE_DASHARRAY , getStyle ( element , NonGeometricData . STROKE_DASHARRAY ) ) ; data . addAttribute ( NonGeometricData . STROKE_DASHOFFSET , getStyle ( element , NonGeometricData . STROKE_DASHOFFSET ) ) ; data . addAttribute ( NonGeometricData . STROKE_MITERLIMIT , getStyle ( element , NonGeometricData . STROKE_MITERLIMIT ) ) ; data . addAttribute ( NonGeometricData . STROKE_OPACITY , getStyle ( element , NonGeometricData . STROKE_OPACITY ) ) ; data . addAttribute ( NonGeometricData . STROKE_WIDTH , getStyle ( element , NonGeometricData . STROKE_WIDTH ) ) ; return data ; }
Get the non - geometric data information from an XML element
38,047
static String getMetaData ( Element element ) { String label = element . getAttributeNS ( INKSCAPE , "label" ) ; if ( ( label != null ) && ( ! label . equals ( "" ) ) ) { return label ; } return element . getAttribute ( "id" ) ; }
Get the meta data store within an element either in the label or id atributes
38,048
static String extractStyle ( String style , String attribute ) { if ( style == null ) { return "" ; } StringTokenizer tokens = new StringTokenizer ( style , ";" ) ; while ( tokens . hasMoreTokens ( ) ) { String token = tokens . nextToken ( ) ; String key = token . substring ( 0 , token . indexOf ( ':' ) ) ; if ( key . equals ( attribute ) ) { return token . substring ( token . indexOf ( ':' ) + 1 ) ; } } return "" ; }
Extract the style value from a Inkscape encoded string
38,049
static Transform getTransform ( Element element , String attribute ) { String str = element . getAttribute ( attribute ) ; if ( str == null ) { return new Transform ( ) ; } if ( str . equals ( "" ) ) { return new Transform ( ) ; } else if ( str . startsWith ( "translate" ) ) { str = str . substring ( 0 , str . length ( ) - 1 ) ; str = str . substring ( "translate(" . length ( ) ) ; StringTokenizer tokens = new StringTokenizer ( str , ", " ) ; float x = Float . parseFloat ( tokens . nextToken ( ) ) ; float y = Float . parseFloat ( tokens . nextToken ( ) ) ; return Transform . createTranslateTransform ( x , y ) ; } else if ( str . startsWith ( "matrix" ) ) { float [ ] pose = new float [ 6 ] ; str = str . substring ( 0 , str . length ( ) - 1 ) ; str = str . substring ( "matrix(" . length ( ) ) ; StringTokenizer tokens = new StringTokenizer ( str , ", " ) ; float [ ] tr = new float [ 6 ] ; for ( int j = 0 ; j < tr . length ; j ++ ) { tr [ j ] = Float . parseFloat ( tokens . nextToken ( ) ) ; } pose [ 0 ] = tr [ 0 ] ; pose [ 1 ] = tr [ 2 ] ; pose [ 2 ] = tr [ 4 ] ; pose [ 3 ] = tr [ 1 ] ; pose [ 4 ] = tr [ 3 ] ; pose [ 5 ] = tr [ 5 ] ; return new Transform ( pose ) ; } return new Transform ( ) ; }
Get a transform defined in the XML
38,050
static float getFloatAttribute ( Element element , String attr ) throws ParsingException { String cx = element . getAttribute ( attr ) ; if ( ( cx == null ) || ( cx . equals ( "" ) ) ) { cx = element . getAttributeNS ( SODIPODI , attr ) ; } try { return Float . parseFloat ( cx ) ; } catch ( NumberFormatException e ) { throw new ParsingException ( element , "Invalid value for: " + attr , e ) ; } }
Get a floating point attribute that may appear in either the default or SODIPODI namespace
38,051
public static boolean validFill ( Shape shape ) { if ( shape . getTriangles ( ) == null ) { return false ; } return shape . getTriangles ( ) . getTriangleCount ( ) != 0 ; }
Check there are enough points to fill
38,052
public static final void textureFit ( Shape shape , final Image image , final float scaleX , final float scaleY ) { if ( ! validFill ( shape ) ) { return ; } float points [ ] = shape . getPoints ( ) ; Texture t = TextureImpl . getLastBind ( ) ; image . getTexture ( ) . bind ( ) ; final float minX = shape . getX ( ) ; final float minY = shape . getY ( ) ; final float maxX = shape . getMaxX ( ) - minX ; final float maxY = shape . getMaxY ( ) - minY ; fill ( shape , new PointCallback ( ) { public float [ ] preRenderPoint ( Shape shape , float x , float y ) { x -= shape . getMinX ( ) ; y -= shape . getMinY ( ) ; x /= ( shape . getMaxX ( ) - shape . getMinX ( ) ) ; y /= ( shape . getMaxY ( ) - shape . getMinY ( ) ) ; float tx = x * scaleX ; float ty = y * scaleY ; tx = image . getTextureOffsetX ( ) + ( image . getTextureWidth ( ) * tx ) ; ty = image . getTextureOffsetY ( ) + ( image . getTextureHeight ( ) * ty ) ; GL . glTexCoord2f ( tx , ty ) ; return null ; } } ) ; if ( t == null ) { TextureImpl . bindNone ( ) ; } else { t . bind ( ) ; } }
Draw the the given shape filled in with a texture . Only the vertices are set . The colour has to be set independently of this method . This method is required to fit the texture scaleX times across the shape and scaleY times down the shape .
38,053
public int playAsSoundEffect ( float pitch , float gain , boolean loop , float x , float y , float z ) { checkTarget ( ) ; return target . playAsSoundEffect ( pitch , gain , loop , x , y , z ) ; }
Play this sound as a sound effect
38,054
public void set ( Vector2f start , Vector2f end ) { super . pointsDirty = true ; if ( this . start == null ) { this . start = new Vector2f ( ) ; } this . start . set ( start ) ; if ( this . end == null ) { this . end = new Vector2f ( ) ; } this . end . set ( end ) ; vec = new Vector2f ( end ) ; vec . sub ( start ) ; lenSquared = vec . lengthSquared ( ) ; }
Configure the line
38,055
public void set ( float sx , float sy , float ex , float ey ) { super . pointsDirty = true ; start . set ( sx , sy ) ; end . set ( ex , ey ) ; float dx = ( ex - sx ) ; float dy = ( ey - sy ) ; vec . set ( dx , dy ) ; lenSquared = ( dx * dx ) + ( dy * dy ) ; }
Configure the line without garbage
38,056
public float distanceSquared ( Vector2f point ) { getClosestPoint ( point , closest ) ; closest . sub ( point ) ; float result = closest . lengthSquared ( ) ; return result ; }
Get the shortest distance squared from a point to this line
38,057
public void getClosestPoint ( Vector2f point , Vector2f result ) { loc . set ( point ) ; loc . sub ( start ) ; float projDistance = vec . dot ( loc ) ; projDistance /= vec . lengthSquared ( ) ; if ( projDistance < 0 ) { result . set ( start ) ; return ; } if ( projDistance > 1 ) { result . set ( end ) ; return ; } result . x = start . getX ( ) + projDistance * vec . getX ( ) ; result . y = start . getY ( ) + projDistance * vec . getY ( ) ; }
Get the closest point on the line to a given point
38,058
private void init ( InputStream in ) throws java . io . IOException { if ( in . available ( ) > 2000000 ) { throw new IOException ( "Font too big" ) ; } this . file = IOUtils . toByteArray ( in ) ; this . fsize = this . file . length ; if ( fsize > 2000000 ) { throw new IOException ( "Font too big" ) ; } this . current = 0 ; }
Initializes class and reads stream . Init does not close stream .
38,059
public void seekSet ( long offset ) throws IOException { if ( offset >= fsize || offset < 0 ) { throw new java . io . EOFException ( "Reached EOF, file size=" + fsize + " offset=" + offset ) ; } current = ( int ) offset ; }
Set current file position to offset
38,060
public byte read ( ) throws IOException { if ( current >= fsize ) { throw new java . io . EOFException ( "Reached EOF, file size=" + fsize ) ; } final byte ret = file [ current ++ ] ; return ret ; }
Read 1 byte .
38,061
public final void writeTTFUShort ( int pos , int val ) throws IOException { if ( ( pos + 2 ) > fsize ) { throw new java . io . EOFException ( "Reached EOF" ) ; } final byte b1 = ( byte ) ( ( val >> 8 ) & 0xff ) ; final byte b2 = ( byte ) ( val & 0xff ) ; file [ pos ] = b1 ; file [ pos + 1 ] = b2 ; }
Write a USHort at a given position .
38,062
public final short readTTFShort ( long pos ) throws IOException { final long cp = getCurrentPos ( ) ; seekSet ( pos ) ; final short ret = readTTFShort ( ) ; seekSet ( cp ) ; return ret ; }
Read 2 bytes signed at position pos without changing current position .
38,063
public final int readTTFUShort ( long pos ) throws IOException { long cp = getCurrentPos ( ) ; seekSet ( pos ) ; int ret = readTTFUShort ( ) ; seekSet ( cp ) ; return ret ; }
Read 2 bytes unsigned at position pos without changing current position .
38,064
public final String readTTFString ( ) throws IOException { int i = current ; while ( file [ i ++ ] != 0 ) { if ( i > fsize ) { throw new java . io . EOFException ( "Reached EOF, file size=" + fsize ) ; } } byte [ ] tmp = new byte [ i - current ] ; System . arraycopy ( file , current , tmp , 0 , i - current ) ; return new String ( tmp , "ISO-8859-1" ) ; }
Read a NUL terminated ISO - 8859 - 1 string .
38,065
public final String readTTFString ( int len ) throws IOException { if ( ( len + current ) > fsize ) { throw new java . io . EOFException ( "Reached EOF, file size=" + fsize ) ; } byte [ ] tmp = new byte [ len ] ; System . arraycopy ( file , current , tmp , 0 , len ) ; current += len ; final String encoding ; if ( ( tmp . length > 0 ) && ( tmp [ 0 ] == 0 ) ) { encoding = "UTF-16BE" ; } else { encoding = "ISO-8859-1" ; } return new String ( tmp , encoding ) ; }
Read an ISO - 8859 - 1 string of len bytes .
38,066
public byte [ ] getBytes ( int offset , int length ) throws IOException { if ( ( offset + length ) > fsize ) { throw new java . io . IOException ( "Reached EOF" ) ; } byte [ ] ret = new byte [ length ] ; System . arraycopy ( file , offset , ret , 0 , length ) ; return ret ; }
Return a copy of the internal array
38,067
private BufferedImage getFontImage ( char ch ) { BufferedImage tempfontImage = new BufferedImage ( 1 , 1 , BufferedImage . TYPE_INT_ARGB ) ; Graphics2D g = ( Graphics2D ) tempfontImage . getGraphics ( ) ; if ( antiAlias == true ) { g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; } g . setFont ( font ) ; fontMetrics = g . getFontMetrics ( ) ; int charwidth = fontMetrics . charWidth ( ch ) ; if ( charwidth <= 0 ) { charwidth = 1 ; } int charheight = fontMetrics . getHeight ( ) ; if ( charheight <= 0 ) { charheight = fontSize ; } BufferedImage fontImage ; fontImage = new BufferedImage ( charwidth , charheight , BufferedImage . TYPE_INT_ARGB ) ; Graphics2D gt = ( Graphics2D ) fontImage . getGraphics ( ) ; if ( antiAlias == true ) { gt . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; } gt . setFont ( font ) ; gt . setColor ( Color . WHITE ) ; int charx = 0 ; int chary = 0 ; gt . drawString ( String . valueOf ( ch ) , ( charx ) , ( chary ) + fontMetrics . getAscent ( ) ) ; return fontImage ; }
Create a standard Java2D BufferedImage of the given character
38,068
private void createSet ( char [ ] customCharsArray ) { if ( customCharsArray != null && customCharsArray . length > 0 ) { textureWidth *= 2 ; } try { BufferedImage imgTemp = new BufferedImage ( textureWidth , textureHeight , BufferedImage . TYPE_INT_ARGB ) ; Graphics2D g = ( Graphics2D ) imgTemp . getGraphics ( ) ; g . setColor ( new Color ( 255 , 255 , 255 , 1 ) ) ; g . fillRect ( 0 , 0 , textureWidth , textureHeight ) ; int rowHeight = 0 ; int positionX = 0 ; int positionY = 0 ; int customCharsLength = ( customCharsArray != null ) ? customCharsArray . length : 0 ; for ( int i = 0 ; i < 256 + customCharsLength ; i ++ ) { char ch = ( i < 256 ) ? ( char ) i : customCharsArray [ i - 256 ] ; BufferedImage fontImage = getFontImage ( ch ) ; IntObject newIntObject = new IntObject ( ) ; newIntObject . width = fontImage . getWidth ( ) ; newIntObject . height = fontImage . getHeight ( ) ; if ( positionX + newIntObject . width >= textureWidth ) { positionX = 0 ; positionY += rowHeight ; rowHeight = 0 ; } newIntObject . storedX = positionX ; newIntObject . storedY = positionY ; if ( newIntObject . height > fontHeight ) { fontHeight = newIntObject . height ; } if ( newIntObject . height > rowHeight ) { rowHeight = newIntObject . height ; } g . drawImage ( fontImage , positionX , positionY , null ) ; positionX += newIntObject . width ; if ( i < 256 ) { charArray [ i ] = newIntObject ; } else { customChars . put ( new Character ( ch ) , newIntObject ) ; } fontImage = null ; } fontTexture = BufferedImageUtil . getTexture ( font . toString ( ) , imgTemp ) ; } catch ( IOException e ) { System . err . println ( "Failed to create font." ) ; e . printStackTrace ( ) ; } }
Create and store the font
38,069
public int getWidth ( String whatchars ) { int totalwidth = 0 ; IntObject intObject = null ; int currentChar = 0 ; for ( int i = 0 ; i < whatchars . length ( ) ; i ++ ) { currentChar = whatchars . charAt ( i ) ; if ( currentChar < 256 ) { intObject = charArray [ currentChar ] ; } else { intObject = ( IntObject ) customChars . get ( new Character ( ( char ) currentChar ) ) ; } if ( intObject != null ) totalwidth += intObject . width ; } return totalwidth ; }
Get the width of a given String
38,070
public Cursor getCursor ( String ref , int x , int y ) throws IOException , LWJGLException { LoadableImageData imageData = null ; imageData = ImageDataFactory . getImageDataFor ( ref ) ; imageData . configureEdging ( false ) ; ByteBuffer buf = imageData . loadImage ( ResourceLoader . getResourceAsStream ( ref ) , true , true , null ) ; for ( int i = 0 ; i < buf . limit ( ) ; i += 4 ) { byte red = buf . get ( i ) ; byte green = buf . get ( i + 1 ) ; byte blue = buf . get ( i + 2 ) ; byte alpha = buf . get ( i + 3 ) ; buf . put ( i + 2 , red ) ; buf . put ( i + 1 , green ) ; buf . put ( i , blue ) ; buf . put ( i + 3 , alpha ) ; } try { int yspot = imageData . getHeight ( ) - y - 1 ; if ( yspot < 0 ) { yspot = 0 ; } return new Cursor ( imageData . getTexWidth ( ) , imageData . getTexHeight ( ) , x , yspot , 1 , buf . asIntBuffer ( ) , null ) ; } catch ( Throwable e ) { Log . info ( "Chances are you cursor is too small for this platform" ) ; throw new LWJGLException ( e ) ; } }
Get a cursor based on a image reference on the classpath
38,071
private int getSourcePixel ( int x , int y ) { x = Math . max ( 0 , x ) ; x = Math . min ( width - 1 , x ) ; y = Math . max ( 0 , y ) ; y = Math . min ( height - 1 , y ) ; return srcImage [ x + ( y * width ) ] ; }
Get a pixel from the source image . This handles bonds checks and resolves to edge pixels
38,072
public int [ ] getScaledData ( ) { for ( int x = 0 ; x < width ; x ++ ) { for ( int y = 0 ; y < height ; y ++ ) { process ( x , y ) ; } } return dstImage ; }
Get the scale image data . Note this is the method that does the work so it might take some time to process .
38,073
private void updateRender ( ) { if ( inherit . isSelected ( ) ) { emitter . usePoints = Particle . INHERIT_POINTS ; oriented . setEnabled ( true ) ; } if ( quads . isSelected ( ) ) { emitter . usePoints = Particle . USE_QUADS ; oriented . setEnabled ( true ) ; } if ( points . isSelected ( ) ) { emitter . usePoints = Particle . USE_POINTS ; oriented . setEnabled ( false ) ; oriented . setSelected ( false ) ; } if ( oriented . isSelected ( ) ) emitter . useOriented = true ; else emitter . useOriented = false ; if ( additive . isSelected ( ) ) emitter . useAdditive = true ; else emitter . useAdditive = false ; }
Update the render setting
38,074
private void updateColors ( ) { if ( blockUpdates ) { return ; } emitter . colors . clear ( ) ; for ( int i = 0 ; i < grad . getControlPointCount ( ) ; i ++ ) { float pos = grad . getPointPos ( i ) ; java . awt . Color col = grad . getColor ( i ) ; Color slick = new Color ( col . getRed ( ) / 255.0f , col . getGreen ( ) / 255.0f , col . getBlue ( ) / 255.0f , 1.0f ) ; emitter . addColorPoint ( pos , slick ) ; } }
Update the state of the emitter based on colours in the editor
38,075
private void completeCheck ( ) throws SlickException { int framebuffer = EXTFramebufferObject . glCheckFramebufferStatusEXT ( EXTFramebufferObject . GL_FRAMEBUFFER_EXT ) ; switch ( framebuffer ) { case EXTFramebufferObject . GL_FRAMEBUFFER_COMPLETE_EXT : break ; case EXTFramebufferObject . GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT : throw new SlickException ( "FrameBuffer: " + FBO + ", has caused a GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT exception" ) ; case EXTFramebufferObject . GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT : throw new SlickException ( "FrameBuffer: " + FBO + ", has caused a GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT exception" ) ; case EXTFramebufferObject . GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT : throw new SlickException ( "FrameBuffer: " + FBO + ", has caused a GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT exception" ) ; case EXTFramebufferObject . GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT : throw new SlickException ( "FrameBuffer: " + FBO + ", has caused a GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT exception" ) ; case EXTFramebufferObject . GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT : throw new SlickException ( "FrameBuffer: " + FBO + ", has caused a GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT exception" ) ; case EXTFramebufferObject . GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT : throw new SlickException ( "FrameBuffer: " + FBO + ", has caused a GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT exception" ) ; default : throw new SlickException ( "Unexpected reply from glCheckFramebufferStatusEXT: " + framebuffer ) ; } }
Check the FBO for completeness as shown in the LWJGL tutorial
38,076
private void init ( ) throws SlickException { IntBuffer buffer = BufferUtils . createIntBuffer ( 1 ) ; EXTFramebufferObject . glGenFramebuffersEXT ( buffer ) ; FBO = buffer . get ( ) ; try { Texture tex = InternalTextureLoader . get ( ) . createTexture ( image . getWidth ( ) , image . getHeight ( ) , image . getFilter ( ) ) ; EXTFramebufferObject . glBindFramebufferEXT ( EXTFramebufferObject . GL_FRAMEBUFFER_EXT , FBO ) ; EXTFramebufferObject . glFramebufferTexture2DEXT ( EXTFramebufferObject . GL_FRAMEBUFFER_EXT , EXTFramebufferObject . GL_COLOR_ATTACHMENT0_EXT , GL11 . GL_TEXTURE_2D , tex . getTextureID ( ) , 0 ) ; completeCheck ( ) ; unbind ( ) ; clear ( ) ; flush ( ) ; drawImage ( image , 0 , 0 ) ; image . setTexture ( tex ) ; } catch ( Exception e ) { throw new SlickException ( "Failed to create new texture for FBO" ) ; } }
Initialise the FBO that will be used to render to
38,077
private void bind ( ) { EXTFramebufferObject . glBindFramebufferEXT ( EXTFramebufferObject . GL_FRAMEBUFFER_EXT , FBO ) ; GL11 . glReadBuffer ( EXTFramebufferObject . GL_COLOR_ATTACHMENT0_EXT ) ; }
Bind to the FBO created
38,078
protected void enterOrtho ( ) { GL11 . glMatrixMode ( GL11 . GL_PROJECTION ) ; GL11 . glLoadIdentity ( ) ; GL11 . glOrtho ( 0 , screenWidth , 0 , screenHeight , 1 , - 1 ) ; GL11 . glMatrixMode ( GL11 . GL_MODELVIEW ) ; }
Enter the orthographic mode
38,079
public void error ( Throwable e ) { out . println ( new Date ( ) + " ERROR:" + e . getMessage ( ) ) ; e . printStackTrace ( out ) ; }
Log an error
38,080
public void warn ( String message , Throwable e ) { warn ( message ) ; e . printStackTrace ( out ) ; }
Log a warning with an exception that caused it
38,081
private static void init ( ) throws SlickException { init = true ; if ( fbo ) { fbo = GLContext . getCapabilities ( ) . GL_EXT_framebuffer_object ; } pbuffer = ( Pbuffer . getCapabilities ( ) & Pbuffer . PBUFFER_SUPPORTED ) != 0 ; pbufferRT = ( Pbuffer . getCapabilities ( ) & Pbuffer . RENDER_TEXTURE_SUPPORTED ) != 0 ; if ( ! fbo && ! pbuffer && ! pbufferRT ) { throw new SlickException ( "Your OpenGL card does not support offscreen buffers and hence can't handle the dynamic images required for this application." ) ; } Log . info ( "Offscreen Buffers FBO=" + fbo + " PBUFFER=" + pbuffer + " PBUFFERRT=" + pbufferRT ) ; }
Initialise offscreen rendering by checking what buffers are supported by the card
38,082
public static Graphics getGraphicsForImage ( Image image ) throws SlickException { Graphics g = ( Graphics ) graphics . get ( image . getTexture ( ) ) ; if ( g == null ) { g = createGraphics ( image ) ; graphics . put ( image . getTexture ( ) , g ) ; } return g ; }
Get a graphics context for a particular image
38,083
public static void releaseGraphicsForImage ( Image image ) throws SlickException { Graphics g = ( Graphics ) graphics . remove ( image . getTexture ( ) ) ; if ( g != null ) { g . destroy ( ) ; } }
Release any graphics context that is assocaited with the given image
38,084
private static Graphics createGraphics ( Image image ) throws SlickException { init ( ) ; if ( fbo ) { try { return new FBOGraphics ( image ) ; } catch ( Exception e ) { fbo = false ; Log . warn ( "FBO failed in use, falling back to PBuffer" ) ; } } if ( pbuffer ) { if ( pbufferRT ) { return new PBufferGraphics ( image ) ; } else { return new PBufferUniqueGraphics ( image ) ; } } throw new SlickException ( "Failed to create offscreen buffer even though the card reports it's possible" ) ; }
Create an underlying graphics context for the given image
38,085
protected boolean isValidLocation ( Mover mover , int sx , int sy , int x , int y ) { boolean invalid = ( x < 0 ) || ( y < 0 ) || ( x >= map . getWidthInTiles ( ) ) || ( y >= map . getHeightInTiles ( ) ) ; if ( ( ! invalid ) && ( ( sx != x ) || ( sy != y ) ) ) { this . mover = mover ; this . sourceX = sx ; this . sourceY = sy ; invalid = map . blocked ( this , x , y ) ; } return ! invalid ; }
Check if a given location is valid for the supplied mover
38,086
public float getMovementCost ( Mover mover , int sx , int sy , int tx , int ty ) { this . mover = mover ; this . sourceX = sx ; this . sourceY = sy ; return map . getCost ( this , tx , ty ) ; }
Get the cost to move through a given location
38,087
public Color darker ( float scale ) { scale = 1 - scale ; Color temp = new Color ( r * scale , g * scale , b * scale , a ) ; return temp ; }
Make a darker instance of this colour
38,088
public Color brighter ( float scale ) { scale += 1 ; Color temp = new Color ( r * scale , g * scale , b * scale , a ) ; return temp ; }
Make a brighter instance of this colour
38,089
public Color multiply ( Color c ) { return new Color ( r * c . r , g * c . g , b * c . b , a * c . a ) ; }
Multiply this color by another
38,090
protected void notifyListeners ( ) { Iterator it = listeners . iterator ( ) ; while ( it . hasNext ( ) ) { ( ( ComponentListener ) it . next ( ) ) . componentActivated ( this ) ; } }
Notify all the listeners .
38,091
public void setFocus ( boolean focus ) { if ( focus ) { if ( currentFocus != null ) { currentFocus . setFocus ( false ) ; } currentFocus = this ; } else { if ( currentFocus == this ) { currentFocus = null ; } } this . focus = focus ; }
Indicate whether this component should be focused or not
38,092
public void mouseReleased ( int button , int x , int y ) { setFocus ( Rectangle . contains ( x , y , getX ( ) , getY ( ) , getWidth ( ) , getHeight ( ) ) ) ; }
Gives the focus to this component with a click of the mouse .
38,093
public void setMusicOn ( boolean music ) { if ( soundWorks ) { this . music = music ; if ( music ) { restartLoop ( ) ; setMusicVolume ( musicVolume ) ; } else { pauseLoop ( ) ; } } }
Inidicate whether music should be playing
38,094
public void setCurrentMusicVolume ( float volume ) { if ( volume < 0 ) { volume = 0 ; } if ( volume > 1 ) { volume = 1 ; } if ( soundWorks ) { lastCurrentMusicVolume = volume ; AL10 . alSourcef ( sources . get ( 0 ) , AL10 . AL_GAIN , lastCurrentMusicVolume * musicVolume ) ; } }
Set the music volume of the current playing music . Does NOT affect the global volume
38,095
public void init ( ) { if ( inited ) { return ; } Log . info ( "Initialising sounds.." ) ; inited = true ; AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { try { AL . create ( ) ; soundWorks = true ; sounds = true ; music = true ; Log . info ( "- Sound works" ) ; } catch ( Exception e ) { Log . error ( "Sound initialisation failure." ) ; Log . error ( e ) ; soundWorks = false ; sounds = false ; music = false ; } return null ; } } ) ; if ( soundWorks ) { sourceCount = 0 ; sources = BufferUtils . createIntBuffer ( maxSources ) ; while ( AL10 . alGetError ( ) == AL10 . AL_NO_ERROR ) { IntBuffer temp = BufferUtils . createIntBuffer ( 1 ) ; try { AL10 . alGenSources ( temp ) ; if ( AL10 . alGetError ( ) == AL10 . AL_NO_ERROR ) { sourceCount ++ ; sources . put ( temp . get ( 0 ) ) ; if ( sourceCount > maxSources - 1 ) { break ; } } } catch ( OpenALException e ) { break ; } } Log . info ( "- " + sourceCount + " OpenAL source available" ) ; if ( AL10 . alGetError ( ) != AL10 . AL_NO_ERROR ) { sounds = false ; music = false ; soundWorks = false ; Log . error ( "- AL init failed" ) ; } else { FloatBuffer listenerOri = BufferUtils . createFloatBuffer ( 6 ) . put ( new float [ ] { 0.0f , 0.0f , - 1.0f , 0.0f , 1.0f , 0.0f } ) ; FloatBuffer listenerVel = BufferUtils . createFloatBuffer ( 3 ) . put ( new float [ ] { 0.0f , 0.0f , 0.0f } ) ; FloatBuffer listenerPos = BufferUtils . createFloatBuffer ( 3 ) . put ( new float [ ] { 0.0f , 0.0f , 0.0f } ) ; listenerPos . flip ( ) ; listenerVel . flip ( ) ; listenerOri . flip ( ) ; AL10 . alListener ( AL10 . AL_POSITION , listenerPos ) ; AL10 . alListener ( AL10 . AL_VELOCITY , listenerVel ) ; AL10 . alListener ( AL10 . AL_ORIENTATION , listenerOri ) ; Log . info ( "- Sounds source generated" ) ; } } }
Initialise the sound effects stored . This must be called before anything else will work
38,096
boolean isPlaying ( int index ) { int state = AL10 . alGetSourcei ( sources . get ( index ) , AL10 . AL_SOURCE_STATE ) ; return ( state == AL10 . AL_PLAYING ) ; }
Check if a particular source is playing
38,097
private int findFreeSource ( ) { for ( int i = 1 ; i < sourceCount - 1 ; i ++ ) { int state = AL10 . alGetSourcei ( sources . get ( i ) , AL10 . AL_SOURCE_STATE ) ; if ( ( state != AL10 . AL_PLAYING ) && ( state != AL10 . AL_PAUSED ) ) { return i ; } } return - 1 ; }
Find a free sound source
38,098
public void setMusicPitch ( float pitch ) { if ( soundWorks ) { AL10 . alSourcef ( sources . get ( 0 ) , AL10 . AL_PITCH , pitch ) ; } }
Set the pitch at which the current music is being played
38,099
public Audio getWAV ( String ref ) throws IOException { return getWAV ( ref , ResourceLoader . getResourceAsStream ( ref ) ) ; }
Get the Sound based on a specified WAV file