code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Leptonica constants. * * @author alanv@google.com (Alan Viverette) */ public class Constants { /*-------------------------------------------------------------------------* * Access and storage flags * *-------------------------------------------------------------------------*/ /* * For Pix, Box, Pta and Numa, there are 3 standard methods for handling the * retrieval or insertion of a struct: (1) direct insertion (Don't do this * if there is another handle somewhere to this same struct!) (2) copy * (Always safe, sets up a refcount of 1 on the new object. Can be * undesirable if very large, such as an image or an array of images.) (3) * clone (Makes another handle to the same struct, and bumps the refcount up * by 1. Safe to do unless you're changing data through one of the handles * but don't want those changes to be seen by the other handle.) For Pixa * and Boxa, which are structs that hold an array of clonable structs, there * is an additional method: (4) copy-clone (Makes a new higher-level struct * with a refcount of 1, but clones all the structs in the array.) Unlike * the other structs, when retrieving a string from an Sarray, you are * allowed to get a handle without a copy or clone (i.e., that you don't * own!). You must not free or insert such a string! Specifically, for an * Sarray, the copyflag for retrieval is either: TRUE (or 1 or L_COPY) or * FALSE (or 0 or L_NOCOPY) For insertion, the copyflag is either: TRUE (or * 1 or L_COPY) or FALSE (or 0 or L_INSERT) Note that L_COPY is always 1, * and L_INSERT and L_NOCOPY are always 0. */ /* Stuff it in; no copy, clone or copy-clone */ public static final int L_INSERT = 0; /* Make/use a copy of the object */ public static final int L_COPY = 1; /* Make/use clone (ref count) of the object */ public static final int L_CLONE = 2; /* * Make a new object and fill with with clones of each object in the * array(s) */ public static final int L_COPY_CLONE = 3; /*--------------------------------------------------------------------------* * Sort flags * *--------------------------------------------------------------------------*/ /* Sort in increasing order */ public static final int L_SORT_INCREASING = 1; /* Sort in decreasing order */ public static final int L_SORT_DECREASING = 2; /* Sort box or c.c. by horiz location */ public static final int L_SORT_BY_X = 3; /* Sort box or c.c. by vert location */ public static final int L_SORT_BY_Y = 4; /* Sort box or c.c. by width */ public static final int L_SORT_BY_WIDTH = 5; /* Sort box or c.c. by height */ public static final int L_SORT_BY_HEIGHT = 6; /* Sort box or c.c. by min dimension */ public static final int L_SORT_BY_MIN_DIMENSION = 7; /* Sort box or c.c. by max dimension */ public static final int L_SORT_BY_MAX_DIMENSION = 8; /* Sort box or c.c. by perimeter */ public static final int L_SORT_BY_PERIMETER = 9; /* Sort box or c.c. by area */ public static final int L_SORT_BY_AREA = 10; /* Sort box or c.c. by width/height ratio */ public static final int L_SORT_BY_ASPECT_RATIO = 11; /* ------------------ Image file format types -------------- */ /* * The IFF_DEFAULT flag is used to write the file out in the same (input) * file format that the pix was read from. If the pix was not read from * file, the input format field will be IFF_UNKNOWN and the output file * format will be chosen to be compressed and lossless; namely, IFF_TIFF_G4 * for d = 1 and IFF_PNG for everything else. IFF_JP2 is for jpeg2000, which * is not supported in leptonica. */ public static final int IFF_UNKNOWN = 0; public static final int IFF_BMP = 1; public static final int IFF_JFIF_JPEG = 2; public static final int IFF_PNG = 3; public static final int IFF_TIFF = 4; public static final int IFF_TIFF_PACKBITS = 5; public static final int IFF_TIFF_RLE = 6; public static final int IFF_TIFF_G3 = 7; public static final int IFF_TIFF_G4 = 8; public static final int IFF_TIFF_LZW = 9; public static final int IFF_TIFF_ZIP = 10; public static final int IFF_PNM = 11; public static final int IFF_PS = 12; public static final int IFF_GIF = 13; public static final int IFF_JP2 = 14; public static final int IFF_DEFAULT = 15; public static final int IFF_SPIX = 16; }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * JPEG input and output methods. * * @author alanv@google.com (Alan Viverette) */ public class JpegIO { static { System.loadLibrary("lept"); } /** Default quality is 85%, which is reasonably good. */ public static final int DEFAULT_QUALITY = 85; /** Progressive encoding is disabled by default to increase compatibility. */ public static final boolean DEFAULT_PROGRESSIVE = false; /** * Returns a compressed JPEG byte representation of this Pix using default * parameters. * * @param pixs * @return a compressed JPEG byte array representation of the Pix */ public static byte[] compressToJpeg(Pix pixs) { return compressToJpeg(pixs, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE); } /** * Returns a compressed JPEG byte representation of this Pix. * * @param pixs A source pix image. * @param quality The quality of the compressed image. Valid range is 0-100. * @param progressive Whether to use progressive compression. * @return a compressed JPEG byte array representation of the Pix */ public static byte[] compressToJpeg(Pix pixs, int quality, boolean progressive) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (quality < 0 || quality > 100) throw new IllegalArgumentException("Quality must be between 0 and 100 (inclusive)"); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); final Bitmap bmp = WriteFile.writeBitmap(pixs); bmp.compress(CompressFormat.JPEG, quality, byteStream); bmp.recycle(); final byte[] encodedData = byteStream.toByteArray(); try { byteStream.close(); } catch (IOException e) { e.printStackTrace(); } return encodedData; } // *************** // * NATIVE CODE * // *************** private static native byte[] nativeCompressToJpeg( int nativePix, int quality, boolean progressive); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * @author alanv@google.com (Alan Viverette) */ public class Rotate { static { System.loadLibrary("lept"); } // Rotation default /** Default rotation quality is high. */ public static final boolean ROTATE_QUALITY = true; /** * Performs rotation using the default parameters. * * @param pixs The source pix. * @param degrees The number of degrees to rotate; clockwise is positive. * @return the rotated source image */ public static Pix rotate(Pix pixs, float degrees) { return rotate(pixs, degrees, false); } /** * Performs rotation with resizing using the default parameters. * * @param pixs The source pix. * @param degrees The number of degrees to rotate; clockwise is positive. * @param quality Whether to use high-quality rotation. * @return the rotated source image */ public static Pix rotate(Pix pixs, float degrees, boolean quality) { return rotate(pixs, degrees, quality, true); } /** * Performs basic image rotation about the center. * <p> * Notes: * <ol> * <li>Rotation is about the center of the image. * <li>For very small rotations, just return a clone. * <li>Rotation brings either white or black pixels in from outside the * image. * <li>Above 20 degrees, if rotation by shear is requested, we rotate by * sampling. * <li>Colormaps are removed for rotation by area map and shear. * <li>The dest can be expanded so that no image pixels are lost. To invoke * expansion, input the original width and height. For repeated rotation, * use of the original width and height allows the expansion to stop at the * maximum required size, which is a square with side = sqrt(w*w + h*h). * </ol> * * @param pixs The source pix. * @param degrees The number of degrees to rotate; clockwise is positive. * @param quality Whether to use high-quality rotation. * @param resize Whether to expand the output so that no pixels are lost. * <strong>Note:</strong> 1bpp images are always resized when * quality is {@code true}. * @return the rotated source image */ public static Pix rotate(Pix pixs, float degrees, boolean quality, boolean resize) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeRotate(pixs.mNativePix, degrees, quality, resize); if (nativePix == 0) return null; return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeRotate(int nativePix, float degrees, boolean quality, boolean resize); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image bit-depth conversion methods. * * @author alanv@google.com (Alan Viverette) */ public class Convert { static { System.loadLibrary("lept"); } /** * Converts an image of any bit depth to 8-bit grayscale. * * @param pixs Source pix of any bit-depth. * @return a new Pix image or <code>null</code> on error */ public static Pix convertTo8(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeConvertTo8(pixs.mNativePix); if (nativePix == 0) throw new RuntimeException("Failed to natively convert pix"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeConvertTo8(int nativePix); }
Java
/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.tesseract.android; import com.googlecode.tesseract.android.TessBaseAPI.PageIteratorLevel; public class PageIterator { static { System.loadLibrary("lept"); System.loadLibrary("tess"); } /** Pointer to native page iterator. */ private final int mNativePageIterator; /* package */PageIterator(int nativePageIterator) { mNativePageIterator = nativePageIterator; } /** * Resets the iterator to point to the start of the page. */ public void begin() { nativeBegin(mNativePageIterator); } /** * Moves to the start of the next object at the given level in the page * hierarchy, and returns false if the end of the page was reached. * <p> * NOTE that {@link PageIteratorLevel#RIL_SYMBOL} will skip non-text blocks, * but all other {@link PageIteratorLevel} level values will visit each * non-text block once. Think of non text blocks as containing a single * para, with a single line, with a single imaginary word. * <p> * Calls to {@link #next} with different levels may be freely intermixed. * <p> * This function iterates words in right-to-left scripts correctly, if the * appropriate language has been loaded into Tesseract. * * @param level the page iterator level. See {@link PageIteratorLevel}. * @return {@code false} if the end of the page was reached, {@code true} * otherwise. */ public boolean next(int level) { return nativeNext(mNativePageIterator, level); } private static native void nativeBegin(int nativeIterator); private static native boolean nativeNext(int nativeIterator, int level); }
Java
/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.tesseract.android; import com.googlecode.tesseract.android.TessBaseAPI.PageIteratorLevel; /** * Java interface for the ResultIterator. Does not implement all available JNI * methods, but does implement enough to be useful. Comments are adapted from * original Tesseract source. * * @author alanv@google.com (Alan Viverette) */ public class ResultIterator extends PageIterator { static { System.loadLibrary("lept"); System.loadLibrary("tess"); } /** Pointer to native result iterator. */ private final int mNativeResultIterator; /* package */ResultIterator(int nativeResultIterator) { super(nativeResultIterator); mNativeResultIterator = nativeResultIterator; } /** * Returns the text string for the current object at the given level. * * @param level the page iterator level. See {@link PageIteratorLevel}. * @return the text string for the current object at the given level. */ public String getUTF8Text(int level) { return nativeGetUTF8Text(mNativeResultIterator, level); } /** * Returns the mean confidence of the current object at the given level. The * number should be interpreted as a percent probability (0-100). * * @param level the page iterator level. See {@link PageIteratorLevel}. * @return the mean confidence of the current object at the given level. */ public float confidence(int level) { return nativeConfidence(mNativeResultIterator, level); } private static native String nativeGetUTF8Text(int nativeResultIterator, int level); private static native float nativeConfidence(int nativeResultIterator, int level); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.tesseract.android; import android.graphics.Bitmap; import android.graphics.Rect; import com.googlecode.leptonica.android.Pix; import com.googlecode.leptonica.android.Pixa; import com.googlecode.leptonica.android.ReadFile; import java.io.File; /** * Java interface for the Tesseract OCR engine. Does not implement all available * JNI methods, but does implement enough to be useful. Comments are adapted * from original Tesseract source. * * @author alanv@google.com (Alan Viverette) */ public class TessBaseAPI { /** * Used by the native implementation of the class. */ private int mNativeData; static { System.loadLibrary("lept"); System.loadLibrary("tess"); nativeClassInit(); } public static final class PageSegMode { /** Orientation and script detection only. */ public static final int PSM_OSD_ONLY = 0; /** * Automatic page segmentation with orientation and script detection. * (OSD) */ public static final int PSM_AUTO_OSD = 1; /** Automatic page segmentation, but no OSD, or OCR. */ public static final int PSM_AUTO_ONLY = 2; /** Fully automatic page segmentation, but no OSD. */ public static final int PSM_AUTO = 3; /** Assume a single column of text of variable sizes. */ public static final int PSM_SINGLE_COLUMN = 4; /** Assume a single uniform block of vertically aligned text. */ public static final int PSM_SINGLE_BLOCK_VERT_TEXT = 5; /** Assume a single uniform block of text. (Default.) */ public static final int PSM_SINGLE_BLOCK = 6; /** Treat the image as a single text line. */ public static final int PSM_SINGLE_LINE = 7; /** Treat the image as a single word. */ public static final int PSM_SINGLE_WORD = 8; /** Treat the image as a single word in a circle. */ public static final int PSM_CIRCLE_WORD = 9; /** Treat the image as a single character. */ public static final int PSM_SINGLE_CHAR = 10; /** Number of enum entries. */ public static final int PSM_COUNT = 11; } /** * Elements of the page hierarchy, used in {@link ResultIterator} to provide * functions that operate on each level without having to have 5x as many * functions. * <p> * NOTE: At present {@link #RIL_PARA} and {@link #RIL_BLOCK} are equivalent * as there is no paragraph internally yet. */ public static final class PageIteratorLevel { /** Block of text/image/separator line. */ public static final int RIL_BLOCK = 0; /** Paragraph within a block. */ public static final int RIL_PARA = 1; /** Line within a paragraph. */ public static final int RIL_TEXTLINE = 2; /** Word within a text line. */ public static final int RIL_WORD = 3; /** Symbol/character within a word. */ public static final int RIL_SYMBOL = 4; } /** Default accuracy versus speed mode. */ public static final int AVS_FASTEST = 0; /** Slowest and most accurate mode. */ public static final int AVS_MOST_ACCURATE = 100; /** Whitelist of characters to recognize. */ public static final String VAR_CHAR_WHITELIST = "tessedit_char_whitelist"; /** Blacklist of characters to not recognize. */ public static final String VAR_CHAR_BLACKLIST = "tessedit_char_blacklist"; /** Accuracy versus speed setting. */ public static final String VAR_ACCURACYVSPEED = "tessedit_accuracyvspeed"; /** * Constructs an instance of TessBaseAPI. */ public TessBaseAPI() { nativeConstruct(); } /** * Called by the GC to clean up the native data that we set up when we * construct the object. */ @Override protected void finalize() throws Throwable { try { nativeFinalize(); } finally { super.finalize(); } } /** * Initializes the Tesseract engine with a specified language model. Returns * <code>true</code> on success. * <p> * Instances are now mostly thread-safe and totally independent, but some * global parameters remain. Basically it is safe to use multiple * TessBaseAPIs in different threads in parallel, UNLESS you use SetVariable * on some of the Params in classify and textord. If you do, then the effect * will be to change it for all your instances. * <p> * The datapath must be the name of the parent directory of tessdata and * must end in / . Any name after the last / will be stripped. The language * is (usually) an ISO 639-3 string or <code>null</code> will default to * eng. It is entirely safe (and eventually will be efficient too) to call * Init multiple times on the same instance to change language, or just to * reset the classifier. * <p> * <b>WARNING:</b> On changing languages, all Tesseract parameters are reset * back to their default values. (Which may vary between languages.) * <p> * If you have a rare need to set a Variable that controls initialization * for a second call to Init you should explicitly call End() and then use * SetVariable before Init. This is only a very rare use case, since there * are very few uses that require any parameters to be set before Init. * * @param datapath the parent directory of tessdata ending in a forward * slash * @param language (optional) an ISO 639-3 string representing the language * @return <code>true</code> on success */ public boolean init(String datapath, String language) { if (datapath == null) { throw new IllegalArgumentException("Data path must not be null!"); } if (!datapath.endsWith(File.separator)) { datapath += File.separator; } File tessdata = new File(datapath + "tessdata"); if (!tessdata.exists() || !tessdata.isDirectory()) { throw new IllegalArgumentException("Data path must contain subfolder tessdata!"); } return nativeInit(datapath, language); } /** * Frees up recognition results and any stored image data, without actually * freeing any recognition data that would be time-consuming to reload. * Afterwards, you must call SetImage or SetRectangle before doing any * Recognize or Get* operation. */ public void clear() { nativeClear(); } /** * Closes down tesseract and free up all memory. End() is equivalent to * destructing and reconstructing your TessBaseAPI. * <p> * Once End() has been used, none of the other API functions may be used * other than Init and anything declared above it in the class definition. */ public void end() { nativeEnd(); } /** * Set the value of an internal "variable" (of either old or new types). * Supply the name of the variable and the value as a string, just as you * would in a config file. * <p> * Example: * <code>setVariable(VAR_TESSEDIT_CHAR_BLACKLIST, "xyz"); to ignore x, y and z. * setVariable(VAR_BLN_NUMERICMODE, "1"); to set numeric-only mode. * </code> * <p> * setVariable() may be used before open(), but settings will revert to * defaults on close(). * * @param var name of the variable * @param value value to set * @return false if the name lookup failed */ public boolean setVariable(String var, String value) { return nativeSetVariable(var, value); } /** * Sets the page segmentation mode. This controls how much processing the * OCR engine will perform before recognizing text. * * @param mode the page segmentation mode to set */ public void setPageSegMode(int mode) { nativeSetPageSegMode(mode); } /** * Sets debug mode. This controls how much information is displayed in the * log during recognition. * * @param enabled <code>true</code> to enable debugging mode */ public void setDebug(boolean enabled) { nativeSetDebug(enabled); } /** * Restricts recognition to a sub-rectangle of the image. Call after * SetImage. Each SetRectangle clears the recogntion results so multiple * rectangles can be recognized with the same image. * * @param rect the bounding rectangle */ public void setRectangle(Rect rect) { setRectangle(rect.left, rect.top, rect.width(), rect.height()); } /** * Restricts recognition to a sub-rectangle of the image. Call after * SetImage. Each SetRectangle clears the recogntion results so multiple * rectangles can be recognized with the same image. * * @param left the left bound * @param top the right bound * @param width the width of the bounding box * @param height the height of the bounding box */ public void setRectangle(int left, int top, int width, int height) { nativeSetRectangle(left, top, width, height); } /** * Provides an image for Tesseract to recognize. * * @param file absolute path to the image file */ public void setImage(File file) { Pix image = ReadFile.readFile(file); if (image == null) { throw new RuntimeException("Failed to read image file"); } nativeSetImagePix(image.getNativePix()); } /** * Provides an image for Tesseract to recognize. Does not copy the image * buffer. The source image must persist until after Recognize or * GetUTF8Chars is called. * * @param bmp bitmap representation of the image */ public void setImage(Bitmap bmp) { Pix image = ReadFile.readBitmap(bmp); if (image == null) { throw new RuntimeException("Failed to read bitmap"); } nativeSetImagePix(image.getNativePix()); } /** * Provides a Leptonica pix format image for Tesseract to recognize. Clones * the pix object. The source image may be destroyed immediately after * SetImage is called, but its contents may not be modified. * * @param image Leptonica pix representation of the image */ public void setImage(Pix image) { nativeSetImagePix(image.getNativePix()); } /** * Provides an image for Tesseract to recognize. Copies the image buffer. * The source image may be destroyed immediately after SetImage is called. * SetImage clears all recognition results, and sets the rectangle to the * full image, so it may be followed immediately by a GetUTF8Text, and it * will automatically perform recognition. * * @param imagedata byte representation of the image * @param width image width * @param height image height * @param bpp bytes per pixel * @param bpl bytes per line */ public void setImage(byte[] imagedata, int width, int height, int bpp, int bpl) { nativeSetImageBytes(imagedata, width, height, bpp, bpl); } /** * The recognized text is returned as a String which is coded as UTF8. * * @return the recognized text */ public String getUTF8Text() { // Trim because the text will have extra line breaks at the end String text = nativeGetUTF8Text(); return text.trim(); } public Pixa getRegions() { int pixa = nativeGetRegions(); if (pixa == 0) { return null; } return new Pixa(pixa, 0, 0); } public Pixa getWords() { int pixa = nativeGetWords(); if (pixa == 0) { return null; } return new Pixa(pixa, 0, 0); } /** * Returns the mean confidence of text recognition. * * @return the mean confidence */ public int meanConfidence() { return nativeMeanConfidence(); } /** * Returns all word confidences (between 0 and 100) in an array. The number * of confidences should correspond to the number of space-delimited words * in GetUTF8Text(). * * @return an array of word confidences (between 0 and 100) for each * space-delimited word returned by GetUTF8Text() */ public int[] wordConfidences() { int[] conf = nativeWordConfidences(); // We shouldn't return null confidences if (conf == null) { conf = new int[0]; } return conf; } public ResultIterator getResultIterator() { int nativeResultIterator = nativeGetResultIterator(); if (nativeResultIterator == 0) { return null; } return new ResultIterator(nativeResultIterator); } // ****************** // * Native methods * // ****************** /** * Initializes static native data. Must be called on object load. */ private static native void nativeClassInit(); /** * Initializes native data. Must be called on object construction. */ private native void nativeConstruct(); /** * Finalizes native data. Must be called on object destruction. */ private native void nativeFinalize(); private native boolean nativeInit(String datapath, String language); private native void nativeClear(); private native void nativeEnd(); private native void nativeSetImageBytes( byte[] imagedata, int width, int height, int bpp, int bpl); private native void nativeSetImagePix(int nativePix); private native void nativeSetRectangle(int left, int top, int width, int height); private native String nativeGetUTF8Text(); private native int nativeGetRegions(); private native int nativeGetWords(); private native int nativeMeanConfidence(); private native int[] nativeWordConfidences(); private native boolean nativeSetVariable(String var, String value); private native void nativeSetDebug(boolean debug); private native void nativeSetPageSegMode(int mode); private native int nativeGetResultIterator(); }
Java
package org.anddev.andengine.extension.physics.box2d; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.entity.shape.IShape; import org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants; import org.anddev.andengine.util.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:51:22 - 05.07.2010 */ public class PhysicsConnector implements IUpdateHandler, PhysicsConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final IShape mShape; protected final Body mBody; protected final float mShapeHalfBaseWidth; protected final float mShapeHalfBaseHeight; protected boolean mUpdatePosition; protected boolean mUpdateRotation; protected final float mPixelToMeterRatio; // =========================================================== // Constructors // =========================================================== public PhysicsConnector(final IShape pShape, final Body pBody) { this(pShape, pBody, true, true); } public PhysicsConnector(final IShape pShape, final Body pBody, final float pPixelToMeterRatio) { this(pShape, pBody, true, true, pPixelToMeterRatio); } public PhysicsConnector(final IShape pShape, final Body pBody, final boolean pUdatePosition, final boolean pUpdateRotation) { this(pShape, pBody, pUdatePosition, pUpdateRotation, PIXEL_TO_METER_RATIO_DEFAULT); } public PhysicsConnector(final IShape pShape, final Body pBody, final boolean pUdatePosition, final boolean pUpdateRotation, final float pPixelToMeterRatio) { this.mShape = pShape; this.mBody = pBody; this.mUpdatePosition = pUdatePosition; this.mUpdateRotation = pUpdateRotation; this.mPixelToMeterRatio = pPixelToMeterRatio; this.mShapeHalfBaseWidth = pShape.getBaseWidth() * 0.5f; this.mShapeHalfBaseHeight = pShape.getBaseHeight() * 0.5f; } // =========================================================== // Getter & Setter // =========================================================== public IShape getShape() { return this.mShape; } public Body getBody() { return this.mBody; } public boolean isUpdatePosition() { return this.mUpdatePosition; } public boolean isUpdateRotation() { return this.mUpdateRotation; } public void setUpdatePosition(final boolean pUpdatePosition) { this.mUpdatePosition = pUpdatePosition; } public void setUpdateRotation(final boolean pUpdateRotation) { this.mUpdateRotation = pUpdateRotation; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onUpdate(final float pSecondsElapsed) { final IShape shape = this.mShape; final Body body = this.mBody; if(this.mUpdatePosition) { final Vector2 position = body.getPosition(); final float pixelToMeterRatio = this.mPixelToMeterRatio; shape.setPosition(position.x * pixelToMeterRatio - this.mShapeHalfBaseWidth, position.y * pixelToMeterRatio - this.mShapeHalfBaseHeight); } if(this.mUpdateRotation) { final float angle = body.getAngle(); shape.setRotation(MathUtils.radToDeg(angle)); } } @Override public void reset() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.extension.physics.box2d; import java.util.Iterator; import java.util.List; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.engine.handler.runnable.RunnableHandler; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactFilter; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.DestructionListener; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.JointDef; import com.badlogic.gdx.physics.box2d.QueryCallback; import com.badlogic.gdx.physics.box2d.RayCastCallback; import com.badlogic.gdx.physics.box2d.World; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:18:19 - 15.07.2010 */ public class PhysicsWorld implements IUpdateHandler { // =========================================================== // Constants // =========================================================== static { System.loadLibrary( "andenginephysicsbox2dextension" ); } public static final int VELOCITY_ITERATIONS_DEFAULT = 8; public static final int POSITION_ITERATIONS_DEFAULT = 8; // =========================================================== // Fields // =========================================================== protected final PhysicsConnectorManager mPhysicsConnectorManager = new PhysicsConnectorManager(); protected final RunnableHandler mRunnableHandler = new RunnableHandler(); protected final World mWorld; protected int mVelocityIterations = VELOCITY_ITERATIONS_DEFAULT; protected int mPositionIterations = POSITION_ITERATIONS_DEFAULT; // =========================================================== // Constructors // =========================================================== public PhysicsWorld(final Vector2 pGravity, final boolean pAllowSleep) { this(pGravity, pAllowSleep, VELOCITY_ITERATIONS_DEFAULT, POSITION_ITERATIONS_DEFAULT); } public PhysicsWorld(final Vector2 pGravity, final boolean pAllowSleep, final int pVelocityIterations, final int pPositionIterations) { this.mWorld = new World(pGravity, pAllowSleep); this.mVelocityIterations = pVelocityIterations; this.mPositionIterations = pPositionIterations; } // =========================================================== // Getter & Setter // =========================================================== // public World getWorld() { // return this.mWorld; // } public int getPositionIterations() { return this.mPositionIterations; } public void setPositionIterations(final int pPositionIterations) { this.mPositionIterations = pPositionIterations; } public int getVelocityIterations() { return this.mVelocityIterations; } public void setVelocityIterations(final int pVelocityIterations) { this.mVelocityIterations = pVelocityIterations; } public PhysicsConnectorManager getPhysicsConnectorManager() { return this.mPhysicsConnectorManager; } public void clearPhysicsConnectors() { this.mPhysicsConnectorManager.clear(); } public void registerPhysicsConnector(final PhysicsConnector pPhysicsConnector) { this.mPhysicsConnectorManager.add(pPhysicsConnector); } public void unregisterPhysicsConnector(final PhysicsConnector pPhysicsConnector) { this.mPhysicsConnectorManager.remove(pPhysicsConnector); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onUpdate(final float pSecondsElapsed) { this.mRunnableHandler.onUpdate(pSecondsElapsed); this.mWorld.step(pSecondsElapsed, this.mVelocityIterations, this.mPositionIterations); this.mPhysicsConnectorManager.onUpdate(pSecondsElapsed); } @Override public void reset() { // TODO Reset all native physics objects !?!??! this.mPhysicsConnectorManager.reset(); this.mRunnableHandler.reset(); } // =========================================================== // Methods // =========================================================== public void postRunnable(final Runnable pRunnable) { this.mRunnableHandler.postRunnable(pRunnable); } public void clearForces() { this.mWorld.clearForces(); } public Body createBody(final BodyDef pDef) { return this.mWorld.createBody(pDef); } public Joint createJoint(final JointDef pDef) { return this.mWorld.createJoint(pDef); } public void destroyBody(final Body pBody) { this.mWorld.destroyBody(pBody); } public void destroyJoint(final Joint pJoint) { this.mWorld.destroyJoint(pJoint); } public void dispose() { this.mWorld.dispose(); } public boolean getAutoClearForces() { return this.mWorld.getAutoClearForces(); } public Iterator<Body> getBodies() { return this.mWorld.getBodies(); } public int getBodyCount() { return this.mWorld.getBodyCount(); } public int getContactCount() { return this.mWorld.getContactCount(); } public List<Contact> getContactList() { return this.mWorld.getContactList(); } public Vector2 getGravity() { return this.mWorld.getGravity(); } public Iterator<Joint> getJoints() { return this.mWorld.getJoints(); } public int getJointCount() { return this.mWorld.getJointCount(); } public int getProxyCount() { return this.mWorld.getProxyCount(); } public boolean isLocked() { return this.mWorld.isLocked(); } public void QueryAABB(final QueryCallback pCallback, final float pLowerX, final float pLowerY, final float pUpperX, final float pUpperY) { this.mWorld.QueryAABB(pCallback, pLowerX, pLowerY, pUpperX, pUpperY); } public void setAutoClearForces(final boolean pFlag) { this.mWorld.setAutoClearForces(pFlag); } public void setContactFilter(final ContactFilter pFilter) { this.mWorld.setContactFilter(pFilter); } public void setContactListener(final ContactListener pListener) { this.mWorld.setContactListener(pListener); } public void setContinuousPhysics(final boolean pFlag) { this.mWorld.setContinuousPhysics(pFlag); } public void setDestructionListener(final DestructionListener pListener) { this.mWorld.setDestructionListener(pListener); } public void setGravity(final Vector2 pGravity) { this.mWorld.setGravity(pGravity); } public void setWarmStarting(final boolean pFlag) { this.mWorld.setWarmStarting(pFlag); } public void rayCast(final RayCastCallback pRayCastCallback, final Vector2 pPoint1, final Vector2 pPoint2) { this.mWorld.rayCast(pRayCastCallback, pPoint1, pPoint2); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.extension.physics.box2d.util.hull; import com.badlogic.gdx.math.Vector2; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:43:54 - 14.09.2010 */ class Vector2Line { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== Vector2 mVertexA; Vector2 mVertexB; // =========================================================== // Constructors // =========================================================== public Vector2Line(final Vector2 pVertexA, final Vector2 pVertexB) { this.mVertexA = pVertexA; this.mVertexB = pVertexB; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.extension.physics.box2d.util.hull; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import com.badlogic.gdx.math.Vector2; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:01:18 - 14.09.2010 * @see http://www.iti.fh-flensburg.de/lang/algorithmen/geo/ */ public class JarvisMarch extends BaseHullAlgorithm { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public int computeHull(final Vector2[] pVectors) { this.mVertices = pVectors; this.mVertexCount = pVectors.length; this.mHullVertexCount = 0; this.jarvisMarch(); return this.mHullVertexCount; } // =========================================================== // Methods // =========================================================== private void jarvisMarch() { final Vector2[] vertices = this.mVertices; int index = this.indexOfLowestVertex(); do { this.swap(this.mHullVertexCount, index); index = this.indexOfRightmostVertexOf(vertices[this.mHullVertexCount]); this.mHullVertexCount++; } while(index > 0); } private int indexOfRightmostVertexOf(final Vector2 pVector) { final Vector2[] vertices = this.mVertices; final int vertexCount = this.mVertexCount; int i = 0; for(int j = 1; j < vertexCount; j++) { final Vector2 vector2A = Vector2Pool.obtain().set(vertices[j]); final Vector2 vector2B = Vector2Pool.obtain().set(vertices[i]); if(Vector2Util.isLess(vector2A.sub(pVector), vector2B.sub(pVector))) { i = j; } Vector2Pool.recycle(vector2A); Vector2Pool.recycle(vector2B); } return i; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.extension.physics.box2d.util.hull; import com.badlogic.gdx.math.Vector2; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:05:51 - 14.09.2010 */ public abstract class BaseHullAlgorithm implements IHullAlgorithm { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected Vector2[] mVertices; protected int mVertexCount; protected int mHullVertexCount; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== protected int indexOfLowestVertex() { final Vector2[] vertices = this.mVertices; final int vertexCount = this.mVertexCount; int min = 0; for(int i = 1; i < vertexCount; i++) { final float dY = vertices[i].y - vertices[min].y; final float dX = vertices[i].x - vertices[min].x; if(dY < 0 || dY == 0 && dX < 0) { min = i; } } return min; } protected void swap(final int pIndexA, final int pIndexB) { final Vector2[] vertices = this.mVertices; final Vector2 tmp = vertices[pIndexA]; vertices[pIndexA] = vertices[pIndexB]; vertices[pIndexB] = tmp; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.extension.physics.box2d.util.hull; import com.badlogic.gdx.math.Vector2; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:01:34 - 14.09.2010 * @see http://www.iti.fh-flensburg.de/lang/algorithmen/geo/ */ public class QuickHull extends BaseHullAlgorithm { // =========================================================== // Constants // =========================================================== private final static float EPSILON = 1e-3f; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public int computeHull(final Vector2[] pVectors) { this.mVertices = pVectors; this.mVertexCount = this.mVertices.length; this.mHullVertexCount = 0; this.quickHull(); return this.mHullVertexCount; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== private void quickHull() { this.swap(0, this.indexOfLowestVertex()); this.mHullVertexCount++; final Vector2Line line = new Vector2Line(this.mVertices[0], new Vector2(this.mVertices[0]).add(-EPSILON, 0)); this.computeHullVertices(line, 1, this.mVertexCount - 1); } private void computeHullVertices(final Vector2Line pLine, final int pIndexFrom, final int pIndexTo) { if(pIndexFrom > pIndexTo) { return; } final int k = this.indexOfFurthestVertex(pLine, pIndexFrom, pIndexTo); final Vector2Line lineA = new Vector2Line(pLine.mVertexA, this.mVertices[k]); final Vector2Line lineB = new Vector2Line(this.mVertices[k], pLine.mVertexB); this.swap(k, pIndexTo); final int i = this.partition(lineA, pIndexFrom, pIndexTo - 1); /* All vertices from pIndexFrom to i-1 are right of lineA. */ /* All vertices from i to pIndexTo-1 are left of lineA. */ this.computeHullVertices(lineA, pIndexFrom, i - 1); /* All vertices before pIndexTo are now on the hull. */ this.swap(pIndexTo, i); this.swap(i, this.mHullVertexCount); this.mHullVertexCount++; final int j = this.partition(lineB, i + 1, pIndexTo); /* All vertices from i+1 to j-1 are right of lineB. */ /* All vertices from j to pToIndex are on the inside. */ this.computeHullVertices(lineB, i + 1, j - 1); } private int indexOfFurthestVertex(final Vector2Line pLine, final int pFromIndex, final int pToIndex) { final Vector2[] vertices = this.mVertices; int f = pFromIndex; float mx = 0; for(int i = pFromIndex; i <= pToIndex; i++) { final float d = -Vector2Util.area2(vertices[i], pLine); if(d > mx || d == mx && vertices[i].x > vertices[f].y) { mx = d; f = i; } } return f; } private int partition(final Vector2Line pLine, final int pFromIndex, final int pToIndex) { final Vector2[] vertices = this.mVertices; int i = pFromIndex; int j = pToIndex; while(i <= j) { while(i <= j && Vector2Util.isRightOf(vertices[i], pLine)) { i++; } while(i <= j && !Vector2Util.isRightOf(vertices[j], pLine)) { j--; } if(i <= j) { this.swap(i++, j--); } } return i; } }
Java
package org.anddev.andengine.extension.physics.box2d.util.hull; import com.badlogic.gdx.math.Vector2; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:00:50 - 14.09.2010 * @see http://www.iti.fh-flensburg.de/lang/algorithmen/geo/ */ public class GrahamScan extends BaseHullAlgorithm { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public int computeHull(final Vector2[] pVertices) { this.mVertices = pVertices; this.mVertexCount = pVertices.length; if(this.mVertexCount < 3) { return this.mVertexCount; } this.mHullVertexCount = 0; this.grahamScan(); return this.mHullVertexCount; } // =========================================================== // Methods // =========================================================== private void grahamScan() { this.swap(0, this.indexOfLowestVertex()); final Vector2 pl = new Vector2(this.mVertices[0]); this.makeAllVerticesRelativeTo(pl); this.sort(); this.makeAllVerticesRelativeTo(new Vector2(pl).mul(-1)); int i = 3; int k = 3; while(k < this.mVertexCount) { this.swap(i, k); while(!this.isConvex(i - 1)) { this.swap(i - 1, i--); } k++; i++; } this.mHullVertexCount = i; } private void makeAllVerticesRelativeTo(final Vector2 pVector) { final Vector2[] vertices = this.mVertices; final int vertexCount = this.mVertexCount; final Vector2 vertexCopy = new Vector2(pVector); // necessary, as pVector might be in mVertices[] for(int i = 0; i < vertexCount; i++) { vertices[i].sub(vertexCopy); } } private boolean isConvex(final int pIndex) { final Vector2[] vertices = this.mVertices; return Vector2Util.isConvex(vertices[pIndex], vertices[pIndex - 1], vertices[pIndex + 1]); } private void sort() { this.quicksort(1, this.mVertexCount - 1); // without Vertex 0 } private void quicksort(final int pFromIndex, final int pToIndex) { final Vector2[] vertices = this.mVertices; int i = pFromIndex; int j = pToIndex; final Vector2 q = vertices[(pFromIndex + pToIndex) / 2]; while(i <= j) { while(Vector2Util.isLess(vertices[i], q)) { i++; } while(Vector2Util.isLess(q, vertices[j])) { j--; } if(i <= j) { this.swap(i++, j--); } } if(pFromIndex < j) { this.quicksort(pFromIndex, j); } if(i < pToIndex) { this.quicksort(i, pToIndex); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.extension.physics.box2d.util.hull; import com.badlogic.gdx.math.Vector2; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:05:33 - 14.09.2010 */ class Vector2Util { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static boolean isLess(final Vector2 pVertexA, final Vector2 pVertexB) { final float f = pVertexA.cross(pVertexB); return f > 0 || f == 0 && Vector2Util.isLonger(pVertexA, pVertexB); } public static boolean isLonger(final Vector2 pVertexA, final Vector2 pVertexB) { return pVertexA.lenManhattan() > pVertexB.lenManhattan(); } public static float getManhattanDistance(final Vector2 pVertexA, final Vector2 pVertexB) { return Math.abs(pVertexA.x - pVertexB.x) + Math.abs(pVertexA.y - pVertexB.y); } public static boolean isConvex(final Vector2 pVertexTest, final Vector2 pVertexA, final Vector2 pVertexB) { final float f = Vector2Util.area2(pVertexTest, pVertexA, pVertexB); return f < 0 || f == 0 && !Vector2Util.isBetween(pVertexTest, pVertexA, pVertexB); } public static float area2(final Vector2 pVertexTest, final Vector2 pVertexA, final Vector2 pVertexB) { return (pVertexA.x - pVertexTest.x) * (pVertexB.y - pVertexTest.y) - (pVertexB.x - pVertexTest.x) * (pVertexA.y - pVertexTest.y); } public static float area2(final Vector2 pVertexTest, final Vector2Line pLine) { return Vector2Util.area2(pVertexTest, pLine.mVertexA, pLine.mVertexB); } public static boolean isBetween(final Vector2 pVertexTest, final Vector2 pVertexA, final Vector2 pVertexB) { return Vector2Util.getManhattanDistance(pVertexA, pVertexB) >= Vector2Util.getManhattanDistance(pVertexTest, pVertexA) + Vector2Util.getManhattanDistance(pVertexTest, pVertexB); } public static boolean isRightOf(final Vector2 pVertexTest, final Vector2Line pLine) { return Vector2Util.area2(pVertexTest, pLine) < 0; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.extension.physics.box2d.util.hull; import com.badlogic.gdx.math.Vector2; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:46:22 - 14.09.2010 */ public interface IHullAlgorithm { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public int computeHull(final Vector2[] pVertices); }
Java
package org.anddev.andengine.extension.physics.box2d.util.constants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:01:50 - 28.07.2010 */ public interface PhysicsConstants { // =========================================================== // Final Fields // =========================================================== public static final float PIXEL_TO_METER_RATIO_DEFAULT = 32.0f; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.extension.physics.box2d.util; import org.anddev.andengine.util.pool.GenericPool; import com.badlogic.gdx.math.Vector2; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:22:23 - 14.09.2010 */ public class Vector2Pool { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static final GenericPool<Vector2> POOL = new GenericPool<Vector2>() { @Override protected Vector2 onAllocatePoolItem() { return new Vector2(); } }; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== public static Vector2 obtain() { return POOL.obtainPoolItem(); } public static Vector2 obtain(final Vector2 pCopyFrom) { return POOL.obtainPoolItem().set(pCopyFrom); } public static Vector2 obtain(final float pX, final float pY) { return POOL.obtainPoolItem().set(pX, pY); } public static void recycle(final Vector2 pVector2) { POOL.recyclePoolItem(pVector2); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.extension.physics.box2d.util.triangulation; import java.util.List; import com.badlogic.gdx.math.Vector2; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:16:04 - 14.09.2010 */ public interface ITriangulationAlgoritm { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== /** * @return a {@link List} of {@link Vector2} objects where every three {@link Vector2} objects form a triangle. */ public List<Vector2> computeTriangles(final List<Vector2> pVertices); }
Java
/******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.anddev.andengine.extension.physics.box2d.util.triangulation; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.badlogic.gdx.math.Vector2; /** * A simple implementation of the ear cutting algorithm to triangulate simple * polygons without holes. For more information: * @see http://cgm.cs.mcgill.ca/~godfried/teaching/cg-projects/97/Ian/algorithm2.html * @see http://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf * * @author badlogicgames@gmail.com * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich (Improved performance. Collinear edges are now supported.) */ public final class EarClippingTriangulator implements ITriangulationAlgoritm { // =========================================================== // Constants // =========================================================== private static final int CONCAVE = 1; private static final int CONVEX = -1; // =========================================================== // Fields // =========================================================== private int mConcaveVertexCount; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public List<Vector2> computeTriangles(final List<Vector2> pVertices) { // TODO Check if LinkedList performs better final ArrayList<Vector2> triangles = new ArrayList<Vector2>(); final ArrayList<Vector2> vertices = new ArrayList<Vector2>(pVertices.size()); vertices.addAll(pVertices); if(vertices.size() == 3) { triangles.addAll(vertices); return triangles; } while(vertices.size() >= 3) { // TODO Usually(Always?) only the Types of the vertices next to the ear change! --> Improve final int vertexTypes[] = this.classifyVertices(vertices); final int vertexCount = vertices.size(); for(int index = 0; index < vertexCount; index++) { if(this.isEarTip(vertices, index, vertexTypes)) { this.cutEarTip(vertices, index, triangles); break; } } } return triangles; } // =========================================================== // Methods // =========================================================== private static boolean areVerticesClockwise(final ArrayList<Vector2> pVertices) { final int vertexCount = pVertices.size(); float area = 0; for(int i = 0; i < vertexCount; i++) { final Vector2 p1 = pVertices.get(i); final Vector2 p2 = pVertices.get(EarClippingTriangulator.computeNextIndex(pVertices, i)); area += p1.x * p2.y - p2.x * p1.y; } if(area < 0) { return true; } else { return false; } } /** * @param pVertices * @return An array of length <code>pVertices.size()</code> filled with either {@link EarClippingTriangulator#CONCAVE} or * {@link EarClippingTriangulator#CONVEX}. */ private int[] classifyVertices(final ArrayList<Vector2> pVertices) { final int vertexCount = pVertices.size(); final int[] vertexTypes = new int[vertexCount]; this.mConcaveVertexCount = 0; /* Ensure vertices are in clockwise order. */ if(!EarClippingTriangulator.areVerticesClockwise(pVertices)) { Collections.reverse(pVertices); } for(int index = 0; index < vertexCount; index++) { final int previousIndex = EarClippingTriangulator.computePreviousIndex(pVertices, index); final int nextIndex = EarClippingTriangulator.computeNextIndex(pVertices, index); final Vector2 previousVertex = pVertices.get(previousIndex); final Vector2 currentVertex = pVertices.get(index); final Vector2 nextVertex = pVertices.get(nextIndex); if(EarClippingTriangulator.isTriangleConvex(previousVertex.x, previousVertex.y, currentVertex.x, currentVertex.y, nextVertex.x, nextVertex.y)) { vertexTypes[index] = CONVEX; } else { vertexTypes[index] = CONCAVE; this.mConcaveVertexCount++; } } return vertexTypes; } private static boolean isTriangleConvex(final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3) { if(EarClippingTriangulator.computeSpannedAreaSign(pX1, pY1, pX2, pY2, pX3, pY3) < 0) { return false; } else { return true; } } private static int computeSpannedAreaSign(final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3) { float area = 0; area += pX1 * (pY3 - pY2); area += pX2 * (pY1 - pY3); area += pX3 * (pY2 - pY1); return (int)Math.signum(area); } /** * @return <code>true</code> when the Triangles contains one or more vertices, <code>false</code> otherwise. */ private static boolean isAnyVertexInTriangle(final ArrayList<Vector2> pVertices, final int[] pVertexTypes, final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3) { int i = 0; final int vertexCount = pVertices.size(); while(i < vertexCount - 1) { if((pVertexTypes[i] == CONCAVE)) { final Vector2 currentVertex = pVertices.get(i); final float currentVertexX = currentVertex.x; final float currentVertexY = currentVertex.y; /* TODO The following condition fails for perpendicular, axis aligned triangles! * Removing it doesn't seem to cause problems. * Maybe it was an optimization? * Maybe it tried to handle collinear pieces ? */ // if(((currentVertexX != pX1) && (currentVertexY != pY1)) || ((currentVertexX != pX2) && (currentVertexY != pY2)) || ((currentVertexX != pX3) && (currentVertexY != pY3))) { final int areaSign1 = EarClippingTriangulator.computeSpannedAreaSign(pX1, pY1, pX2, pY2, currentVertexX, currentVertexY); final int areaSign2 = EarClippingTriangulator.computeSpannedAreaSign(pX2, pY2, pX3, pY3, currentVertexX, currentVertexY); final int areaSign3 = EarClippingTriangulator.computeSpannedAreaSign(pX3, pY3, pX1, pY1, currentVertexX, currentVertexY); if(areaSign1 > 0 && areaSign2 > 0 && areaSign3 > 0) { return true; } else if(areaSign1 <= 0 && areaSign2 <= 0 && areaSign3 <= 0) { return true; } // } } i++; } return false; } private boolean isEarTip(final ArrayList<Vector2> pVertices, final int pEarTipIndex, final int[] pVertexTypes) { if(this.mConcaveVertexCount != 0) { final Vector2 previousVertex = pVertices.get(EarClippingTriangulator.computePreviousIndex(pVertices, pEarTipIndex)); final Vector2 currentVertex = pVertices.get(pEarTipIndex); final Vector2 nextVertex = pVertices.get(EarClippingTriangulator.computeNextIndex(pVertices, pEarTipIndex)); if(EarClippingTriangulator.isAnyVertexInTriangle(pVertices, pVertexTypes, previousVertex.x, previousVertex.y, currentVertex.x, currentVertex.y, nextVertex.x, nextVertex.y)) { return false; } else { return true; } } else { return true; } } private void cutEarTip(final ArrayList<Vector2> pVertices, final int pEarTipIndex, final ArrayList<Vector2> pTriangles) { final int previousIndex = EarClippingTriangulator.computePreviousIndex(pVertices, pEarTipIndex); final int nextIndex = EarClippingTriangulator.computeNextIndex(pVertices, pEarTipIndex); if(!EarClippingTriangulator.isCollinear(pVertices, previousIndex, pEarTipIndex, nextIndex)) { pTriangles.add(new Vector2(pVertices.get(previousIndex))); pTriangles.add(new Vector2(pVertices.get(pEarTipIndex))); pTriangles.add(new Vector2(pVertices.get(nextIndex))); } pVertices.remove(pEarTipIndex); if(pVertices.size() >= 3) { EarClippingTriangulator.removeCollinearNeighborEarsAfterRemovingEarTip(pVertices, pEarTipIndex); } } private static void removeCollinearNeighborEarsAfterRemovingEarTip(final ArrayList<Vector2> pVertices, final int pEarTipCutIndex) { final int collinearityCheckNextIndex = pEarTipCutIndex % pVertices.size(); int collinearCheckPreviousIndex = EarClippingTriangulator.computePreviousIndex(pVertices, collinearityCheckNextIndex); if(EarClippingTriangulator.isCollinear(pVertices, collinearityCheckNextIndex)) { pVertices.remove(collinearityCheckNextIndex); if(pVertices.size() > 3) { /* Update */ collinearCheckPreviousIndex = EarClippingTriangulator.computePreviousIndex(pVertices, collinearityCheckNextIndex); if(EarClippingTriangulator.isCollinear(pVertices, collinearCheckPreviousIndex)){ pVertices.remove(collinearCheckPreviousIndex); } } } else if(EarClippingTriangulator.isCollinear(pVertices, collinearCheckPreviousIndex)){ pVertices.remove(collinearCheckPreviousIndex); } } private static boolean isCollinear(final ArrayList<Vector2> pVertices, final int pIndex) { final int previousIndex = EarClippingTriangulator.computePreviousIndex(pVertices, pIndex); final int nextIndex = EarClippingTriangulator.computeNextIndex(pVertices, pIndex); return EarClippingTriangulator.isCollinear(pVertices, previousIndex, pIndex, nextIndex); } private static boolean isCollinear(final ArrayList<Vector2> pVertices, final int pPreviousIndex, final int pIndex, final int pNextIndex) { final Vector2 previousVertex = pVertices.get(pPreviousIndex); final Vector2 vertex = pVertices.get(pIndex); final Vector2 nextVertex = pVertices.get(pNextIndex); return EarClippingTriangulator.computeSpannedAreaSign(previousVertex.x, previousVertex.y, vertex.x, vertex.y, nextVertex.x, nextVertex.y) == 0; } private static int computePreviousIndex(final List<Vector2> pVertices, final int pIndex) { return pIndex == 0 ? pVertices.size() - 1 : pIndex - 1; } private static int computeNextIndex(final List<Vector2> pVertices, final int pIndex) { return pIndex == pVertices.size() - 1 ? 0 : pIndex + 1; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.extension.physics.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.World; /** * A subclass of {@link PhysicsWorld} that tries to achieve a specific amount of steps per second. * When the time since the last step is bigger long the steplength, additional steps are executed. * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:39:42 - 25.07.2010 */ public class FixedStepPhysicsWorld extends PhysicsWorld { // =========================================================== // Constants // =========================================================== public static final int STEPSPERSECOND_DEFAULT = 60; // =========================================================== // Fields // =========================================================== private final float mTimeStep; private final int mMaximumStepsPerUpdate; private float mSecondsElapsedAccumulator; // =========================================================== // Constructors // =========================================================== public FixedStepPhysicsWorld(final int pStepsPerSecond, final Vector2 pGravity, final boolean pAllowSleep) { this(pStepsPerSecond, Integer.MAX_VALUE, pGravity, pAllowSleep); } public FixedStepPhysicsWorld(final int pStepsPerSecond, final int pMaximumStepsPerUpdate, final Vector2 pGravity, final boolean pAllowSleep) { super(pGravity, pAllowSleep); this.mTimeStep = 1.0f / pStepsPerSecond; this.mMaximumStepsPerUpdate = pMaximumStepsPerUpdate; } public FixedStepPhysicsWorld(final int pStepsPerSecond, final Vector2 pGravity, final boolean pAllowSleep, final int pVelocityIterations, final int pPositionIterations) { this(pStepsPerSecond, Integer.MAX_VALUE, pGravity, pAllowSleep, pVelocityIterations, pPositionIterations); } public FixedStepPhysicsWorld(final int pStepsPerSecond, final int pMaximumStepsPerUpdate, final Vector2 pGravity, final boolean pAllowSleep, final int pVelocityIterations, final int pPositionIterations) { super(pGravity, pAllowSleep, pVelocityIterations, pPositionIterations); this.mTimeStep = 1.0f / pStepsPerSecond; this.mMaximumStepsPerUpdate = pMaximumStepsPerUpdate; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onUpdate(final float pSecondsElapsed) { this.mRunnableHandler.onUpdate(pSecondsElapsed); this.mSecondsElapsedAccumulator += pSecondsElapsed; final int velocityIterations = this.mVelocityIterations; final int positionIterations = this.mPositionIterations; final World world = this.mWorld; final float stepLength = this.mTimeStep; int stepsAllowed = this.mMaximumStepsPerUpdate; while(this.mSecondsElapsedAccumulator >= stepLength && stepsAllowed > 0) { world.step(stepLength, velocityIterations, positionIterations); this.mSecondsElapsedAccumulator -= stepLength; stepsAllowed--; } this.mPhysicsConnectorManager.onUpdate(pSecondsElapsed); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.extension.physics.box2d; import static org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT; import java.util.List; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.shape.IShape; import org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants; import org.anddev.andengine.util.MathUtils; import org.anddev.andengine.util.constants.Constants; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.Filter; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:59:03 - 15.07.2010 */ public class PhysicsFactory { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== public static FixtureDef createFixtureDef(final float pDensity, final float pElasticity, final float pFriction) { return PhysicsFactory.createFixtureDef(pDensity, pElasticity, pFriction, false); } public static FixtureDef createFixtureDef(final float pDensity, final float pElasticity, final float pFriction, final boolean pSensor) { final FixtureDef fixtureDef = new FixtureDef(); fixtureDef.density = pDensity; fixtureDef.restitution = pElasticity; fixtureDef.friction = pFriction; fixtureDef.isSensor = pSensor; return fixtureDef; } public static FixtureDef createFixtureDef(final float pDensity, final float pElasticity, final float pFriction, final boolean pSensor, final short pCategoryBits, final short pMaskBits, final short pGroupIndex) { final FixtureDef fixtureDef = new FixtureDef(); fixtureDef.density = pDensity; fixtureDef.restitution = pElasticity; fixtureDef.friction = pFriction; fixtureDef.isSensor = pSensor; final Filter filter = fixtureDef.filter; filter.categoryBits = pCategoryBits; filter.maskBits = pMaskBits; filter.groupIndex = pGroupIndex; return fixtureDef; } public static Body createBoxBody(final PhysicsWorld pPhysicsWorld, final IShape pShape, final BodyType pBodyType, final FixtureDef pFixtureDef) { return PhysicsFactory.createBoxBody(pPhysicsWorld, pShape, pBodyType, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT); } public static Body createBoxBody(final PhysicsWorld pPhysicsWorld, final IShape pShape, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) { final float[] sceneCenterCoordinates = pShape.getSceneCenterCoordinates(); final float centerX = sceneCenterCoordinates[Constants.VERTEX_INDEX_X]; final float centerY = sceneCenterCoordinates[Constants.VERTEX_INDEX_Y]; return PhysicsFactory.createBoxBody(pPhysicsWorld, centerX, centerY, pShape.getWidthScaled(), pShape.getHeightScaled(), pShape.getRotation(), pBodyType, pFixtureDef, pPixelToMeterRatio); } public static Body createBoxBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final float pWidth, final float pHeight, final float pRotation, final BodyType pBodyType, final FixtureDef pFixtureDef) { return PhysicsFactory.createBoxBody(pPhysicsWorld, pCenterX, pCenterY, pWidth, pHeight, pRotation, pBodyType, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT); } public static Body createBoxBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final float pWidth, final float pHeight, final float pRotation, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) { final BodyDef boxBodyDef = new BodyDef(); boxBodyDef.type = pBodyType; boxBodyDef.position.x = pCenterX / pPixelToMeterRatio; boxBodyDef.position.y = pCenterY / pPixelToMeterRatio; final Body boxBody = pPhysicsWorld.createBody(boxBodyDef); final PolygonShape boxPoly = new PolygonShape(); final float halfWidth = pWidth * 0.5f / pPixelToMeterRatio; final float halfHeight = pHeight * 0.5f / pPixelToMeterRatio; boxPoly.setAsBox(halfWidth, halfHeight); pFixtureDef.shape = boxPoly; boxBody.createFixture(pFixtureDef); boxPoly.dispose(); boxBody.setTransform(boxBody.getWorldCenter(), MathUtils.degToRad(pRotation)); return boxBody; } public static Body createCircleBody(final PhysicsWorld pPhysicsWorld, final IShape pShape, final BodyType pBodyType, final FixtureDef pFixtureDef) { return PhysicsFactory.createCircleBody(pPhysicsWorld, pShape, pBodyType, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT); } public static Body createCircleBody(final PhysicsWorld pPhysicsWorld, final IShape pShape, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) { final float[] sceneCenterCoordinates = pShape.getSceneCenterCoordinates(); final float centerX = sceneCenterCoordinates[Constants.VERTEX_INDEX_X]; final float centerY = sceneCenterCoordinates[Constants.VERTEX_INDEX_Y]; return PhysicsFactory.createCircleBody(pPhysicsWorld, centerX, centerY, pShape.getWidthScaled() * 0.5f, pShape.getRotation(), pBodyType, pFixtureDef, pPixelToMeterRatio); } public static Body createCircleBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final float pRadius, final float pRotation, final BodyType pBodyType, final FixtureDef pFixtureDef) { return createCircleBody(pPhysicsWorld, pCenterX, pCenterY, pRadius, pRotation, pBodyType, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT); } public static Body createCircleBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final float pRadius, final float pRotation, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) { final BodyDef circleBodyDef = new BodyDef(); circleBodyDef.type = pBodyType; circleBodyDef.position.x = pCenterX / pPixelToMeterRatio; circleBodyDef.position.y = pCenterY / pPixelToMeterRatio; circleBodyDef.angle = MathUtils.degToRad(pRotation); final Body circleBody = pPhysicsWorld.createBody(circleBodyDef); final CircleShape circlePoly = new CircleShape(); pFixtureDef.shape = circlePoly; final float radius = pRadius / pPixelToMeterRatio; circlePoly.setRadius(radius); circleBody.createFixture(pFixtureDef); circlePoly.dispose(); return circleBody; } public static Body createLineBody(final PhysicsWorld pPhysicsWorld, final Line pLine, final FixtureDef pFixtureDef) { return PhysicsFactory.createLineBody(pPhysicsWorld, pLine, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT); } public static Body createLineBody(final PhysicsWorld pPhysicsWorld, final Line pLine, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) { final BodyDef lineBodyDef = new BodyDef(); lineBodyDef.type = BodyType.StaticBody; final Body boxBody = pPhysicsWorld.createBody(lineBodyDef); final PolygonShape linePoly = new PolygonShape(); linePoly.setAsEdge(new Vector2(pLine.getX1() / pPixelToMeterRatio, pLine.getY1() / pPixelToMeterRatio), new Vector2(pLine.getX2() / pPixelToMeterRatio, pLine.getY2() / pPixelToMeterRatio)); pFixtureDef.shape = linePoly; boxBody.createFixture(pFixtureDef); linePoly.dispose(); return boxBody; } /** * @param pPhysicsWorld * @param pShape * @param pVertices are to be defined relative to the center of the pShape and have the {@link PhysicsConstants#PIXEL_TO_METER_RATIO_DEFAULT} applied. * @param pBodyType * @param pFixtureDef * @return */ public static Body createPolygonBody(final PhysicsWorld pPhysicsWorld, final IShape pShape, final Vector2[] pVertices, final BodyType pBodyType, final FixtureDef pFixtureDef) { return PhysicsFactory.createPolygonBody(pPhysicsWorld, pShape, pVertices, pBodyType, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT); } /** * @param pPhysicsWorld * @param pShape * @param pVertices are to be defined relative to the center of the pShape. * @param pBodyType * @param pFixtureDef * @return */ public static Body createPolygonBody(final PhysicsWorld pPhysicsWorld, final IShape pShape, final Vector2[] pVertices, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) { final BodyDef boxBodyDef = new BodyDef(); boxBodyDef.type = pBodyType; final float[] sceneCenterCoordinates = pShape.getSceneCenterCoordinates(); boxBodyDef.position.x = sceneCenterCoordinates[Constants.VERTEX_INDEX_X] / pPixelToMeterRatio; boxBodyDef.position.y = sceneCenterCoordinates[Constants.VERTEX_INDEX_Y] / pPixelToMeterRatio; final Body boxBody = pPhysicsWorld.createBody(boxBodyDef); final PolygonShape boxPoly = new PolygonShape(); boxPoly.set(pVertices); pFixtureDef.shape = boxPoly; boxBody.createFixture(pFixtureDef); boxPoly.dispose(); return boxBody; } /** * @param pPhysicsWorld * @param pShape * @param pTriangleVertices are to be defined relative to the center of the pShape and have the {@link PhysicsConstants#PIXEL_TO_METER_RATIO_DEFAULT} applied. * @param pBodyType * @param pFixtureDef * @return */ public static Body createTrianglulatedBody(final PhysicsWorld pPhysicsWorld, final IShape pShape, final List<Vector2> pTriangleVertices, final BodyType pBodyType, final FixtureDef pFixtureDef) { return PhysicsFactory.createTrianglulatedBody(pPhysicsWorld, pShape, pTriangleVertices, pBodyType, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT); } /** * @param pPhysicsWorld * @param pShape * @param pTriangleVertices are to be defined relative to the center of the pShape and have the {@link PhysicsConstants#PIXEL_TO_METER_RATIO_DEFAULT} applied. * The vertices will be triangulated and for each triangle a {@link Fixture} will be created. * @param pBodyType * @param pFixtureDef * @return */ public static Body createTrianglulatedBody(final PhysicsWorld pPhysicsWorld, final IShape pShape, final List<Vector2> pTriangleVertices, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) { final Vector2[] TMP_TRIANGLE = new Vector2[3]; final BodyDef boxBodyDef = new BodyDef(); boxBodyDef.type = pBodyType; final float[] sceneCenterCoordinates = pShape.getSceneCenterCoordinates(); boxBodyDef.position.x = sceneCenterCoordinates[Constants.VERTEX_INDEX_X] / pPixelToMeterRatio; boxBodyDef.position.y = sceneCenterCoordinates[Constants.VERTEX_INDEX_Y] / pPixelToMeterRatio; final Body boxBody = pPhysicsWorld.createBody(boxBodyDef); final int vertexCount = pTriangleVertices.size(); for(int i = 0; i < vertexCount; /* */) { final PolygonShape boxPoly = new PolygonShape(); TMP_TRIANGLE[2] = pTriangleVertices.get(i++); TMP_TRIANGLE[1] = pTriangleVertices.get(i++); TMP_TRIANGLE[0] = pTriangleVertices.get(i++); boxPoly.set(TMP_TRIANGLE); pFixtureDef.shape = boxPoly; boxBody.createFixture(pFixtureDef); boxPoly.dispose(); } return boxBody; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.extension.physics.box2d; import java.util.ArrayList; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.entity.shape.IShape; import com.badlogic.gdx.physics.box2d.Body; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:52:27 - 15.07.2010 */ public class PhysicsConnectorManager extends ArrayList<PhysicsConnector> implements IUpdateHandler { // =========================================================== // Constants // =========================================================== private static final long serialVersionUID = 412969510084261799L; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== PhysicsConnectorManager() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onUpdate(final float pSecondsElapsed) { final ArrayList<PhysicsConnector> physicsConnectors = this; for(int i = physicsConnectors.size() - 1; i >= 0; i--) { physicsConnectors.get(i).onUpdate(pSecondsElapsed); } } @Override public void reset() { final ArrayList<PhysicsConnector> physicsConnectors = this; for(int i = physicsConnectors.size() - 1; i >= 0; i--) { physicsConnectors.get(i).reset(); } } // =========================================================== // Methods // =========================================================== public Body findBodyByShape(final IShape pShape) { final ArrayList<PhysicsConnector> physicsConnectors = this; for(int i = physicsConnectors.size() - 1; i >= 0; i--) { final PhysicsConnector physicsConnector = physicsConnectors.get(i); if(physicsConnector.mShape == pShape){ return physicsConnector.mBody; } } return null; } public PhysicsConnector findPhysicsConnectorByShape(final IShape pShape) { final ArrayList<PhysicsConnector> physicsConnectors = this; for(int i = physicsConnectors.size() - 1; i >= 0; i--) { final PhysicsConnector physicsConnector = physicsConnectors.get(i); if(physicsConnector.mShape == pShape){ return physicsConnector; } } return null; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
/******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. ******************************************************************************/ package com.badlogic.gdx.math; /** * Encapsulates a 2D vector. Allows chaining methods by returning a reference to itself * @author badlogicgames@gmail.com * */ public final class Vector2 { /** static temporary vector **/ private final static Vector2 tmp = new Vector2(); /** the x-component of this vector **/ public float x; /** the y-component of this vector **/ public float y; /** * Constructs a new vector at (0,0) */ public Vector2 () { } /** * Constructs a vector with the given components * @param x The x-component * @param y The y-component */ public Vector2 (float x, float y) { this.x = x; this.y = y; } /** * Constructs a vector from the given vector * @param v The vector */ public Vector2 (Vector2 v) { set(v); } /** * @return a copy of this vector */ public Vector2 cpy () { return new Vector2(this); } /** * @return The euclidian length */ public float len () { return (float)Math.sqrt(x * x + y * y); } /** * @return The squared euclidian length */ public float len2 () { return x * x + y * y; } /** * Sets this vector from the given vector * @param v The vector * @return This vector for chaining */ public Vector2 set (Vector2 v) { x = v.x; y = v.y; return this; } /** * Sets the components of this vector * @param x The x-component * @param y The y-component * @return This vector for chaining */ public Vector2 set (float x, float y) { this.x = x; this.y = y; return this; } /** * Substracts the given vector from this vector. * @param v The vector * @return This vector for chaining */ public Vector2 sub (Vector2 v) { x -= v.x; y -= v.y; return this; } /** * Normalizes this vector * @return This vector for chaining */ public Vector2 nor () { float len = len(); if (len != 0) { x /= len; y /= len; } return this; } /** * Adds the given vector to this vector * @param v The vector * @return This vector for chaining */ public Vector2 add (Vector2 v) { x += v.x; y += v.y; return this; } /** * Adds the given components to this vector * @param x The x-component * @param y The y-component * @return This vector for chaining */ public Vector2 add (float x, float y) { this.x += x; this.y += y; return this; } /** * @param v The other vector * @return The dot product between this and the other vector */ public float dot (Vector2 v) { return x * v.x + y * v.y; } /** * Multiplies this vector by a scalar * @param scalar The scalar * @return This vector for chaining */ public Vector2 mul (float scalar) { x *= scalar; y *= scalar; return this; } /** * @param v The other vector * @return the distance between this and the other vector */ public float dst (Vector2 v) { float x_d = v.x - x; float y_d = v.y - y; return (float)Math.sqrt(x_d * x_d + y_d * y_d); } /** * @param x The x-component of the other vector * @param y The y-component of the other vector * @return the distance between this and the other vector */ public float dst (float x, float y) { float x_d = x - this.x; float y_d = y - this.y; return (float)Math.sqrt(x_d * x_d + y_d * y_d); } /** * @param v The other vector * @return the squared distance between this and the other vector */ public float dst2 (Vector2 v) { float x_d = v.x - x; float y_d = v.y - y; return x_d * x_d + y_d * y_d; } public String toString () { return "[" + x + ":" + y + "]"; } /** * Substracts the other vector from this vector. * @param x The x-component of the other vector * @param y The y-component of the other vector * @return This vector for chaining */ public Vector2 sub (float x, float y) { this.x -= x; this.y -= y; return this; } /** * @return a temporary copy of this vector. Use with care as this is backed by a single static Vector2 instance. v1.tmp().add( * v2.tmp() ) will not work! */ public Vector2 tmp () { return tmp.set(this); } /** * @param v the other vector * @return The cross product between this and the other vector */ public float cross(final Vector2 v) { return this.x * v.y - v.x * this.y; } /** * @return The manhattan length */ public float lenManhattan() { return Math.abs(this.x) + Math.abs(this.y); } }
Java
package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; public class Manifold { final World world; long addr; final ManifoldPoint[] points = new ManifoldPoint[] { new ManifoldPoint(), new ManifoldPoint() }; final Vector2 localNormal = new Vector2(); final Vector2 localPoint = new Vector2(); final int[] tmpInt = new int[2]; final float[] tmpFloat = new float[4]; protected Manifold(World world, long addr) { this.world = world; this.addr = addr; } public ManifoldType getType() { int type = jniGetType(addr); if(type == 0) return ManifoldType.Circle; if(type == 1) return ManifoldType.FaceA; if(type == 2) return ManifoldType.FaceB; return ManifoldType.Circle; } private native int jniGetType(long addr); public int getPointCount() { return jniGetPointCount(addr); } private native int jniGetPointCount(long addr); public Vector2 getLocalNormal() { jniGetLocalNormal(addr, tmpFloat); localNormal.set(tmpFloat[0], tmpFloat[1]); return localNormal; } private native void jniGetLocalNormal(long addr, float[] values); public Vector2 getLocalPoint() { jniGetLocalPoint(addr, tmpFloat); localPoint.set(tmpFloat[0], tmpFloat[1]); return localPoint; } private native void jniGetLocalPoint(long addr, float[] values); public ManifoldPoint[] getPoints() { int count = jniGetPointCount(addr); for(int i = 0; i < count; i++) { int contactID = jniGetPoint(addr, tmpFloat, i); ManifoldPoint point = points[i]; point.contactID = contactID; point.localPoint.set(tmpFloat[0], tmpFloat[1]); point.normalImpulse = tmpFloat[2]; point.tangentImpulse = tmpFloat[3]; } return points; } private native int jniGetPoint(long addr, float[] values, int i); public class ManifoldPoint { public final Vector2 localPoint = new Vector2(); public float normalImpulse; public float tangentImpulse; public int contactID = 0; public String toString() { return "id: " + contactID + ", " + localPoint + ", " + normalImpulse + ", " + tangentImpulse; } } public enum ManifoldType { Circle, FaceA, FaceB } }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; public class JointDef { public enum JointType { Unknown(0), RevoluteJoint(1), PrismaticJoint(2), DistanceJoint(3), PulleyJoint(4), MouseJoint(5), GearJoint(6), LineJoint(7), WeldJoint( 8), FrictionJoint(9); public static JointType[] valueTypes = new JointType[] {Unknown, RevoluteJoint, PrismaticJoint, DistanceJoint, PulleyJoint, MouseJoint, GearJoint, LineJoint, WeldJoint, FrictionJoint}; private int value; JointType (int value) { this.value = value; } public int getValue () { return value; } } /** The joint type is set automatically for concrete joint types. **/ public JointType type = JointType.Unknown; /** The first attached body. **/ public Body bodyA = null; /** The second attached body **/ public Body bodyB = null; /** Set this flag to true if the attached bodies should collide. **/ public boolean collideConnected = false; }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; /** * This holds contact filtering data. * @author mzechner * */ public class Filter { /** * The collision category bits. Normally you would just set one bit. */ public short categoryBits = 0x0001; /** * The collision mask bits. This states the categories that this shape would accept for collision. */ public short maskBits = -1; /** * Collision groups allow a certain group of objects to never collide (negative) or always collide (positive). Zero means no * collision group. Non-zero group filtering always wins against the mask bits. */ public short groupIndex = 0; }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; /** * A body definition holds all the data needed to construct a rigid body. You can safely re-use body definitions. Shapes are added * to a body after construction. * * @author mzechner * */ public class BodyDef { /** * The body type. static: zero mass, zero velocity, may be manually moved kinematic: zero mass, non-zero velocity set by user, * moved by solver dynamic: positive mass, non-zero velocity determined by forces, moved by solver */ public enum BodyType { StaticBody(0), KinematicBody(1), DynamicBody(2); private int value; private BodyType (int value) { this.value = value; } public int getValue () { return value; } }; /** * The body type: static, kinematic, or dynamic. Note: if a dynamic body would have zero mass, the mass is set to one. **/ public BodyType type = BodyType.StaticBody; /** * The world position of the body. Avoid creating bodies at the origin since this can lead to many overlapping shapes. **/ public final Vector2 position = new Vector2(); /** The world angle of the body in radians. **/ public float angle = 0; /** The linear velocity of the body's origin in world co-ordinates. **/ public final Vector2 linearVelocity = new Vector2(); /** The angular velocity of the body. **/ public float angularVelocity = 0; /** * Linear damping is use to reduce the linear velocity. The damping parameter can be larger than 1.0f but the damping effect * becomes sensitive to the time step when the damping parameter is large. **/ public float linearDamping = 0; /** * Angular damping is use to reduce the angular velocity. The damping parameter can be larger than 1.0f but the damping effect * becomes sensitive to the time step when the damping parameter is large. **/ public float angularDamping = 0; /** * Set this flag to false if this body should never fall asleep. Note that this increases CPU usage. **/ public boolean allowSleep = true; /** Is this body initially awake or sleeping? **/ public boolean awake = true; /** Should this body be prevented from rotating? Useful for characters. **/ public boolean fixedRotation = false; /** * Is this a fast moving body that should be prevented from tunneling through other moving bodies? Note that all bodies are * prevented from tunneling through kinematic and static bodies. This setting is only considered on dynamic bodies. * @warning You should use this flag sparingly since it increases processing time. **/ public boolean bullet = false; /** Does this body start out active? **/ public boolean active = true; /** Experimental: scales the inertia tensor. **/ public float inertiaScale = 1; }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; /** * A joint edge is used to connect bodies and joints together in a joint graph where each body is a node and each joint is an * edge. A joint edge belongs to a doubly linked list maintained in each attached body. Each joint has two joint nodes, one for * each attached body. */ public class JointEdge { public final Body other; public final Joint joint; protected JointEdge (Body other, Joint joint) { this.other = other; this.joint = joint; } }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; /** * This holds the mass data computed for a shape. * @author mzechner * */ public class MassData { /** The mass of the shape, usually in kilograms. **/ public float mass; /** The position of the shape's centroid relative to the shape's origin. **/ public final Vector2 center = new Vector2(); /** The rotational inertia of the shape about the local origin. **/ public float I; }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; import java.util.ArrayList; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; /** * A rigid body. These are created via World.CreateBody. * @author mzechner * */ public class Body { /** the address of the body **/ protected final long addr; /** temporary float array **/ private final float[] tmp = new float[4]; /** World **/ private final World world; /** Fixtures of this body **/ private ArrayList<Fixture> fixtures = new ArrayList<Fixture>(2); /** Joints of this body **/ protected ArrayList<JointEdge> joints = new ArrayList<JointEdge>(2); /** user data **/ private Object userData; /** * Constructs a new body with the given address * @param world the world * @param addr the address */ protected Body (World world, long addr) { this.world = world; this.addr = addr; } /** * Creates a fixture and attach it to this body. Use this function if you need to set some fixture parameters, like friction. * Otherwise you can create the fixture directly from a shape. If the density is non-zero, this function automatically updates * the mass of the body. Contacts are not created until the next time step. * @param def the fixture definition. * @warning This function is locked during callbacks. */ public Fixture createFixture (FixtureDef def) { Fixture fixture = new Fixture(this, jniCreateFixture(addr, def.shape.addr, def.friction, def.restitution, def.density, def.isSensor, def.filter.categoryBits, def.filter.maskBits, def.filter.groupIndex)); this.world.fixtures.put(fixture.addr, fixture); this.fixtures.add(fixture); return fixture; } private native long jniCreateFixture (long addr, long shapeAddr, float friction, float restitution, float density, boolean isSensor, short filterCategoryBits, short filterMaskBits, short filterGroupIndex); /** * Creates a fixture from a shape and attach it to this body. This is a convenience function. Use b2FixtureDef if you need to * set parameters like friction, restitution, user data, or filtering. If the density is non-zero, this function automatically * updates the mass of the body. * @param shape the shape to be cloned. * @param density the shape density (set to zero for static bodies). * @warning This function is locked during callbacks. */ public Fixture createFixture (Shape shape, float density) { Fixture fixture = new Fixture(this, jniCreateFixture(addr, shape.addr, density)); this.world.fixtures.put(fixture.addr, fixture); this.fixtures.add(fixture); return fixture; } private native long jniCreateFixture (long addr, long shapeAddr, float density); /** * Destroy a fixture. This removes the fixture from the broad-phase and destroys all contacts associated with this fixture. * This will automatically adjust the mass of the body if the body is dynamic and the fixture has positive density. All * fixtures attached to a body are implicitly destroyed when the body is destroyed. * @param fixture the fixture to be removed. * @warning This function is locked during callbacks. */ public void destroyFixture (Fixture fixture) { jniDestroyFixture(addr, fixture.addr); this.world.fixtures.remove(fixture.addr); this.fixtures.remove(fixture); } private native void jniDestroyFixture (long addr, long fixtureAddr); /** * Set the position of the body's origin and rotation. This breaks any contacts and wakes the other bodies. Manipulating a * body's transform may cause non-physical behavior. * @param position the world position of the body's local origin. * @param angle the world rotation in radians. */ public void setTransform (Vector2 position, float angle) { jniSetTransform(addr, position.x, position.y, angle); } /** * Set the position of the body's origin and rotation. This breaks any contacts and wakes the other bodies. Manipulating a * body's transform may cause non-physical behavior. * @param x the world position on the x-axis * @param y the world position on the y-axis * @param angle the world rotation in radians. */ public void setTransform(float x, float y, float angle) { jniSetTransform(addr, x, y, angle); } private native void jniSetTransform (long addr, float positionX, float positionY, float angle); /** * Get the body transform for the body's origin. FIXME */ private final Transform transform = new Transform(); public Transform getTransform () { jniGetTransform(addr, transform.vals); return transform; } private native void jniGetTransform (long addr, float[] vals); private final Vector2 position = new Vector2(); /** * Get the world body origin position. * @return the world position of the body's origin. */ public Vector2 getPosition () { jniGetPosition(addr, tmp); position.x = tmp[0]; position.y = tmp[1]; return position; } private native void jniGetPosition (long addr, float[] position); /** * Get the angle in radians. * @return the current world rotation angle in radians. */ public float getAngle () { return jniGetAngle(addr); } private native float jniGetAngle (long addr); /** * Get the world position of the center of mass. */ private final Vector2 worldCenter = new Vector2(); public Vector2 getWorldCenter () { jniGetWorldCenter(addr, tmp); worldCenter.x = tmp[0]; worldCenter.y = tmp[1]; return worldCenter; } private native void jniGetWorldCenter (long addr, float[] worldCenter); /** * Get the local position of the center of mass. */ private final Vector2 localCenter = new Vector2(); public Vector2 getLocalCenter () { jniGetLocalCenter(addr, tmp); localCenter.x = tmp[0]; localCenter.y = tmp[1]; return localCenter; } private native void jniGetLocalCenter (long addr, float[] localCenter); /** * Set the linear velocity of the center of mass. */ public void setLinearVelocity (Vector2 v) { jniSetLinearVelocity(addr, v.x, v.y); } /** * Set the linear velocity of the center of mass. */ public void setLinearVelocity (float vX, float vY) { jniSetLinearVelocity(addr, vX, vY); } private native void jniSetLinearVelocity (long addr, float x, float y); /** * Get the linear velocity of the center of mass. */ private final Vector2 linearVelocity = new Vector2(); public Vector2 getLinearVelocity () { jniGetLinearVelocity(addr, tmp); linearVelocity.x = tmp[0]; linearVelocity.y = tmp[1]; return linearVelocity; } private native void jniGetLinearVelocity (long addr, float[] tmpLinearVelocity); /** * Set the angular velocity. */ public void setAngularVelocity (float omega) { jniSetAngularVelocity(addr, omega); } private native void jniSetAngularVelocity (long addr, float omega); /** * Get the angular velocity. */ public float getAngularVelocity () { return jniGetAngularVelocity(addr); } private native float jniGetAngularVelocity (long addr); /** * Apply a force at a world point. If the force is not applied at the center of mass, it will generate a torque and affect the * angular velocity. This wakes up the body. * @param force the world force vector, usually in Newtons (N). * @param point the world position of the point of application. */ public void applyForce (Vector2 force, Vector2 point) { jniApplyForce(addr, force.x, force.y, point.x, point.y); } /** * Apply a force at a world point. If the force is not applied at the center of mass, it will generate a torque and affect the * angular velocity. This wakes up the body. * @param forceX the world force vector on x, usually in Newtons (N). * @param forceY the world force vector on y, usually in Newtons (N). * @param pointX the world position of the point of application on x. * @param pointY the world position of the point of application on y. */ public void applyForce (float forceX, float forceY, float pointX, float pointY) { jniApplyForce(addr, forceX, forceY, pointX, pointY); } private native void jniApplyForce (long addr, float forceX, float forceY, float pointX, float pointY); /** * Apply a torque. This affects the angular velocity without affecting the linear velocity of the center of mass. This wakes up * the body. * @param torque about the z-axis (out of the screen), usually in N-m. */ public void applyTorque (float torque) { jniApplyTorque(addr, torque); } private native void jniApplyTorque (long addr, float torque); /** * Apply an impulse at a point. This immediately modifies the velocity. It also modifies the angular velocity if the point of * application is not at the center of mass. This wakes up the body. * @param impulse the world impulse vector, usually in N-seconds or kg-m/s. * @param point the world position of the point of application. */ public void applyLinearImpulse (Vector2 impulse, Vector2 point) { jniApplyLinearImpulse(addr, impulse.x, impulse.y, point.x, point.y); } /** * Apply an impulse at a point. This immediately modifies the velocity. It also modifies the angular velocity if the point of * application is not at the center of mass. This wakes up the body. * @param impulseX the world impulse vector on the x-axis, usually in N-seconds or kg-m/s. * @param impulseY the world impulse vector on the y-axis, usually in N-seconds or kg-m/s. * @param pointX the world position of the point of application on the x-axis. * @param pointY the world position of the point of application on the y-axis. */ public void applyLinearImpulse(float impulseX, float impulseY, float pointX, float pointY) { jniApplyLinearImpulse(addr, impulseX, impulseY, pointX, pointY); } private native void jniApplyLinearImpulse (long addr, float impulseX, float impulseY, float pointX, float pointY); /** * Apply an angular impulse. * @param impulse the angular impulse in units of kg*m*m/s */ public void applyAngularImpulse (float impulse) { jniApplyAngularImpulse(addr, impulse); } private native void jniApplyAngularImpulse (long addr, float impulse); /** * Get the total mass of the body. * @return the mass, usually in kilograms (kg). */ public float getMass () { return jniGetMass(addr); } private native float jniGetMass (long addr); /** * Get the rotational inertia of the body about the local origin. * @return the rotational inertia, usually in kg-m^2. */ public float getInertia () { return jniGetInertia(addr); } private native float jniGetInertia (long addr); private final MassData massData = new MassData(); /** * Get the mass data of the body. * @return a struct containing the mass, inertia and center of the body. */ public MassData getMassData () { jniGetMassData(addr, tmp); massData.mass = tmp[0]; massData.center.x = tmp[1]; massData.center.y = tmp[2]; massData.I = tmp[3]; return massData; } private native void jniGetMassData (long addr, float[] massData); /** * Set the mass properties to override the mass properties of the fixtures. Note that this changes the center of mass position. * Note that creating or destroying fixtures can also alter the mass. This function has no effect if the body isn't dynamic. * @param data the mass properties. */ public void setMassData (MassData data) { jniSetMassData(addr, data.mass, data.center.x, data.center.y, data.I); } private native void jniSetMassData (long addr, float mass, float centerX, float centerY, float I); /** * This resets the mass properties to the sum of the mass properties of the fixtures. This normally does not need to be called * unless you called SetMassData to override the mass and you later want to reset the mass. */ public void resetMassData () { jniResetMassData(addr); } private native void jniResetMassData (long addr); private final Vector2 localPoint = new Vector2(); /** * Get the world coordinates of a point given the local coordinates. * @param localPoint a point on the body measured relative the the body's origin. * @return the same point expressed in world coordinates. */ public Vector2 getWorldPoint (Vector2 localPoint) { jniGetWorldPoint(addr, localPoint.x, localPoint.y, tmp); this.localPoint.x = tmp[0]; this.localPoint.y = tmp[1]; return this.localPoint; } private native void jniGetWorldPoint (long addr, float localPointX, float localPointY, float[] worldPoint); private final Vector2 worldVector = new Vector2(); /** * Get the world coordinates of a vector given the local coordinates. * @param localVector a vector fixed in the body. * @return the same vector expressed in world coordinates. */ public Vector2 getWorldVector (Vector2 localVector) { jniGetWorldVector(addr, localVector.x, localVector.y, tmp); worldVector.x = tmp[0]; worldVector.y = tmp[1]; return worldVector; } private native void jniGetWorldVector (long addr, float localVectorX, float localVectorY, float[] worldVector); public final Vector2 localPoint2 = new Vector2(); /** * Gets a local point relative to the body's origin given a world point. * @param worldPoint a point in world coordinates. * @return the corresponding local point relative to the body's origin. */ public Vector2 getLocalPoint (Vector2 worldPoint) { jniGetLocalPoint(addr, worldPoint.x, worldPoint.y, tmp); localPoint2.x = tmp[0]; localPoint2.y = tmp[1]; return localPoint2; } private native void jniGetLocalPoint (long addr, float worldPointX, float worldPointY, float[] localPoint); public final Vector2 localVector = new Vector2(); /** * Gets a local vector given a world vector. * @param worldVector a vector in world coordinates. * @return the corresponding local vector. */ public Vector2 getLocalVector (Vector2 worldVector) { jniGetLocalVector(addr, worldVector.x, worldVector.y, tmp); localVector.x = tmp[0]; localVector.y = tmp[1]; return localVector; } private native void jniGetLocalVector (long addr, float worldVectorX, float worldVectorY, float[] worldVector); public final Vector2 linVelWorld = new Vector2(); /** * Get the world linear velocity of a world point attached to this body. * @param worldPoint a point in world coordinates. * @return the world velocity of a point. */ public Vector2 getLinearVelocityFromWorldPoint (Vector2 worldPoint) { jniGetLinearVelocityFromWorldPoint(addr, worldPoint.x, worldPoint.y, tmp); linVelWorld.x = tmp[0]; linVelWorld.y = tmp[1]; return linVelWorld; } private native void jniGetLinearVelocityFromWorldPoint (long addr, float worldPointX, float worldPointY, float[] linVelWorld); public final Vector2 linVelLoc = new Vector2(); /** * Get the world velocity of a local point. * @param localPoint a point in local coordinates. * @return the world velocity of a point. */ public Vector2 getLinearVelocityFromLocalPoint (Vector2 localPoint) { jniGetLinearVelocityFromLocalPoint(addr, localPoint.x, localPoint.y, tmp); linVelLoc.x = tmp[0]; linVelLoc.y = tmp[1]; return linVelLoc; } private native void jniGetLinearVelocityFromLocalPoint (long addr, float localPointX, float localPointY, float[] linVelLoc); /** * Get the linear damping of the body. */ public float getLinearDamping () { return jniGetLinearDamping(addr); } private native float jniGetLinearDamping (long add); /** * Set the linear damping of the body. */ public void setLinearDamping (float linearDamping) { jniSetLinearDamping(addr, linearDamping); } private native void jniSetLinearDamping (long addr, float linearDamping); /** * Get the angular damping of the body. */ public float getAngularDamping () { return jniGetAngularDamping(addr); } private native float jniGetAngularDamping (long addr); /** * Set the angular damping of the body. */ public void setAngularDamping (float angularDamping) { jniSetAngularDamping(addr, angularDamping); } private native void jniSetAngularDamping (long addr, float angularDamping); /** * Set the type of this body. This may alter the mass and velocity. */ public void setType (BodyType type) { jniSetType(addr, type.getValue()); } private native void jniSetType (long addr, int type); /** * Get the type of this body. */ public BodyType getType () { int type = jniGetType(addr); if (type == 0) return BodyType.StaticBody; if (type == 1) return BodyType.KinematicBody; if (type == 2) return BodyType.DynamicBody; return BodyType.StaticBody; } private native int jniGetType (long addr); /** * Should this body be treated like a bullet for continuous collision detection? */ public void setBullet (boolean flag) { jniSetBullet(addr, flag); } private native void jniSetBullet (long addr, boolean flag); /** * Is this body treated like a bullet for continuous collision detection? */ public boolean isBullet () { return jniIsBullet(addr); } private native boolean jniIsBullet (long addr); /** * You can disable sleeping on this body. If you disable sleeping, the */ public void setSleepingAllowed (boolean flag) { jniSetSleepingAllowed(addr, flag); } private native void jniSetSleepingAllowed (long addr, boolean flag); /** * Is this body allowed to sleep */ public boolean isSleepingAllowed () { return jniIsSleepingAllowed(addr); } private native boolean jniIsSleepingAllowed (long addr); /** * Set the sleep state of the body. A sleeping body has very low CPU cost. * @param flag set to true to put body to sleep, false to wake it. */ public void setAwake (boolean flag) { jniSetAwake(addr, flag); } private native void jniSetAwake (long addr, boolean flag); /** * Get the sleeping state of this body. * @return true if the body is sleeping. */ public boolean isAwake () { return jniIsAwake(addr); } private native boolean jniIsAwake (long addr); /** * Set the active state of the body. An inactive body is not simulated and cannot be collided with or woken up. If you pass a * flag of true, all fixtures will be added to the broad-phase. If you pass a flag of false, all fixtures will be removed from * the broad-phase and all contacts will be destroyed. Fixtures and joints are otherwise unaffected. You may continue to * create/destroy fixtures and joints on inactive bodies. Fixtures on an inactive body are implicitly inactive and will not * participate in collisions, ray-casts, or queries. Joints connected to an inactive body are implicitly inactive. An inactive * body is still owned by a b2World object and remains in the body list. */ public void setActive (boolean flag) { jniSetActive(addr, flag); } private native void jniSetActive (long addr, boolean flag); /** * Get the active state of the body. */ public boolean isActive () { return jniIsActive(addr); } private native boolean jniIsActive (long addr); /** * Set this body to have fixed rotation. This causes the mass to be reset. */ public void setFixedRotation (boolean flag) { jniSetFixedRotation(addr, flag); } private native void jniSetFixedRotation (long addr, boolean flag); /** * Does this body have fixed rotation? */ public boolean isFixedRotation () { return jniIsFixedRotation(addr); } private native boolean jniIsFixedRotation (long addr); /** * Get the list of all fixtures attached to this body. Do not modify the list! */ public ArrayList<Fixture> getFixtureList () { return fixtures; } /** * Get the list of all joints attached to this body. Do not modify the list! */ public ArrayList<JointEdge> getJointList () { return joints; } /** * Get the list of all contacts attached to this body. * @warning this list changes during the time step and you may miss some collisions if you don't use b2ContactListener. Do not * modify the returned list! */ // ArrayList<ContactEdge> getContactList() // { // return contacts; // } /** * Get the parent world of this body. */ public World getWorld () { return world; } /** * Get the user data */ public Object getUserData () { return userData; } /** * Set the user data */ public void setUserData (Object userData) { this.userData = userData; } }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; /** * A circle shape. * @author mzechner * */ public class CircleShape extends Shape { public CircleShape () { addr = newCircleShape(); } private native long newCircleShape (); protected CircleShape (long addr) { this.addr = addr; } /** * {@inheritDoc} */ @Override public Type getType () { return Type.Circle; } /** * Returns the position of the shape */ private final float[] tmp = new float[2]; private final Vector2 position = new Vector2(); public Vector2 getPosition () { jniGetPosition(addr, tmp); position.x = tmp[0]; position.y = tmp[1]; return position; } private native void jniGetPosition (long addr, float[] position); /** * Sets the position of the shape */ public void setPosition (Vector2 position) { jniSetPosition(addr, position.x, position.y); } private native void jniSetPosition (long addr, float positionX, float positionY); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; /** * A shape is used for collision detection. You can create a shape however you like. Shapes used for simulation in b2World are * created automatically when a b2Fixture is created. * * NOTE: YOU NEED TO DISPOSE SHAPES AFTER YOU NO LONGER USE THEM! E.g. after calling body.createFixture(); * @author mzechner * */ public abstract class Shape { /** * Enum describing the type of a shape * @author mzechner * */ public enum Type { Circle, Polygon, }; /** the address of the shape **/ protected long addr; /** * Get the type of this shape. You can use this to down cast to the concrete shape. * @return the shape type. */ public abstract Type getType (); /** * Returns the radius of this shape */ public float getRadius () { return jniGetRadius(addr); } private native float jniGetRadius (long addr); /** * Sets the radius of this shape */ public void setRadius (float radius) { jniSetRadius(addr, radius); } private native void jniSetRadius (long addr, float radius); /** * Needs to be called when the shape is no longer used, e.g. after a fixture was created based on the shape. */ public void dispose () { jniDispose(addr); } private native void jniDispose (long addr); protected static native int jniGetType (long addr); // /// Test a point for containment in this shape. This only works for convex shapes. // /// @param xf the shape world transform. // /// @param p a point in world coordinates. // virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0; // // /// Cast a ray against this shape. // /// @param output the ray-cast results. // /// @param input the ray-cast input parameters. // /// @param transform the transform to be applied to the shape. // virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const = 0; // // /// Given a transform, compute the associated axis aligned bounding box for this shape. // /// @param aabb returns the axis aligned box. // /// @param xf the world transform of the shape. // virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf) const = 0; // // /// Compute the mass properties of this shape using its dimensions and density. // /// The inertia tensor is computed about the local origin. // /// @param massData returns the mass data for this shape. // /// @param density the density in kilograms per meter squared. // virtual void ComputeMass(b2MassData* massData, float32 density) const = 0; }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; /** * Callback class for ray casts. * @see World#rayCast(RayCastCallback, Vector2, Vector2) * @author mzechner * */ public interface RayCastCallback { /** Called for each fixture found in the query. You control how the ray cast proceeds by returning a float: return -1: ignore this fixture and continue return 0: terminate the ray cast return fraction: clip the ray to this point return 1: don't clip the ray and continue @param fixture the fixture hit by the ray @param point the point of initial intersection @param normal the normal vector at the point of intersection @return -1 to filter, 0 to terminate, fraction to clip the ray for closest hit, 1 to continue **/ public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.JointDef; /** * Friction joint definition. */ public class FrictionJointDef extends JointDef { public FrictionJointDef () { type = JointType.FrictionJoint; } /** * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. */ public void initialize (Body bodyA, Body bodyB, Vector2 anchor) { this.bodyA = bodyA; this.bodyB = bodyB; localAnchorA.set(bodyA.getLocalPoint(anchor)); localAnchorB.set(bodyB.getLocalPoint(anchor)); } /** * The local anchor point relative to bodyA's origin. */ public final Vector2 localAnchorA = new Vector2(); /** * The local anchor point relative to bodyB's origin. */ public final Vector2 localAnchorB = new Vector2(); /** * The maximum friction force in N. */ public float maxForce = 0; /** * The maximum friction torque in N-m. */ public float maxTorque = 0; }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.JointDef; public class WeldJointDef extends JointDef { public WeldJointDef () { type = JointType.WeldJoint; } // / Initialize the bodies, anchors, and reference angle using a world // / anchor point. public void initialize (Body body1, Body body2, Vector2 anchor) { this.bodyA = body1; this.bodyB = body2; this.localAnchorA.set(body1.getLocalPoint(anchor)); this.localAnchorB.set(body2.getLocalPoint(anchor)); referenceAngle = body2.getAngle() - body1.getAngle(); } // / The local anchor point relative to body1's origin. public final Vector2 localAnchorA = new Vector2(); // / The local anchor point relative to body2's origin. public final Vector2 localAnchorB = new Vector2(); // / The body2 angle minus body1 angle in the reference state (radians). public float referenceAngle = 0; }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** * A revolute joint constrains two bodies to share a common point while they are free to rotate about the point. The relative * rotation about the shared point is the joint angle. You can limit the relative rotation with a joint limit that specifies a * lower and upper angle. You can use a motor to drive the relative rotation about the shared point. A maximum motor torque is * provided so that infinite forces are not generated. */ public class RevoluteJoint extends Joint { public RevoluteJoint (World world, long addr) { super(world, addr); } /** * Get the current joint angle in radians. */ public float getJointAngle () { return jniGetJointAngle(addr); } private native float jniGetJointAngle (long addr); /** * Get the current joint angle speed in radians per second. */ public float getJointSpeed () { return jniGetJointSpeed(addr); } private native float jniGetJointSpeed (long addr); /** * Is the joint limit enabled? */ public boolean isLimitEnabled () { return jniIsLimitEnabled(addr); } private native boolean jniIsLimitEnabled (long addr); /** * Enable/disable the joint limit. */ public void enableLimit (boolean flag) { jniEnableLimit(addr, flag); } private native void jniEnableLimit (long addr, boolean flag); /** * Get the lower joint limit in radians. */ public float getLowerLimit () { return jniGetLowerLimit(addr); } private native float jniGetLowerLimit (long addr); /** * Get the upper joint limit in radians. */ public float getUpperLimit () { return jniGetUpperLimit(addr); } private native float jniGetUpperLimit (long addr); /** * Set the joint limits in radians. * @param upper */ public void setLimits (float lower, float upper) { jniSetLimits(addr, lower, upper); } private native void jniSetLimits (long addr, float lower, float upper); /** * Is the joint motor enabled? */ public boolean isMotorEnabled () { return jniIsMotorEnabled(addr); } private native boolean jniIsMotorEnabled (long addr); /** * Enable/disable the joint motor. */ public void enableMotor (boolean flag) { jniEnableMotor(addr, flag); } private native void jniEnableMotor (long addr, boolean flag); /** * Set the motor speed in radians per second. */ public void setMotorSpeed (float speed) { jniSetMotorSpeed(addr, speed); } private native void jniSetMotorSpeed (long addr, float speed); /** * Get the motor speed in radians per second. */ public float getMotorSpeed () { return jniGetMotorSpeed(addr); } private native float jniGetMotorSpeed (long addr); /** * Set the maximum motor torque, usually in N-m. */ public void setMaxMotorTorque (float torque) { jniSetMaxMotorTorque(addr, torque); } private native void jniSetMaxMotorTorque (long addr, float torque); /** * Get the current motor torque, usually in N-m. */ public float getMotorTorque () { return jniGetMotorTorque(addr); } private native float jniGetMotorTorque (long addr); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.JointDef; /** * Revolute joint definition. This requires defining an anchor point where the bodies are joined. The definition uses local anchor * points so that the initial configuration can violate the constraint slightly. You also need to specify the initial relative * angle for joint limits. This helps when saving and loading a game. The local anchor points are measured from the body's origin * rather than the center of mass because: 1. you might not know where the center of mass will be. 2. if you add/remove shapes * from a body and recompute the mass, the joints will be broken. */ public class RevoluteJointDef extends JointDef { public RevoluteJointDef () { type = JointType.RevoluteJoint; } /** * Initialize the bodies, anchors, and reference angle using a world anchor point. */ public void initialize (Body bodyA, Body bodyB, Vector2 anchor) { this.bodyA = bodyA; this.bodyB = bodyB; localAnchorA.set(bodyA.getLocalPoint(anchor)); localAnchorB.set(bodyB.getLocalPoint(anchor)); referenceAngle = bodyB.getAngle() - bodyA.getAngle(); } /** * The local anchor point relative to body1's origin. */ public final Vector2 localAnchorA = new Vector2(); /** * The local anchor point relative to body2's origin. */ public final Vector2 localAnchorB = new Vector2();; /** * The body2 angle minus body1 angle in the reference state (radians). */ public float referenceAngle = 0; /** * A flag to enable joint limits. */ public boolean enableLimit = false; /** * The lower angle for the joint limit (radians). */ public float lowerAngle = 0; /** * The upper angle for the joint limit (radians). */ public float upperAngle = 0; /** * A flag to enable the joint motor. */ public boolean enableMotor = false; /** * The desired motor speed. Usually in radians per second. */ public float motorSpeed = 0; /** * The maximum motor torque used to achieve the desired motor speed. Usually in N-m. */ public float maxMotorTorque = 0; }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** * The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a ratio such that: length1 + ratio * * length2 <= constant Yes, the force transmitted is scaled by the ratio. The pulley also enforces a maximum length limit on * both sides. This is useful to prevent one side of the pulley hitting the top. */ public class PulleyJoint extends Joint { public PulleyJoint (World world, long addr) { super(world, addr); } /** * Get the first ground anchor. */ private final float[] tmp = new float[2]; private final Vector2 groundAnchorA = new Vector2(); public Vector2 getGroundAnchorA () { jniGetGroundAnchorA(addr, tmp); groundAnchorA.set(tmp[0], tmp[1]); return groundAnchorA; } private native void jniGetGroundAnchorA (long addr, float[] anchor); /** * Get the second ground anchor. */ private final Vector2 groundAnchorB = new Vector2(); public Vector2 getGroundAnchorB () { jniGetGroundAnchorB(addr, tmp); groundAnchorB.set(tmp[0], tmp[1]); return groundAnchorB; } private native void jniGetGroundAnchorB (long addr, float[] anchor); /** * Get the current length of the segment attached to body1. */ public float getLength1 () { return jniGetLength1(addr); } private native float jniGetLength1 (long addr); /** * Get the current length of the segment attached to body2. */ public float getLength2 () { return jniGetLength2(addr); } private native float jniGetLength2 (long addr); /** * Get the pulley ratio. */ public float getRatio () { return jniGetRatio(addr); } private native float jniGetRatio (long addr); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** * A distance joint constrains two points on two bodies to remain at a fixed distance from each other. You can view this as a * massless, rigid rod. */ public class DistanceJoint extends Joint { public DistanceJoint (World world, long addr) { super(world, addr); } /** * Set/get the natural length. Manipulating the length can lead to non-physical behavior when the frequency is zero. */ public void setLength (float length) { jniSetLength(addr, length); } private native void jniSetLength (long addr, float length); /** * Set/get the natural length. Manipulating the length can lead to non-physical behavior when the frequency is zero. */ public float getLength () { return jniGetLength(addr); } private native float jniGetLength (long addr); /** * Set/get frequency in Hz. */ public void setFrequency (float hz) { jniSetFrequency(addr, hz); } private native void jniSetFrequency (long addr, float hz); /** * Set/get frequency in Hz. */ public float getFrequency () { return jniGetFrequency(addr); } private native float jniGetFrequency (long addr); /** * Set/get damping ratio. */ public void setDampingRatio (float ratio) { jniSetDampingRatio(addr, ratio); } private native void jniSetDampingRatio (long addr, float ratio); /** * Set/get damping ratio. */ public float getDampingRatio () { return jniGetDampingRatio(addr); } private native float jniGetDampingRatio (long addr); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** * A gear joint is used to connect two joints together. Either joint can be a revolute or prismatic joint. You specify a gear * ratio to bind the motions together: coordinate1 + ratio * coordinate2 = constant The ratio can be negative or positive. If one * joint is a revolute joint and the other joint is a prismatic joint, then the ratio will have units of length or units of * 1/length. * @warning The revolute and prismatic joints must be attached to fixed bodies (which must be body1 on those joints). */ public class GearJoint extends Joint { public GearJoint (World world, long addr) { super(world, addr); } /** * Set/Get the gear ratio. */ public void setRatio (float ratio) { jniSetRatio(addr, ratio); } private native void jniSetRatio (long addr, float ratio); /** * Set/Get the gear ratio. */ public float getRatio () { return jniGetRatio(addr); } private native float jniGetRatio (long addr); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.JointDef; /** * Pulley joint definition. This requires two ground anchors, two dynamic body anchor points, max lengths for each side, and a * pulley ratio. */ public class PulleyJointDef extends JointDef { private final static float minPulleyLength = 2.0f; public PulleyJointDef () { type = JointType.PulleyJoint; collideConnected = true; } /** * Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors. */ public void initialize (Body bodyA, Body bodyB, Vector2 groundAnchorA, Vector2 groundAnchorB, Vector2 anchorA, Vector2 anchorB, float ratio) { this.bodyA = bodyA; this.bodyB = bodyB; this.groundAnchorA.set(groundAnchorA); this.groundAnchorB.set(groundAnchorB); this.localAnchorA.set(bodyA.getLocalPoint(anchorA)); this.localAnchorB.set(bodyB.getLocalPoint(anchorB)); lengthA = anchorA.dst(groundAnchorA); lengthB = anchorB.dst(groundAnchorB); this.ratio = ratio; float C = lengthA + ratio * lengthB; maxLengthA = C - ratio * minPulleyLength; maxLengthB = (C - minPulleyLength) / ratio; } /** * The first ground anchor in world coordinates. This point never moves. */ public final Vector2 groundAnchorA = new Vector2(-1, 1); /** * The second ground anchor in world coordinates. This point never moves. */ public final Vector2 groundAnchorB = new Vector2(1, 1); /** * The local anchor point relative to bodyA's origin. */ public final Vector2 localAnchorA = new Vector2(-1, 0); /** * The local anchor point relative to bodyB's origin. */ public final Vector2 localAnchorB = new Vector2(1, 0); /** * The a reference length for the segment attached to bodyA. */ public float lengthA = 0; /** * The maximum length of the segment attached to bodyA. */ public float maxLengthA = 0; /** * The a reference length for the segment attached to bodyB. */ public float lengthB = 0; /** * The maximum length of the segment attached to bodyB. */ public float maxLengthB = 0; /** * The pulley ratio, used to simulate a block-and-tackle. */ public float ratio = 1; }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** * A prismatic joint. This joint provides one degree of freedom: translation along an axis fixed in body1. Relative rotation is * prevented. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint * friction. */ public class PrismaticJoint extends Joint { public PrismaticJoint (World world, long addr) { super(world, addr); } /** * Get the current joint translation, usually in meters. */ public float getJointTranslation () { return jniGetJointTranslation(addr); } private native float jniGetJointTranslation (long addr); /** * Get the current joint translation speed, usually in meters per second. */ public float getJointSpeed () { return jniGetJointSpeed(addr); } private native float jniGetJointSpeed (long addr); /** * Is the joint limit enabled? */ public boolean isLimitEnabled () { return jniIsLimitEnabled(addr); } private native boolean jniIsLimitEnabled (long addr); /** * Enable/disable the joint limit. */ public void enableLimit (boolean flag) { jniEnableLimit(addr, flag); } private native void jniEnableLimit (long addr, boolean flag); /** * Get the lower joint limit, usually in meters. */ public float getLowerLimit () { return jniGetLowerLimit(addr); } private native float jniGetLowerLimit (long addr); /** * Get the upper joint limit, usually in meters. */ public float getUpperLimit () { return jniGetUpperLimit(addr); } private native float jniGetUpperLimit (long addr); /** * Set the joint limits, usually in meters. */ public void setLimits (float lower, float upper) { jniSetLimits(addr, lower, upper); } private native void jniSetLimits (long addr, float lower, float upper); /** * Is the joint motor enabled? */ public boolean isMotorEnabled () { return jniIsMotorEnabled(addr); } private native boolean jniIsMotorEnabled (long addr); /** * Enable/disable the joint motor. */ public void enableMotor (boolean flag) { jniEnableMotor(addr, flag); } private native void jniEnableMotor (long addr, boolean flag); /** * Set the motor speed, usually in meters per second. */ public void setMotorSpeed (float speed) { jniSetMotorSpeed(addr, speed); } private native void jniSetMotorSpeed (long addr, float speed); /** * Get the motor speed, usually in meters per second. */ public float getMotorSpeed () { return jniGetMotorSpeed(addr); } private native float jniGetMotorSpeed (long addr); /** * Set the maximum motor force, usually in N. */ public void setMaxMotorForce (float force) { jniSetMaxMotorForce(addr, force); } private native void jniSetMaxMotorForce (long addr, float force); /** * Get the current motor force, usually in N. */ public float getMotorForce () { return jniGetMotorForce(addr); } private native float jniGetMotorForce (long addr); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.JointDef; /** * Gear joint definition. This definition requires two existing revolute or prismatic joints (any combination will work). The * provided joints must attach a dynamic body to a static body. */ public class GearJointDef extends JointDef { public GearJointDef () { type = JointType.GearJoint; } /** * The first revolute/prismatic joint attached to the gear joint. */ public Joint joint1 = null; /** * The second revolute/prismatic joint attached to the gear joint. */ public Joint joint2 = null; /** * The gear ratio. * @see GearJoint for explanation. */ public float ratio = 1; }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** * A weld joint essentially glues two bodies together. A weld joint may distort somewhat because the island constraint solver is * approximate. */ public class WeldJoint extends Joint { public WeldJoint (World world, long addr) { super(world, addr); } }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.JointDef; /** * Prismatic joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses * local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint * translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when * saving and loading a game. * @warning at least one body should by dynamic with a non-fixed rotation. */ public class PrismaticJointDef extends JointDef { public PrismaticJointDef () { type = JointType.PrismaticJoint; } /** * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. */ public void initialize (Body bodyA, Body bodyB, Vector2 anchor, Vector2 axis) { this.bodyA = bodyA; this.bodyB = bodyB; localAnchorA.set(bodyA.getLocalPoint(anchor)); localAnchorB.set(bodyB.getLocalPoint(anchor)); localAxis1.set(bodyA.getLocalVector(axis)); referenceAngle = bodyB.getAngle() - bodyA.getAngle(); } /** * The local anchor point relative to body1's origin. */ public final Vector2 localAnchorA = new Vector2(); /** * The local anchor point relative to body2's origin. */ public final Vector2 localAnchorB = new Vector2(); /** * The local translation axis in body1. */ public final Vector2 localAxis1 = new Vector2(1, 0); /** * The constrained angle between the bodies: body2_angle - body1_angle. */ public float referenceAngle = 0; /** * Enable/disable the joint limit. */ public boolean enableLimit = false; /** * The lower translation limit, usually in meters. */ public float lowerTranslation = 0; /** * The upper translation limit, usually in meters. */ public float upperTranslation = 0; /** * Enable/disable the joint motor. */ public boolean enableMotor = false; /** * The maximum motor torque, usually in N-m. */ public float maxMotorForce = 0; /** * The desired motor speed in radians per second. */ public float motorSpeed = 0; }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.JointDef; /** * Mouse joint definition. This requires a world target point, tuning parameters, and the time step. */ public class MouseJointDef extends JointDef { public MouseJointDef () { type = JointType.MouseJoint; } /** * The initial world target point. This is assumed to coincide with the body anchor initially. */ public final Vector2 target = new Vector2(); /** * The maximum constraint force that can be exerted to move the candidate body. Usually you will express as some multiple of * the weight (multiplier * mass * gravity). */ public float maxForce = 0; /** * The response speed. */ public float frequencyHz = 5.0f; /** * The damping ratio. 0 = no damping, 1 = critical damping. */ public float dampingRatio = 0.7f; }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** * A line joint. This joint provides two degrees of freedom: translation along an axis fixed in body1 and rotation in the plane. * You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint friction. */ public class LineJoint extends Joint { public LineJoint (World world, long addr) { super(world, addr); } /** * Get the current joint translation, usually in meters. */ public float getJointTranslation () { return jniGetJointTranslation(addr); } private native float jniGetJointTranslation (long addr); /** * Get the current joint translation speed, usually in meters per second. */ public float getJointSpeed () { return jniGetJointSpeed(addr); } private native float jniGetJointSpeed (long addr); /** * Is the joint limit enabled? */ public boolean isLimitEnabled () { return jniIsLimitEnabled(addr); } private native boolean jniIsLimitEnabled (long addr); /** * Enable/disable the joint limit. */ public void enableLimit (boolean flag) { jniEnableLimit(addr, flag); } private native void jniEnableLimit (long addr, boolean flag); /** * Get the lower joint limit, usually in meters. */ public float getLowerLimit () { return jniGetLowerLimit(addr); } private native float jniGetLowerLimit (long addr); /** * Get the upper joint limit, usually in meters. */ public float getUpperLimit () { return jniGetUpperLimit(addr); } private native float jniGetUpperLimit (long addr); /** * Set the joint limits, usually in meters. */ public void setLimits (float lower, float upper) { jniSetLimits(addr, lower, upper); } private native void jniSetLimits (long addr, float lower, float upper); /** * Is the joint motor enabled? */ public boolean isMotorEnabled () { return jniIsMotorEnabled(addr); } private native boolean jniIsMotorEnabled (long addr); /** * Enable/disable the joint motor. */ public void enableMotor (boolean flag) { jniEnableMotor(addr, flag); } private native void jniEnableMotor (long addr, boolean flag); /** * Set the motor speed, usually in meters per second. */ public void setMotorSpeed (float speed) { jniSetMotorSpeed(addr, speed); } private native void jniSetMotorSpeed (long addr, float speed); /** * Get the motor speed, usually in meters per second. */ public float getMotorSpeed () { return jniGetMotorSpeed(addr); } private native float jniGetMotorSpeed (long addr); /** * Set/Get the maximum motor force, usually in N. */ public void setMaxMotorForce (float force) { jniSetMaxMotorForce(addr, force); } private native void jniSetMaxMotorForce (long addr, float force); /** * Set/Get the maximum motor force, usually in N. FIXME returns 0 at the moment due to a linking problem. */ public float getMaxMotorForce () { return jniGetMaxMotorForce(addr); } private native float jniGetMaxMotorForce (long addr); /** * Get the current motor force, usually in N. */ public float getMotorForce () { return jniGetMotorForce(addr); } private native float jniGetMotorForce (long addr); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.JointDef; /** * Line joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local * anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is * zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a * game. */ public class LineJointDef extends JointDef { public LineJointDef () { type = JointType.LineJoint; } /** * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. */ public void initialize (Body bodyA, Body bodyB, Vector2 anchor, Vector2 axis) { this.bodyA = bodyA; this.bodyB = bodyB; localAnchorA.set(bodyA.getLocalPoint(anchor)); localAnchorB.set(bodyB.getLocalPoint(anchor)); localAxisA.set(bodyA.getLocalVector(axis)); } /** * The local anchor point relative to body1's origin. */ public final Vector2 localAnchorA = new Vector2(); /** * The local anchor point relative to body2's origin. */ public final Vector2 localAnchorB = new Vector2(); /** * The local translation axis in body1. */ public final Vector2 localAxisA = new Vector2(1.0f, 0); /** * Enable/disable the joint limit. */ public boolean enableLimit = false; /** * The lower translation limit, usually in meters. */ public float lowerTranslation = 0; /** * The upper translation limit, usually in meters. */ public float upperTranslation = 0; /** * Enable/disable the joint motor. */ public boolean enableMotor = false; /** * The maximum motor torque, usually in N-m. */ public float maxMotorForce = 0; /** * The desired motor speed in radians per second. */ public float motorSpeed = 0; }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** * A mouse joint is used to make a point on a body track a specified world point. This a soft constraint with a maximum force. * This allows the constraint to stretch and without applying huge forces. NOTE: this joint is not documented in the manual * because it was developed to be used in the testbed. If you want to learn how to use the mouse joint, look at the testbed. */ public class MouseJoint extends Joint { public MouseJoint (World world, long addr) { super(world, addr); } /** * Use this to update the target point. */ public void setTarget (Vector2 target) { jniSetTarget(addr, target.x, target.y); } private native void jniSetTarget (long addr, float x, float y); /** * Use this to update the target point. */ final float[] tmp = new float[2]; private final Vector2 target = new Vector2(); public Vector2 getTarget () { jniGetTarget(addr, tmp); target.x = tmp[0]; target.y = tmp[1]; return target; } private native void jniGetTarget (long addr, float[] target); /** * Set/get the maximum force in Newtons. */ public void setMaxForce (float force) { jniSetMaxForce(addr, force); } private native void jniSetMaxForce (long addr, float force); /** * Set/get the maximum force in Newtons. */ public float getMaxForce () { return jniGetMaxForce(addr); } private native float jniGetMaxForce (long addr); /** * Set/get the frequency in Hertz. */ public void setFrequency (float hz) { jniSetFrequency(addr, hz); } private native void jniSetFrequency (long addr, float hz); /** * Set/get the frequency in Hertz. */ public float getFrequency () { return jniGetFrequency(addr); } private native float jniGetFrequency (long addr); /** * Set/get the damping ratio (dimensionless). */ public void setDampingRatio (float ratio) { jniSetDampingRatio(addr, ratio); } private native void jniSetDampingRatio (long addr, float ratio); /** * Set/get the damping ratio (dimensionless). */ public float getDampingRatio () { return jniGetDampingRatio(addr); } private native float jniGetDampingRatio (long addr); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.JointDef; /** * Distance joint definition. This requires defining an anchor point on both bodies and the non-zero length of the distance joint. * The definition uses local anchor points so that the initial configuration can violate the constraint slightly. This helps when * saving and loading a game. * @warning Do not use a zero or short length. */ public class DistanceJointDef extends JointDef { public DistanceJointDef () { type = JointType.DistanceJoint; } /** * Initialize the bodies, anchors, and length using the world anchors. */ public void initialize (Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB) { this.bodyA = bodyA; this.bodyB = bodyB; this.localAnchorA.set(bodyA.getLocalPoint(anchorA)); this.localAnchorB.set(bodyB.getLocalPoint(anchorB)); this.length = anchorA.dst(anchorB); } /** * The local anchor point relative to body1's origin. */ public final Vector2 localAnchorA = new Vector2(); /** * The local anchor point relative to body2's origin. */ public final Vector2 localAnchorB = new Vector2(); /** * The natural length between the anchor points. */ public float length = 1; /** * The mass-spring-damper frequency in Hertz. */ public float frequencyHz = 0; /** * The damping ratio. 0 = no damping, 1 = critical damping. */ public float dampingRatio = 0; }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** * Friction joint. This is used for top-down friction. It provides 2D translational friction and angular friction. */ public class FrictionJoint extends Joint { public FrictionJoint (World world, long addr) { super(world, addr); } /** * Set the maximum friction force in N. */ public void setMaxForce (float force) { jniSetMaxForce(addr, force); } private native void jniSetMaxForce (long ddr, float force); /** * Get the maximum friction force in N. */ public float getMaxForce () { return jniGetMaxForce(addr); } private native float jniGetMaxForce (long addr); /** * Set the maximum friction torque in N*m. */ public void setMaxTorque (float torque) { jniSetMaxTorque(addr, torque); } private native void jniSetMaxTorque (long addr, float torque); /** * Get the maximum friction torque in N*m. */ public float getMaxTorque () { return jniGetMaxTorque(addr); } private native float jniGetMaxTorque (long addr); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; /** * Implement this class to provide collision filtering. In other words, you can implement this class if you want finer control * over contact creation. * @author mzechner * */ public interface ContactFilter { boolean shouldCollide (Fixture fixtureA, Fixture fixtureB); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.JointDef.JointType; public abstract class Joint { /** the address of the joint **/ protected long addr; /** world **/ private final World world; /** temporary float array **/ private final float[] tmp = new float[2]; /** joint edge a **/ protected JointEdge jointEdgeA; /** joint edge b **/ protected JointEdge jointEdgeB; /** * Constructs a new joint * @param addr the address of the joint */ protected Joint (World world, long addr) { this.world = world; this.addr = addr; } /** * Get the type of the concrete joint. */ public JointType getType () { int type = jniGetType(addr); if (type > 0 && type < JointType.valueTypes.length) return JointType.valueTypes[type]; else return JointType.Unknown; } private native int jniGetType (long addr); /** * Get the first body attached to this joint. */ public Body getBodyA () { return world.bodies.get(jniGetBodyA(addr)); } private native long jniGetBodyA (long addr); /** * Get the second body attached to this joint. */ public Body getBodyB () { return world.bodies.get(jniGetBodyB(addr)); } private native long jniGetBodyB (long addr); /** * Get the anchor point on bodyA in world coordinates. */ private final Vector2 anchorA = new Vector2(); public Vector2 getAnchorA () { jniGetAnchorA(addr, tmp); anchorA.x = tmp[0]; anchorA.y = tmp[1]; return anchorA; } private native void jniGetAnchorA (long addr, float[] anchorA); /** * Get the anchor point on bodyB in world coordinates. */ private final Vector2 anchorB = new Vector2(); public Vector2 getAnchorB () { jniGetAnchorB(addr, tmp); anchorB.x = tmp[0]; anchorB.y = tmp[1]; return anchorB; } private native void jniGetAnchorB (long addr, float[] anchorB); /** * Get the reaction force on body2 at the joint anchor in Newtons. */ private final Vector2 reactionForce = new Vector2(); public Vector2 getReactionForce (float inv_dt) { jniGetReactionForce(addr, inv_dt, tmp); reactionForce.x = tmp[0]; reactionForce.y = tmp[1]; return reactionForce; } private native void jniGetReactionForce (long addr, float inv_dt, float[] reactionForce); /** * Get the reaction torque on body2 in N*m. */ public float getReactionTorque (float inv_dt) { return jniGetReactionTorque(addr, inv_dt); } private native float jniGetReactionTorque (long addr, float inv_dt); // /// Get the next joint the world joint list. // b2Joint* GetNext(); // // /// Get the user data pointer. // void* GetUserData() const; // // /// Set the user data pointer. // void SetUserData(void* data); /** * Short-cut function to determine if either body is inactive. */ public boolean isActive () { return jniIsActive(addr); } private native boolean jniIsActive (long addr); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.JointDef.JointType; import com.badlogic.gdx.physics.box2d.joints.DistanceJoint; import com.badlogic.gdx.physics.box2d.joints.DistanceJointDef; import com.badlogic.gdx.physics.box2d.joints.FrictionJoint; import com.badlogic.gdx.physics.box2d.joints.FrictionJointDef; import com.badlogic.gdx.physics.box2d.joints.GearJoint; import com.badlogic.gdx.physics.box2d.joints.GearJointDef; import com.badlogic.gdx.physics.box2d.joints.LineJoint; import com.badlogic.gdx.physics.box2d.joints.LineJointDef; import com.badlogic.gdx.physics.box2d.joints.MouseJoint; import com.badlogic.gdx.physics.box2d.joints.MouseJointDef; import com.badlogic.gdx.physics.box2d.joints.PrismaticJoint; import com.badlogic.gdx.physics.box2d.joints.PrismaticJointDef; import com.badlogic.gdx.physics.box2d.joints.PulleyJoint; import com.badlogic.gdx.physics.box2d.joints.PulleyJointDef; import com.badlogic.gdx.physics.box2d.joints.RevoluteJoint; import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef; import com.badlogic.gdx.physics.box2d.joints.WeldJoint; import com.badlogic.gdx.physics.box2d.joints.WeldJointDef; import com.badlogic.gdx.utils.LongMap; /** * The world class manages all physics entities, dynamic simulation, and asynchronous queries. The world also contains efficient * memory management facilities. * @author mzechner */ public class World { /** the address of the world instance **/ private final long addr; /** all known bodies **/ protected final LongMap<Body> bodies = new LongMap<Body>(100); /** all known fixtures **/ protected final LongMap<Fixture> fixtures = new LongMap<Fixture>(100); /** all known joints **/ protected final LongMap<Joint> joints = new LongMap<Joint>(100); /** Contact filter **/ protected ContactFilter contactFilter = null; /** Contact listener **/ protected ContactListener contactListener = null; /** * Ray-cast the world for all fixtures in the path of the ray. * The ray-cast ignores shapes that contain the starting point. * @param callback a user implemented callback class. * @param point1 the ray starting point * @param point2 the ray ending point */ public void rayCast(RayCastCallback callback, Vector2 point1, Vector2 point2) { rayCastCallback = callback; jniRayCast(addr, point1.x, point1.y, point2.x, point2.y); } private RayCastCallback rayCastCallback = null; private native void jniRayCast (long addr, float aX, float aY, float bX, float bY); private Vector2 rayPoint = new Vector2(); private Vector2 rayNormal = new Vector2(); private float reportRayFixture (long addr, float pX, float pY, float nX, float nY, float fraction) { if (rayCastCallback != null) return rayCastCallback.reportRayFixture(fixtures.get(addr), rayPoint.set(pX, pY), rayNormal.set(nX, nY), fraction); else return 0.0f; } /** * Construct a world object. * @param gravity the world gravity vector. * @param doSleep improve performance by not simulating inactive bodies. */ public World (Vector2 gravity, boolean doSleep) { addr = newWorld(gravity.x, gravity.y, doSleep); for (int i = 0; i < 200; i++) freeContacts.add(new Contact(this, 0)); } private native long newWorld (float gravityX, float gravityY, boolean doSleep); /** * Register a destruction listener. The listener is owned by you and must remain in scope. */ public void setDestructionListener (DestructionListener listener) { } /** * Register a contact filter to provide specific control over collision. Otherwise the default filter is used * (b2_defaultFilter). The listener is owned by you and must remain in scope. */ public void setContactFilter (ContactFilter filter) { this.contactFilter = filter; } /** * Register a contact event listener. The listener is owned by you and must remain in scope. */ public void setContactListener (ContactListener listener) { this.contactListener = listener; } /** * Create a rigid body given a definition. No reference to the definition is retained. * @warning This function is locked during callbacks. */ public Body createBody (BodyDef def) { Body body = new Body(this, jniCreateBody(addr, def.type.getValue(), def.position.x, def.position.y, def.angle, def.linearVelocity.x, def.linearVelocity.y, def.angularVelocity, def.linearDamping, def.angularDamping, def.allowSleep, def.awake, def.fixedRotation, def.bullet, def.active, def.inertiaScale)); this.bodies.put(body.addr, body); return body; } private native long jniCreateBody (long addr, int type, float positionX, float positionY, float angle, float linearVelocityX, float linearVelocityY, float angularVelocity, float linearDamping, float angularDamping, boolean allowSleep, boolean awake, boolean fixedRotation, boolean bullet, boolean active, float intertiaScale); /** * Destroy a rigid body given a definition. No reference to the definition is retained. This function is locked during * callbacks. * @warning This automatically deletes all associated shapes and joints. * @warning This function is locked during callbacks. */ public void destroyBody (Body body) { this.bodies.remove(body.addr); for (int i = 0; i < body.getFixtureList().size(); i++) this.fixtures.remove(body.getFixtureList().get(i).addr); for (int i = 0; i < body.getJointList().size(); i++) this.joints.remove(body.getJointList().get(i).joint.addr); jniDestroyBody(addr, body.addr); } private native void jniDestroyBody (long addr, long bodyAddr); /** * Create a joint to constrain bodies together. No reference to the definition is retained. This may cause the connected bodies * to cease colliding. * @warning This function is locked during callbacks. */ public Joint createJoint (JointDef def) { long jointAddr = createProperJoint(def); Joint joint = null; if (def.type == JointType.DistanceJoint) joint = new DistanceJoint(this, jointAddr); if (def.type == JointType.FrictionJoint) joint = new FrictionJoint(this, jointAddr); if (def.type == JointType.GearJoint) joint = new GearJoint(this, jointAddr); if (def.type == JointType.LineJoint) joint = new LineJoint(this, jointAddr); if (def.type == JointType.MouseJoint) joint = new MouseJoint(this, jointAddr); if (def.type == JointType.PrismaticJoint) joint = new PrismaticJoint(this, jointAddr); if (def.type == JointType.PulleyJoint) joint = new PulleyJoint(this, jointAddr); if (def.type == JointType.RevoluteJoint) joint = new RevoluteJoint(this, jointAddr); if (def.type == JointType.WeldJoint) joint = new WeldJoint(this, jointAddr); if (joint != null) joints.put(joint.addr, joint); JointEdge jointEdgeA = new JointEdge(def.bodyB, joint); JointEdge jointEdgeB = new JointEdge(def.bodyA, joint); joint.jointEdgeA = jointEdgeA; joint.jointEdgeB = jointEdgeB; def.bodyA.joints.add(jointEdgeA); def.bodyB.joints.add(jointEdgeB); return joint; } private long createProperJoint (JointDef def) { if (def.type == JointType.DistanceJoint) { DistanceJointDef d = (DistanceJointDef)def; return jniCreateDistanceJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.length, d.frequencyHz, d.dampingRatio); } if (def.type == JointType.FrictionJoint) { FrictionJointDef d = (FrictionJointDef)def; return jniCreateFrictionJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.maxForce, d.maxTorque); } if (def.type == JointType.GearJoint) { GearJointDef d = (GearJointDef)def; return jniCreateGearJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.joint1.addr, d.joint2.addr, d.ratio); } if (def.type == JointType.LineJoint) { LineJointDef d = (LineJointDef)def; return jniCreateLineJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.localAxisA.x, d.localAxisA.y, d.enableLimit, d.lowerTranslation, d.upperTranslation, d.enableMotor, d.maxMotorForce, d.motorSpeed); } if (def.type == JointType.MouseJoint) { MouseJointDef d = (MouseJointDef)def; return jniCreateMouseJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.target.x, d.target.y, d.maxForce, d.frequencyHz, d.dampingRatio); } if (def.type == JointType.PrismaticJoint) { PrismaticJointDef d = (PrismaticJointDef)def; return jniCreatePrismaticJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.localAxis1.x, d.localAxis1.y, d.referenceAngle, d.enableLimit, d.lowerTranslation, d.upperTranslation, d.enableMotor, d.maxMotorForce, d.motorSpeed); } if (def.type == JointType.PulleyJoint) { PulleyJointDef d = (PulleyJointDef)def; return jniCreatePulleyJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.groundAnchorA.x, d.groundAnchorA.y, d.groundAnchorB.x, d.groundAnchorB.y, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.lengthA, d.maxLengthA, d.lengthB, d.maxLengthB, d.ratio); } if (def.type == JointType.RevoluteJoint) { RevoluteJointDef d = (RevoluteJointDef)def; return jniCreateRevoluteJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.referenceAngle, d.enableLimit, d.lowerAngle, d.upperAngle, d.enableMotor, d.motorSpeed, d.maxMotorTorque); } if (def.type == JointType.WeldJoint) { WeldJointDef d = (WeldJointDef)def; return jniCreateWeldJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.referenceAngle); } return 0; } private native long jniCreateDistanceJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float length, float frequencyHz, float dampingRatio); private native long jniCreateFrictionJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float maxForce, float maxTorque); private native long jniCreateGearJoint (long addr, long bodyA, long bodyB, boolean collideConnected, long joint1, long joint2, float ratio); private native long jniCreateLineJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float localAxisAX, float localAxisAY, boolean enableLimit, float lowerTranslation, float upperTranslation, boolean enableMotor, float maxMotorForce, float motorSpeed); private native long jniCreateMouseJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float targetX, float targetY, float maxForce, float frequencyHz, float dampingRatio); private native long jniCreatePrismaticJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float localAxisAX, float localAxisAY, float referenceAngle, boolean enableLimit, float lowerTranslation, float upperTranslation, boolean enableMotor, float maxMotorForce, float motorSpeed); private native long jniCreatePulleyJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float groundAnchorAX, float groundAnchorAY, float groundAnchorBX, float groundAnchorBY, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float lengthA, float maxLengthA, float lengthB, float maxLengthB, float ratio); private native long jniCreateRevoluteJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float referenceAngle, boolean enableLimit, float lowerAngle, float upperAngle, boolean enableMotor, float motorSpeed, float maxMotorTorque); private native long jniCreateWeldJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float referenceAngle); /** * Destroy a joint. This may cause the connected bodies to begin colliding. * @warning This function is locked during callbacks. */ public void destroyJoint (Joint joint) { joints.remove(joint.addr); joint.jointEdgeA.other.joints.remove(joint.jointEdgeB); joint.jointEdgeB.other.joints.remove(joint.jointEdgeA); jniDestroyJoint(addr, joint.addr); } private native void jniDestroyJoint (long addr, long jointAddr); /** * Take a time step. This performs collision detection, integration, and constraint solution. * @param timeStep the amount of time to simulate, this should not vary. * @param velocityIterations for the velocity constraint solver. * @param positionIterations for the position constraint solver. */ public void step (float timeStep, int velocityIterations, int positionIterations) { jniStep(addr, timeStep, velocityIterations, positionIterations); } private native void jniStep (long addr, float timeStep, int velocityIterations, int positionIterations); /** * Call this after you are done with time steps to clear the forces. You normally call this after each call to Step, unless you * are performing sub-steps. By default, forces will be automatically cleared, so you don't need to call this function. See * {@link #setAutoClearForces(boolean)} */ public void clearForces () { jniClearForces(addr); } private native void jniClearForces (long addr); /** * Enable/disable warm starting. For testing. */ public void setWarmStarting (boolean flag) { jniSetWarmStarting(addr, flag); } private native void jniSetWarmStarting (long addr, boolean flag); /** * Enable/disable continuous physics. For testing. */ public void setContinuousPhysics (boolean flag) { jniSetContiousPhysics(addr, flag); } private native void jniSetContiousPhysics (long addr, boolean flag); /** * Get the number of broad-phase proxies. */ public int getProxyCount () { return jniGetProxyCount(addr); } private native int jniGetProxyCount (long addr); /** * Get the number of bodies. */ public int getBodyCount () { return jniGetBodyCount(addr); } private native int jniGetBodyCount (long addr); /** * Get the number of joints. */ public int getJointCount () { return jniGetJointcount(addr); } private native int jniGetJointcount (long addr); /** * Get the number of contacts (each may have 0 or more contact points). */ public int getContactCount () { return jniGetContactCount(addr); } private native int jniGetContactCount (long addr); /** * Change the global gravity vector. */ public void setGravity (Vector2 gravity) { jniSetGravity(addr, gravity.x, gravity.y); } private native void jniSetGravity (long addr, float gravityX, float gravityY); /** * Get the global gravity vector. */ final float[] tmpGravity = new float[2]; final Vector2 gravity = new Vector2(); public Vector2 getGravity () { jniGetGravity(addr, tmpGravity); gravity.x = tmpGravity[0]; gravity.y = tmpGravity[1]; return gravity; } private native void jniGetGravity (long addr, float[] gravity); /** * Is the world locked (in the middle of a time step). */ public boolean isLocked () { return jniIsLocked(addr); } private native boolean jniIsLocked (long addr); /** * Set flag to control automatic clearing of forces after each time step. */ public void setAutoClearForces (boolean flag) { jniSetAutoClearForces(addr, flag); } private native void jniSetAutoClearForces (long addr, boolean flag); /** * Get the flag that controls automatic clearing of forces after each time step. */ public boolean getAutoClearForces () { return jniGetAutoClearForces(addr); } private native boolean jniGetAutoClearForces (long addr); /** * Query the world for all fixtures that potentially overlap the provided AABB. * @param callback a user implemented callback class. * @param lowerX the x coordinate of the lower left corner * @param lowerY the y coordinate of the lower left corner * @param upperX the x coordinate of the upper right corner * @param upperY the y coordinate of the upper right corner */ public void QueryAABB (QueryCallback callback, float lowerX, float lowerY, float upperX, float upperY) { queryCallback = callback; jniQueryAABB(addr, lowerX, lowerY, upperX, upperY); } private QueryCallback queryCallback = null;; private native void jniQueryAABB (long addr, float lowX, float lowY, float upX, float upY); // // /// Ray-cast the world for all fixtures in the path of the ray. Your callback // /// controls whether you get the closest point, any point, or n-points. // /// The ray-cast ignores shapes that contain the starting point. // /// @param callback a user implemented callback class. // /// @param point1 the ray starting point // /// @param point2 the ray ending point // void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const; // // /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get // /// the next contact in the world list. A NULL contact indicates the end of the list. // /// @return the head of the world contact list. // /// @warning contacts are // b2Contact* GetContactList(); private long[] contactAddrs = new long[200]; private final ArrayList<Contact> contacts = new ArrayList<Contact>(); private final ArrayList<Contact> freeContacts = new ArrayList<Contact>(); public List<Contact> getContactList () { int numContacts = getContactCount(); if (numContacts > contactAddrs.length) contactAddrs = new long[numContacts]; if (numContacts > freeContacts.size()) { int freeConts = freeContacts.size(); for (int i = 0; i < numContacts - freeConts; i++) freeContacts.add(new Contact(this, 0)); } jniGetContactList(addr, contactAddrs); contacts.clear(); for (int i = 0; i < numContacts; i++) { Contact contact = freeContacts.get(i); contact.addr = contactAddrs[i]; contacts.add(contact); } return contacts; } /** * @return all bodies currently in the simulation */ public Iterator<Body> getBodies () { return bodies.values(); } /** * @return all joints currently in the simulation */ public Iterator<Joint> getJoints () { return joints.values(); } private native void jniGetContactList (long addr, long[] contacts); public void dispose () { jniDispose(addr); } private native void jniDispose (long addr); /** * Internal method called from JNI in case a contact happens * @param fixtureA * @param fixtureB * @return whether the things collided */ private boolean contactFilter (long fixtureA, long fixtureB) { if (contactFilter != null) return contactFilter.shouldCollide(fixtures.get(fixtureA), fixtures.get(fixtureB)); else { Filter filterA = fixtures.get(fixtureA).getFilterData(); Filter filterB = fixtures.get(fixtureB).getFilterData(); if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) { return filterA.groupIndex > 0; } boolean collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0; return collide; } } private final Contact contact = new Contact(this, 0); private final Manifold manifold = new Manifold(this, 0); private final ContactImpulse impulse = new ContactImpulse(this, 0); private void beginContact (long contactAddr) { contact.addr = contactAddr; if (contactListener != null) contactListener.beginContact(contact); } private void endContact (long contactAddr) { contact.addr = contactAddr; if (contactListener != null) contactListener.endContact(contact); } private void preSolve (long contactAddr, long manifoldAddr) { contact.addr = contactAddr; manifold.addr = manifoldAddr; if (contactListener != null) contactListener.preSolve(contact, manifold); } private void postSolve (long contactAddr, long impulseAddr) { contact.addr = contactAddr; impulse.addr = impulseAddr; if (contactListener != null) contactListener.postSolve(contact, impulse); } private boolean reportFixture (long addr) { if (queryCallback != null) return queryCallback.reportFixture(fixtures.get(addr)); else return false; } }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; public interface ContactListener { /** * Called when two fixtures begin to touch. */ public void beginContact (Contact contact); /** * Called when two fixtures cease to touch. */ public void endContact (Contact contact); /* This is called after a contact is updated. This allows you to inspect a contact before it goes to the solver. If you are careful, you can modify the contact manifold (e.g. disable contact). A copy of the old manifold is provided so that you can detect changes. Note: this is called only for awake bodies. Note: this is called even when the number of contact points is zero. Note: this is not called for sensors. Note: if you set the number of contact points to zero, you will not get an EndContact callback. However, you may get a BeginContact callback the next step. */ public void preSolve(Contact contact, Manifold oldManifold); /* This lets you inspect a contact after the solver is finished. This is useful for inspecting impulses. Note: the contact manifold does not include time of impact impulses, which can be arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly in a separate data structure. Note: this is only called for contacts that are touching, solid, and awake. */ public void postSolve(Contact contact, ContactImpulse impulse); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; /** * A fixture definition is used to create a fixture. This class defines an abstract fixture definition. You can reuse fixture * definitions safely. * @author mzechner * */ public class FixtureDef { /** * The shape, this must be set. The shape will be cloned, so you can create the shape on the stack. */ public Shape shape; /** The friction coefficient, usually in the range [0,1]. **/ public float friction = 0.2f; /** The restitution (elasticity) usually in the range [0,1]. **/ public float restitution = 0; /** The density, usually in kg/m^2. **/ public float density = 0; /** * A sensor shape collects contact information but never generates a collision response. */ public boolean isSensor = false; /** Contact filtering data. **/ public final Filter filter = new Filter(); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; /** * Encodes a Box2D transform. We are lazy so we only store a 6 float wide array. First two floats are the position of the * b2Transform struct. Next two floats are the b2Transform.R.col1 x and y coordinates. Final 2 floats are the b2Transform.R.col2 x * and y coordinates; * @author mzechner * */ public class Transform { public static final int POS_X = 0; public static final int POS_Y = 1; public static final int COL1_X = 2; public static final int COL1_Y = 3; public static final int COL2_X = 4; public static final int COL2_Y = 5; public float[] vals = new float[6]; private Vector2 position = new Vector2(); public Transform () { } /** * Constructs a new Transform instance with the given position and angle * @param position the position * @param angle the angle in radians */ public Transform (Vector2 position, float angle) { setPosition(position); setRotation(angle); } /** * Transforms the given vector by this transform * @param v the vector */ public Vector2 mul (Vector2 v) { float x = vals[POS_X] + vals[COL1_X] * v.x + vals[COL2_X] * v.y; float y = vals[POS_Y] + vals[COL1_Y] * v.x + vals[COL2_Y] * v.y; v.x = x; v.y = y; return v; } /** * @return the position, modification of the vector has no effect on the Transform */ public Vector2 getPosition () { return position.set(vals[0], vals[1]); } /** * Sets the rotation of this transform * @param angle angle in radians */ public void setRotation (float angle) { float c = (float)Math.cos(angle), s = (float)Math.sin(angle); vals[COL1_X] = c; vals[COL2_X] = -s; vals[COL1_Y] = s; vals[COL2_Y] = c; } /** * Sets the position of this transform * @param pos the position */ public void setPosition (Vector2 pos) { this.vals[POS_X] = pos.x; this.vals[POS_Y] = pos.y; } }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; public interface DestructionListener { }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; /** * This is used to compute the current state of a contact manifold. */ public class WorldManifold { protected final Vector2 normal = new Vector2(); protected final Vector2[] points = {new Vector2(), new Vector2()}; protected int numContactPoints; protected WorldManifold () { } /** * Returns the normal of this manifold */ public Vector2 getNormal () { return normal; } /** * Returns the contact points of this manifold. Use getNumberOfContactPoints to determine how many contact points there are * (0,1 or 2) */ public Vector2[] getPoints () { return points; } /** * @return the number of contact points */ public int getNumberOfContactPoints () { return numContactPoints; } }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; /** * The class manages contact between two shapes. A contact exists for each overlapping AABB in the broad-phase (except if * filtered). Therefore a contact object may exist that has no contact points. * @author mzechner * */ public class Contact { /** the address **/ protected long addr; /** the world **/ protected World world; /** the world manifold **/ protected final WorldManifold worldManifold = new WorldManifold(); protected Contact (World world, long addr) { this.addr = addr; this.world = world; } /** * Get the world manifold. */ private final float[] tmp = new float[6]; public WorldManifold getWorldManifold () { int numContactPoints = jniGetWorldManifold(addr, tmp); worldManifold.numContactPoints = numContactPoints; worldManifold.normal.set(tmp[0], tmp[1]); for (int i = 0; i < numContactPoints; i++) { Vector2 point = worldManifold.points[i]; point.x = tmp[2 + i * 2]; point.y = tmp[2 + i * 2 + 1]; } return worldManifold; } private native int jniGetWorldManifold (long addr, float[] manifold); public boolean isTouching () { return jniIsTouching(addr); } private native boolean jniIsTouching (long addr); /** * Enable/disable this contact. This can be used inside the pre-solve contact listener. The contact is only disabled for the * current time step (or sub-step in continuous collisions). */ public void setEnabled (boolean flag) { jniSetEnabled(addr, flag); } private native void jniSetEnabled (long addr, boolean flag); /** * Has this contact been disabled? */ public boolean isEnabled () { return jniIsEnabled(addr); } private native boolean jniIsEnabled (long addr); /** * Get the first fixture in this contact. */ public Fixture getFixtureA () { return world.fixtures.get(jniGetFixtureA(addr)); } private native long jniGetFixtureA (long addr); /** * Get the second fixture in this contact. */ public Fixture getFixtureB () { return world.fixtures.get(jniGetFixtureB(addr)); } private native long jniGetFixtureB (long addr); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Shape.Type; public class Fixture { /** body **/ private final Body body; /** the address of the fixture **/ protected final long addr; /** the shape, initialized lazy **/ protected Shape shape; /** user specified data **/ protected Object userData; /** * Constructs a new fixture * @param addr the address of the fixture */ protected Fixture (Body body, long addr) { this.body = body; this.addr = addr; } /** * Get the type of the child shape. You can use this to down cast to the concrete shape. * @return the shape type. */ public Type getType () { int type = jniGetType(addr); if (type == 0) return Type.Circle; else return Type.Polygon; } private native int jniGetType (long addr); /** * Returns the shape of this fixture */ public Shape getShape () { if (shape == null) { long shapeAddr = jniGetShape(addr); int type = Shape.jniGetType(shapeAddr); if (type == 0) shape = new CircleShape(shapeAddr); else shape = new PolygonShape(shapeAddr); } return shape; } private native long jniGetShape (long addr); /** * Set if this fixture is a sensor. */ public void setSensor (boolean sensor) { jniSetSensor(addr, sensor); } private native void jniSetSensor (long addr, boolean sensor); /** * Is this fixture a sensor (non-solid)? * @return the true if the shape is a sensor. */ public boolean isSensor () { return jniIsSensor(addr); } private native boolean jniIsSensor (long addr); /** * Set the contact filtering data. This will not update contacts until the next time step when either parent body is active and * awake. */ public void setFilterData (Filter filter) { jniSetFilterData(addr, filter.categoryBits, filter.maskBits, filter.groupIndex); } private native void jniSetFilterData (long addr, short categoryBits, short maskBits, short groupIndex); /** * Get the contact filtering data. */ private final short[] tmp = new short[3]; private final Filter filter = new Filter(); public Filter getFilterData () { jniGetFilterData(addr, tmp); filter.maskBits = tmp[0]; filter.categoryBits = tmp[1]; filter.groupIndex = tmp[2]; return filter; } private native void jniGetFilterData (long addr, short[] filter); /** * Get the parent body of this fixture. This is NULL if the fixture is not attached. */ public Body getBody () { return body; } /** * Test a point for containment in this fixture. * @param p a point in world coordinates. */ public boolean testPoint (Vector2 p) { return jniTestPoint(addr, p.x, p.y); } /** * Test a point for containment in this fixture. * @param x the x-coordinate * @param y the y-coordinate */ public boolean testPoint(float x, float y) { return jniTestPoint(addr, x, y); } private native boolean jniTestPoint (long addr, float x, float y); // const b2Body* GetBody() const; // // /// Get the next fixture in the parent body's fixture list. // /// @return the next shape. // b2Fixture* GetNext(); // const b2Fixture* GetNext() const; // // /// Get the user data that was assigned in the fixture definition. Use this to // /// store your application specific data. // void* GetUserData() const; // // /// Set the user data. Use this to store your application specific data. // void SetUserData(void* data); // // /// Cast a ray against this shape. // /// @param output the ray-cast results. // /// @param input the ray-cast input parameters. // bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const; // // /// Get the mass data for this fixture. The mass data is based on the density and // /// the shape. The rotational inertia is about the shape's origin. This operation // /// may be expensive. // void GetMassData(b2MassData* massData) const; /** * Set the density of this fixture. This will _not_ automatically adjust the mass of the body. You must call * b2Body::ResetMassData to update the body's mass. */ public void setDensity (float density) { jniSetDensity(addr, density); } private native void jniSetDensity (long addr, float density); /** * Get the density of this fixture. */ public float getDensity () { return jniGetDensity(addr); } private native float jniGetDensity (long addr); /** * Get the coefficient of friction. */ public float getFriction () { return jniGetFriction(addr); } private native float jniGetFriction (long addr); /** * Set the coefficient of friction. */ public void setFriction (float friction) { jniSetFriction(addr, friction); } private native void jniSetFriction (long addr, float friction); /** * Get the coefficient of restitution. */ public float getRestitution () { return jniGetRestitution(addr); } private native float jniGetRestitution (long addr); /** * Set the coefficient of restitution. */ public void setRestitution (float restitution) { jniSetRestitution(addr, restitution); } private native void jniSetRestitution (long addr, float restitution); // /// Get the fixture's AABB. This AABB may be enlarge and/or stale. // /// If you need a more accurate AABB, compute it using the shape and // /// the body transform. // const b2AABB& GetAABB() const; /** * Sets custom user data. */ public void setUserData (Object userData) { this.userData = userData; } /** * @return custom user data */ public Object getUserData () { return userData; } }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; public class PolygonShape extends Shape { /** * Constructs a new polygon */ public PolygonShape () { addr = newPolygonShape(); } protected PolygonShape (long addr) { this.addr = addr; } private native long newPolygonShape (); /** * {@inheritDoc} */ @Override public Type getType () { return Type.Polygon; } /** * Copy vertices. This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each * edge. */ public void set (Vector2[] vertices) { float[] verts = new float[vertices.length * 2]; for (int i = 0, j = 0; i < vertices.length * 2; i += 2, j++) { verts[i] = vertices[j].x; verts[i + 1] = vertices[j].y; } jniSet(addr, verts); } private native void jniSet (long addr, float[] verts); /** * Build vertices to represent an axis-aligned box. * @param hx the half-width. * @param hy the half-height. */ public void setAsBox (float hx, float hy) { jniSetAsBox(addr, hx, hy); } private native void jniSetAsBox (long addr, float hx, float hy); /** * Build vertices to represent an oriented box. * @param hx the half-width. * @param hy the half-height. * @param center the center of the box in local coordinates. * @param angle the rotation of the box in local coordinates. */ public void setAsBox (float hx, float hy, Vector2 center, float angle) { jniSetAsBox(addr, hx, hy, center.x, center.y, angle); } private native void jniSetAsBox (long addr, float hx, float hy, float centerX, float centerY, float angle); /** * Set this as a single edge. */ public void setAsEdge (Vector2 v1, Vector2 v2) { jniSetAsEdge(addr, v1.x, v1.y, v2.x, v2.y); } private native void jniSetAsEdge (long addr, float v1x, float v1y, float v2x, float v2y); /** * @return the number of vertices */ public int getVertexCount () { return jniGetVertexCount(addr); } private native int jniGetVertexCount (long addr); private static float[] verts = new float[2]; /** * Returns the vertex at the given position. * @param index the index of the vertex 0 <= index < getVertexCount( ) * @param vertex vertex */ public void getVertex (int index, Vector2 vertex) { jniGetVertex(addr, index, verts); vertex.x = verts[0]; vertex.y = verts[1]; } private native void jniGetVertex (long addr, int index, float[] verts); }
Java
package com.badlogic.gdx.physics.box2d; public class ContactImpulse { final World world; long addr; float[] tmp = new float[2]; final float[] normalImpulses = new float[2]; final float[] tangentImpulses = new float[2]; protected ContactImpulse(World world, long addr) { this.world = world; this.addr = addr; } public float[] getNormalImpulses() { jniGetNormalImpulses(addr, normalImpulses); return normalImpulses; } private native void jniGetNormalImpulses(long addr, float[] values); public float[] getTangentImpulses() { jniGetTangentImpulses(addr, tangentImpulses); return tangentImpulses; } private native void jniGetTangentImpulses(long addr, float[] values); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; /** * Callback class for AABB queries. */ public interface QueryCallback { /** * Called for each fixture found in the query AABB. * @return false to terminate the query. */ public boolean reportFixture (Fixture fixture); }
Java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.utils; import java.lang.reflect.Array; import java.util.Iterator; import java.util.NoSuchElementException; import org.anddev.andengine.util.MathUtils; /** * An unordered map that uses long keys. This implementation is a cuckoo hash map using 3 hashes, random walking, and a small * stash for problematic keys. Null values are allowed. No allocation is done except when growing the table size. <br> * <br> * This map performs very fast get, containsKey, and remove (typically O(1), worst case O(log(n))). Put may be a bit slower, * depending on hash collisions. Load factors greater than 0.91 greatly increase the chances the map will have to rehash to the * next higher POT size. * @author Nathan Sweet */ public class LongMap<V> { private static final int PRIME1 = 0xbe1f14b1; private static final int PRIME2 = 0xb4b82e39; private static final int PRIME3 = 0xced1c241; private static final int EMPTY = 0; public int size; long[] keyTable; V[] valueTable; int capacity, stashSize; V zeroValue; boolean hasZeroValue; private float loadFactor; private int hashShift, mask, threshold; private int stashCapacity; private int pushIterations; private Entries entries; private Values values; private Keys keys; /** * Creates a new map with an initial capacity of 32 and a load factor of 0.8. This map will hold 25 items before growing the * backing table. */ public LongMap () { this(32, 0.8f); } /** * Creates a new map with a load factor of 0.8. This map will hold initialCapacity * 0.8 items before growing the backing * table. */ public LongMap (int initialCapacity) { this(initialCapacity, 0.8f); } /** * Creates a new map with the specified initial capacity and load factor. This map will hold initialCapacity * loadFactor items * before growing the backing table. */ public LongMap (int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be >= 0: " + initialCapacity); if (capacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large: " + initialCapacity); capacity = MathUtils.nextPowerOfTwo(initialCapacity); if (loadFactor <= 0) throw new IllegalArgumentException("loadFactor must be > 0: " + loadFactor); this.loadFactor = loadFactor; threshold = (int)(capacity * loadFactor); mask = capacity - 1; hashShift = 31 - Integer.numberOfTrailingZeros(capacity); stashCapacity = Math.max(3, (int)Math.ceil(Math.log(capacity)) + 1); pushIterations = Math.max(Math.min(capacity, 32), (int)Math.sqrt(capacity) / 4); keyTable = new long[capacity + stashCapacity]; valueTable = (V[])new Object[keyTable.length]; } public V put (long key, V value) { if (key == 0) { V oldValue = zeroValue; zeroValue = value; hasZeroValue = true; size++; return oldValue; } // Check for existing keys. int index1 = (int)(key & mask); long key1 = keyTable[index1]; if (key1 == key) { V oldValue = valueTable[index1]; valueTable[index1] = value; return oldValue; } int index2 = hash2(key); long key2 = keyTable[index2]; if (key2 == key) { V oldValue = valueTable[index2]; valueTable[index2] = value; return oldValue; } int index3 = hash3(key); long key3 = keyTable[index3]; if (key3 == key) { V oldValue = valueTable[index3]; valueTable[index3] = value; return oldValue; } // Check for empty buckets. if (key1 == EMPTY) { keyTable[index1] = key; valueTable[index1] = value; if (size++ >= threshold) resize(capacity << 1); return null; } if (key2 == EMPTY) { keyTable[index2] = key; valueTable[index2] = value; if (size++ >= threshold) resize(capacity << 1); return null; } if (key3 == EMPTY) { keyTable[index3] = key; valueTable[index3] = value; if (size++ >= threshold) resize(capacity << 1); return null; } push(key, value, index1, key1, index2, key2, index3, key3); return null; } public void putAll (LongMap<V> map) { for (Entry<V> entry : map.entries()) put(entry.key, entry.value); } /** * Skips checks for existing keys. */ private void putResize (long key, V value) { if (key == 0) { zeroValue = value; hasZeroValue = true; return; } // Check for empty buckets. int index1 = (int)(key & mask); long key1 = keyTable[index1]; if (key1 == EMPTY) { keyTable[index1] = key; valueTable[index1] = value; if (size++ >= threshold) resize(capacity << 1); return; } int index2 = hash2(key); long key2 = keyTable[index2]; if (key2 == EMPTY) { keyTable[index2] = key; valueTable[index2] = value; if (size++ >= threshold) resize(capacity << 1); return; } int index3 = hash3(key); long key3 = keyTable[index3]; if (key3 == EMPTY) { keyTable[index3] = key; valueTable[index3] = value; if (size++ >= threshold) resize(capacity << 1); return; } push(key, value, index1, key1, index2, key2, index3, key3); } private void push (long insertKey, V insertValue, int index1, long key1, int index2, long key2, int index3, long key3) { long[] keyTable = this.keyTable; V[] valueTable = this.valueTable; int mask = this.mask; // Push keys until an empty bucket is found. long evictedKey; V evictedValue; int i = 0, pushIterations = this.pushIterations; do { // Replace the key and value for one of the hashes. switch (MathUtils.random(0, 2)) { case 0: evictedKey = key1; evictedValue = valueTable[index1]; keyTable[index1] = insertKey; valueTable[index1] = insertValue; break; case 1: evictedKey = key2; evictedValue = valueTable[index2]; keyTable[index2] = insertKey; valueTable[index2] = insertValue; break; default: evictedKey = key3; evictedValue = valueTable[index3]; keyTable[index3] = insertKey; valueTable[index3] = insertValue; break; } // If the evicted key hashes to an empty bucket, put it there and stop. index1 = (int)(evictedKey & mask); key1 = keyTable[index1]; if (key1 == EMPTY) { keyTable[index1] = evictedKey; valueTable[index1] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } index2 = hash2(evictedKey); key2 = keyTable[index2]; if (key2 == EMPTY) { keyTable[index2] = evictedKey; valueTable[index2] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } index3 = hash3(evictedKey); key3 = keyTable[index3]; if (key3 == EMPTY) { keyTable[index3] = evictedKey; valueTable[index3] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } if (++i == pushIterations) break; insertKey = evictedKey; insertValue = evictedValue; } while (true); putStash(evictedKey, evictedValue); } private void putStash (long key, V value) { if (stashSize == stashCapacity) { // Too many pushes occurred and the stash is full, increase the table size. resize(capacity << 1); put(key, value); return; } // Update key in the stash. long[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) { if (keyTable[i] == key) { valueTable[i] = value; return; } } // Store key in the stash. int index = capacity + stashSize; keyTable[index] = key; valueTable[index] = value; stashSize++; } public V get (long key) { if (key == 0) return zeroValue; int index = (int)(key & mask); if (keyTable[index] != key) { index = hash2(key); if (keyTable[index] != key) { index = hash3(key); if (keyTable[index] != key) return getStash(key); } } return valueTable[index]; } private V getStash (long key) { long[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) if (keyTable[i] == key) return valueTable[i]; return null; } public V remove (long key) { if (key == 0) { if (!hasZeroValue) return null; V oldValue = zeroValue; zeroValue = null; hasZeroValue = false; size--; return oldValue; } int index = (int)(key & mask); if (keyTable[index] == key) { keyTable[index] = EMPTY; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } index = hash2(key); if (keyTable[index] == key) { keyTable[index] = EMPTY; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } index = hash3(key); if (keyTable[index] == key) { keyTable[index] = EMPTY; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } return removeStash(key); } V removeStash (long key) { long[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) { if (keyTable[i] == key) { V oldValue = valueTable[i]; removeStashIndex(i); size--; return oldValue; } } return null; } void removeStashIndex (int index) { // If the removed location was not last, move the last tuple to the removed location. stashSize--; int lastIndex = capacity + stashSize; if (index < lastIndex) { keyTable[index] = keyTable[lastIndex]; valueTable[index] = valueTable[lastIndex]; valueTable[lastIndex] = null; } else valueTable[index] = null; } public void clear () { long[] keyTable = this.keyTable; V[] valueTable = this.valueTable; for (int i = capacity + stashSize; i-- > 0;) { keyTable[i] = EMPTY; valueTable[i] = null; } size = 0; stashSize = 0; zeroValue = null; hasZeroValue = false; } /** * Returns true if the specified value is in the map. Note this traverses the entire map and compares every value, which may be * an expensive operation. */ public boolean containsValue (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { if (hasZeroValue && zeroValue == null) return true; long[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != EMPTY && valueTable[i] == null) return true; } else if (identity) { if (value == zeroValue) return true; for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return true; } else { if (hasZeroValue && value.equals(zeroValue)) return true; for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return true; } return false; } public boolean containsKey (long key) { if (key == 0) return hasZeroValue; int index = (int)(key & mask); if (keyTable[index] != key) { index = hash2(key); if (keyTable[index] != key) { index = hash3(key); if (keyTable[index] != key) return containsKeyStash(key); } } return true; } private boolean containsKeyStash (long key) { long[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) if (keyTable[i] == key) return true; return false; } /** * Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many * items to avoid multiple backing array resizes. */ public void ensureCapacity (int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded >= threshold) resize(MathUtils.nextPowerOfTwo((int)(sizeNeeded / loadFactor))); } private void resize (int newSize) { int oldEndIndex = capacity + stashSize; capacity = newSize; threshold = (int)(newSize * loadFactor); mask = newSize - 1; hashShift = 31 - Integer.numberOfTrailingZeros(newSize); stashCapacity = Math.max(3, (int)Math.ceil(Math.log(newSize))); pushIterations = Math.max(Math.min(capacity, 32), (int)Math.sqrt(capacity) / 4); long[] oldKeyTable = keyTable; V[] oldValueTable = valueTable; keyTable = new long[newSize + stashCapacity]; valueTable = (V[])new Object[newSize + stashCapacity]; size = hasZeroValue ? 1 : 0; stashSize = 0; for (int i = 0; i < oldEndIndex; i++) { long key = oldKeyTable[i]; if (key != EMPTY) putResize(key, oldValueTable[i]); } } private int hash2 (long h) { h *= PRIME2; return (int)((h ^ h >>> hashShift) & mask); } private int hash3 (long h) { h *= PRIME3; return (int)((h ^ h >>> hashShift) & mask); } public String toString () { if (size == 0) return "[]"; StringBuilder buffer = new StringBuilder(32); buffer.append('['); long[] keyTable = this.keyTable; V[] valueTable = this.valueTable; int i = keyTable.length; while (i-- > 0) { long key = keyTable[i]; if (key == EMPTY) continue; buffer.append(key); buffer.append('='); buffer.append(valueTable[i]); break; } while (i-- > 0) { long key = keyTable[i]; if (key == EMPTY) continue; buffer.append(", "); buffer.append(key); buffer.append('='); buffer.append(valueTable[i]); } buffer.append(']'); return buffer.toString(); } /** * Returns an iterator for the entries in the map. Remove is supported. Note that the same iterator instance is returned each * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Entries<V> entries () { if (entries == null) entries = new Entries(this); else entries.reset(); return entries; } /** * Returns an iterator for the values in the map. Remove is supported. Note that the same iterator instance is returned each * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Values<V> values () { if (values == null) values = new Values(this); else values.reset(); return values; } /** * Returns an iterator for the keys in the map. Remove is supported. Note that the same iterator instance is returned each time * this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Keys keys () { if (keys == null) keys = new Keys(this); else keys.reset(); return keys; } static public class Entry<V> { public long key; public V value; public String toString () { return key + "=" + value; } } static private class MapIterator<V> { static final int INDEX_ILLEGAL = -2; static final int INDEX_ZERO = -1; public boolean hasNext; final LongMap<V> map; int nextIndex, currentIndex; public MapIterator (LongMap<V> map) { this.map = map; reset(); } public void reset () { currentIndex = INDEX_ILLEGAL; nextIndex = INDEX_ZERO; if (map.hasZeroValue) hasNext = true; else findNextIndex(); } void findNextIndex () { hasNext = false; long[] keyTable = map.keyTable; for (int n = map.capacity + map.stashSize; ++nextIndex < n;) { if (keyTable[nextIndex] != EMPTY) { hasNext = true; break; } } } public void remove () { if (currentIndex == INDEX_ZERO && map.hasZeroValue) { map.zeroValue = null; map.hasZeroValue = false; } else if (currentIndex < 0) { throw new IllegalStateException("next must be called before remove."); } else if (currentIndex >= map.capacity) { map.removeStashIndex(currentIndex); } else { map.keyTable[currentIndex] = EMPTY; map.valueTable[currentIndex] = null; } currentIndex = INDEX_ILLEGAL; map.size--; } } static public class Entries<V> extends MapIterator<V> implements Iterable<Entry<V>>, Iterator<Entry<V>> { private Entry<V> entry = new Entry(); public Entries (LongMap map) { super(map); } /** * Note the same entry instance is returned each time this method is called. */ public Entry<V> next () { if (!hasNext) throw new NoSuchElementException(); long[] keyTable = map.keyTable; if (nextIndex == INDEX_ZERO) { entry.key = 0; entry.value = map.zeroValue; } else { entry.key = keyTable[nextIndex]; entry.value = map.valueTable[nextIndex]; } currentIndex = nextIndex; findNextIndex(); return entry; } public boolean hasNext () { return hasNext; } public Iterator<Entry<V>> iterator () { return this; } } static public class Values<V> extends MapIterator<V> implements Iterable<V>, Iterator<V> { public Values (LongMap<V> map) { super(map); } public boolean hasNext () { return hasNext; } public V next () { V value; if (nextIndex == INDEX_ZERO) value = map.zeroValue; else value = map.valueTable[nextIndex]; currentIndex = nextIndex; findNextIndex(); return value; } public Iterator<V> iterator () { return this; } } static public class Keys extends MapIterator { public Keys (LongMap map) { super(map); } public long next () { long key = nextIndex == INDEX_ZERO ? 0 : map.keyTable[nextIndex]; currentIndex = nextIndex; findNextIndex(); return key; } } }
Java
package com.felight.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.felight.calc.Calculator; /** * Servlet implementation class Prime */ public class Prime extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Prime() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String str = request.getParameter("num"); int number = Integer.parseInt(str); out.write(""+Calculator.isPrime(number)); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String str = request.getParameter("num"); int number = Integer.parseInt(str); boolean res = Calculator.isPrime(number); out.write(" "+ res); } }
Java
package com.felight.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.felight.calc.Calculator; /** * Servlet implementation class Calculator */ public class CalculatorServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CalculatorServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String s1 = request.getParameter("Size"); int random = Integer.parseInt(s1); int[] array = Calculator.generateRandomIntArray(random); out.write("The random array is :"); for(int i = 0;i<array.length;i++){ out.write(" "+ array[i] ); } out.write("The sum of array is: "+ Calculator.sumOfArray(array)); } }
Java
package com.felight.servlets; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ServletConfig */ public class ServletConf extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ServletConf() { super(); // TODO Auto-generated constructor stub } public void init(){ System.out.println("server started.."); } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ PrintWriter out = response.getWriter(); ServletConfig sc = getServletConfig(); String driver = sc.getInitParameter("driver"); String url = sc.getInitParameter("url"); String uname = sc.getInitParameter("username"); String pwd = sc.getInitParameter("password"); String table = sc.getInitParameter("tablename"); out.println("table"); Class.forName(driver); out.println("registration successfull.."); Connection conn = DriverManager.getConnection(url,uname,pwd); out.println("Connection eshtablished"); Statement stm = conn.createStatement(); ResultSet rs = stm.executeQuery("select * from "+ table); out.println("inside table."); while(rs.next()){ out.println("<h2>"+rs.getInt(1)+"</h2>"); out.println("<h2>"+rs.getString(2)+"</h2>"); } } catch(Exception e){ e.printStackTrace(); } } }
Java
package com.felight.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Addition */ public class Addition extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Addition() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String str = request.getParameter("num"); String str1 = str.replace(";", ","); String[] array = str1.split(","); int sum =0; for(int i=0;i<array.length;i++){ sum =sum + Integer.parseInt(array[i]); } out.write("sum : "+sum); } }
Java
package com.felight.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.felight.calc.Calculator; /** * Servlet implementation class Fibonacci */ public class Fibonacci extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Fibonacci() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String s1 = request.getParameter("Size"); int random = Integer.parseInt(s1); int[] array = Calculator.Fibonacci(random); //out.write("the fibonacci series is:"); for(int i = 0;i<array.length;i++){ System.out.println(""+array[i]); out.write(""+array[i]); } } }
Java
package com.felight.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.felight.sql.User; import com.felight.sql.UserDao; /** * Servlet implementation class UserInfo */ public class UserInfo extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UserInfo() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String s1 = request.getParameter("firstname"); String s2 = request.getParameter("lastname"); out.write("Hi.. "+s1+" "+s2); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); UserDao ud = new UserDao(); User u = new User(); String str = request.getParameter("userid"); int id = Integer.parseInt(str); u = ud.getUser(id); out.write("User details:"+u.getUserId()); } }
Java
package com.felight.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.felight.calc.Calculator; /** * Servlet implementation class CountingVowel */ public class CountingVowel extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CountingVowel() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String name = request.getParameter("name"); char[] cName = name.toCharArray(); out.write("Number of vowels in your father's name is:"+Calculator.countVowels(cName)); } }
Java
package com.felight.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Example */ public class Example extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Example() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Successfully executed...."); PrintWriter writer = response.getWriter(); writer.write("<html><body><h1>THE ALCHEMIST<br/></h1>"); writer.write("<h4>by,<span style=color:red>Paulo Coelho</span></h4>"); writer.write("<div style = color:#D2691E><p>If I became a <b>monster</b> today, and decided to kill them, one by one, they would become aware only after most of the flock had been slaughtered,thought the boy. They trust me, and they've forgotten how to rely on their own instincts, because I lead them to nourishment.</p>"); writer.write("<p>The boy was surprised at his thoughts. Maybe the <b>church</b>, with the sycamore growing from within, had been haunted. It had caused him to have the same dream for a second time, and it was causing him to feel anger toward his faithful companions. He drank a bit from the wine that remained from his dinner of the night before, and he gathered his jacket closer to his body. He knew that a few hours from now, with the sun at its zenith, the heat would be so great that he would not be able to lead hisflock across the fields. It was the time of day when all of Spain slept during the summer. The heat lasted until nightfall, and all that time he had to carry his jacket. But when he thought to complain about the burden of its weight, he remembered that, because he had the jacket, he had withstood the cold of the dawn.</p>"); writer.write("<p><i>People from all over the world have passed through this village, son,</i> said his father.<i> They come in search of new things, but when they leave they are basically the same people they were when they arrived. They climb the mountain to see the castle, and they wind up thinking that the past was better than what we have now. They have blond hair, or dark skin, but basically they're the same as the people who live right here</i></p>."); writer.write("</body></html>"); } }
Java
package com.felight.sql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.apache.log4j.Logger; import com.felight.examples.jdbc.db.DbUtil; public class UserDao { private Logger log = Logger.getLogger(UserDao.class); private Connection connection; private Statement statement; private PreparedStatement preparedStatement; public User getUser(int userId){ String query = "SELECT * FROM USER WHERE USER_ID = "+ userId; ResultSet rs = null; User user = null; try { connection = ConnectionFactory.getConnection(); statement = connection.createStatement(); rs = statement.executeQuery(query); if(rs.next()){ user = new User(); user.setUserId(rs.getInt("USER_ID")); user.setUserName(rs.getString("USER_NAME")); user.setEmail(rs.getString("EMAIL")); user.setFirstName(rs.getString("FIRST_NAME")); user.setLastName(rs.getString("LAST_NAME")); user.setPassword(rs.getString("PASSWORD")); user.setUserType(rs.getString("USER_TYPE")); user.setActiveFlag(rs.getString("ACTIVE_FLAG")); user.setCreatedBy(rs.getInt("CREATED_BY")); user.setCreatedDate(rs.getDate("CREATED_DATE")); user.setModifiedBy(rs.getInt("MODIFIED_BY")); user.setModifiedDate(rs.getDate("MODIFIED_DATE")); user.setDob(rs.getDate("DATE_OF_BIRTH")); user.setCoins(rs.getInt("COINS")); user.setNoOfBusiness(rs.getInt("NO_OF_BUSINESS")); log.info(query + "exectued successfully"); return user; } } catch(SQLException e){ log.debug("Select query unsuccessful : QUERY : "+query); log.debug("due to :"+e); } finally{ DbUtil.close(rs); DbUtil.close(statement); DbUtil.close(connection); } return user; } public boolean saveUser(User user){ String query = "INSERT INTO USER (USER_NAME, EMAIL, FIRST_NAME, LAST_NAME, PASSWORD, USER_TYPE, ACTIVE_FLAG, CREATED_BY, CREATED_DATE, MODIFIED_BY, MODIFIED_DATE, DATE_OF_BIRTH" + "COINS, NO_OF_BUSINESS) VALUES" + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?);"; try{ connection = ConnectionFactory.getConnection(); preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, user.getUserName()); preparedStatement.setString(2, user.getEmail()); preparedStatement.setString(3, user.getFirstName()); preparedStatement.setString(4, user.getLastName()); preparedStatement.setString(5, user.getPassword()); preparedStatement.setString(6, user.getUserType()); preparedStatement.setString(7, user.getActiveFlag()); preparedStatement.setInt(8, user.getCreatedBy()); preparedStatement.setDate(9, user.getCreatedDate()); preparedStatement.setInt(10, user.getModifiedBy()); preparedStatement.setDate(11, user.getModifiedDate()); preparedStatement.setDate(12, user.getDob()); preparedStatement.setInt(13, user.getCoins()); preparedStatement.setInt(14, user.getNoOfBusiness()); log.info("NEw row added to database with query : "+ query); return preparedStatement.executeUpdate() > 0 ? true : false; } catch(SQLException ex){ log.error("Insertion failed due to : "+ ex); return false; } finally{ DbUtil.close(preparedStatement); DbUtil.close(connection); } } public boolean updateUser(User user){ String query = "UPDATE USER SET USER_NAME = ?, EMAIL=?, FIRST_NAME=?, LAST_NAME=?," + "PASSWORD=?, USER_TYPE=?, ACTIVE_FLAG=?, CREATED_BY=?," +"CREATED_DATE=?, MODIFIED_BY=?,MODIFIED_DATE=?,DATE_OF_BIRTH=?," +"COINS=?,NO_OF_BUSINESS=? WHERE USER_ID="+user.getUserId(); try{ connection = ConnectionFactory.getConnection(); preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, user.getUserName()); preparedStatement.setString(2, user.getEmail()); preparedStatement.setString(3, user.getFirstName()); preparedStatement.setString(4, user.getLastName()); preparedStatement.setString(5, user.getPassword()); preparedStatement.setString(6, user.getUserType()); preparedStatement.setString(7, user.getActiveFlag()); preparedStatement.setInt(8, user.getCreatedBy()); preparedStatement.setDate(9, user.getCreatedDate()); preparedStatement.setInt(10, user.getModifiedBy()); preparedStatement.setDate(11, user.getModifiedDate()); preparedStatement.setDate(12, user.getDob()); preparedStatement.setInt(13, user.getCoins()); preparedStatement.setInt(14, user.getNoOfBusiness()); log.info("Row updated successful with query :"+query); return preparedStatement.executeUpdate() >0 ? true : false; } catch(SQLException ex){ log.error("Update failed due to :"+ ex); return false; } finally{ DbUtil.close(preparedStatement); DbUtil.close(connection); } } public boolean deleteUser(User user){ String query = "DELETE from USER WHERE USER_ID ="+user.getUserId(); try{ connection = ConnectionFactory.getConnection(); preparedStatement = connection.prepareStatement(query); log.info("Row deleted successfully with query :"+ query); return preparedStatement.executeUpdate() > 0 ? true : false; } catch(SQLException ex){ log.error("Delete failed due to : " + ex); return false; } finally { DbUtil.close(preparedStatement); DbUtil.close(connection); } } }
Java
package com.felight.sql; import java.sql.Date; public class User { private int userId; private String userName; private String email; private String firstName; private String lastName; private String password; private String userType; private String activeFlag; private int createdBy; private Date createdDate; private int modifiedBy; private Date modifiedDate; private Date dob; private int coins; private int noOfBusiness; /*public User(int userId, String userName, String email, String firstName, String lastName, String password, char userType, char activeFlag, int createdBy, Date createdDate, int modifiedBy, Date modifiedDate, Date dob, int coins, int noOfBusiness) { super(); this.userId = userId; this.userName = userName; this.email = email; this.firstName = firstName; this.lastName = lastName; this.password = password; this.userType = userType; this.activeFlag = activeFlag; this.createdBy = createdBy; this.createdDate = createdDate; this.modifiedBy = modifiedBy; this.modifiedDate = modifiedDate; this.dob = dob; this.coins = coins; this.noOfBusiness = noOfBusiness; }*/ public int getUserId() { return userId; } public String getUserName() { return userName; } public String getEmail() { return email; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getPassword() { return password; } public String getUserType() { return userType; } public String getActiveFlag() { return activeFlag; } public int getCreatedBy() { return createdBy; } public Date getCreatedDate() { return createdDate; } public int getModifiedBy() { return modifiedBy; } public Date getModifiedDate() { return modifiedDate; } public Date getDob() { return dob; } public int getCoins() { return coins; } public int getNoOfBusiness() { return noOfBusiness; } public void setUserId(int userId) { this.userId = userId; } public void setUserName(String userName) { this.userName = userName; } public void setEmail(String email) { this.email = email; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setPassword(String password) { this.password = password; } public void setUserType(String string) { this.userType = string; } public void setActiveFlag(String string) { this.activeFlag = string; } public void setCreatedBy(int createdBy) { this.createdBy = createdBy; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public void setModifiedBy(int modifiedBy) { this.modifiedBy = modifiedBy; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } public void setDob(Date dob) { this.dob = dob; } public void setCoins(int coins) { this.coins = coins; } public void setNoOfBusiness(int noOfBusiness) { this.noOfBusiness = noOfBusiness; } }
Java
package com.felight.sql; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import org.apache.log4j.Logger; import java.sql.Connection; public class ConnectionFactory{ private static Logger log = Logger.getLogger(ConnectionFactory.class); private static ConnectionFactory instance = new ConnectionFactory(); private Properties prop = new Properties(); private static String url; private static String userName; private static String password; private static String driver; private static Connection connection; public static Connection getConnection(){ return instance.createConnection(); } private Connection createConnection(){ try{ connection = DriverManager.getConnection(url,userName,password); } catch(SQLException e){ log.error("ERROR: Unable to Connect to database"); log.error(e); } return connection; } private ConnectionFactory(){ initialize(); } private void initialize(){ try{ prop.load(new FileInputStream("application.properties")); url = prop.getProperty("url"); userName = prop.getProperty("username"); password = prop.getProperty("password"); driver = prop.getProperty("driver"); Class.forName(driver); log.info("Using Driver :"+ driver); log.info("Driver registration successfull"); } catch(FileNotFoundException e){ System.out.println("file not found"); log.error("application.properties file not found"); log.error(e); } catch(IOException e){ log.error("Error occured while reading application.properties" + "please check if the file has write access or not"); log.error(e); } catch(ClassNotFoundException e){ log.error("driver initialization failed"); log.error(e); } } }
Java
package com.felight.calc; public class Calculator{ public final static double PI=3.142; // public static void main(String[] args){ // isPrime(2); //System.out.println("Hiii"); // int[][] matrix=new int[2][3]; // int[] array={5, 8, 1, 3, 2}; // String[] arr={"a","r","t","e","i"}; // // areaOfRectangle(4.5,7.5); // areaOfCircle(20.0); // System.out.println("the fibonacci series are:"); // Fibonacci(10); // // sumOfArray(array); // getMaxOfArray(array); // reverseArray(array); // countVowels(arr); // generatePrimeArray(1,10); // //generateRandomIntMatrix(matrix); // printMatrix(matrix); //} public static double areaOfRectangle(double height,double width){ double h=height; double w=width; double area=0.0; if(height>=0){ if(width>=0) area=h*w; } return area; } public static double areaOfCircle(double r){ double area=0.0; if(r>=0) area=r*r*PI; return area; } public static int[] Fibonacci(int num){ int[] result=new int[num]; //int[] res = new int[result.length]; result[0]=0; result[1]=1; for(int i=2;i<num;i++){ result[i]=result[i-1]+result[i-2]; //System.out.println(result[i]); } return result; } /*public int even(int num){ if(num%2==0){ System.out.println("the num"+num+"is even"); } else{ System.out.println("the num"+num+"is odd"); } return num; }*/ public static void printCharArray(char[] array){ for(int i=0;i<array.length;i++) System.out.println(array[i]+","); } public static void printIntArray(int[] array){ for(int i=0;i<array.length;i++) System.out.println(array[i]+","); } public static long sumOfArray(int[] array){ long sum = 0; for(int i =0;i<array.length;i++) sum = sum+array[i]; return sum; } public static int[] generateRandomIntArray(int size){ int[] result = new int[size]; for(int i=0;i<size;i++){ result[i]=(int) (Math.random()*100); //System.out.println(result[i]); } return result; } public static int[] generateRandomIntMatrix(int[][] matrix){ int[] result = new int[matrix.length]; int row=0,column=0; for(row=0;row<matrix.length;row++){ for( column=0;column<matrix[row].length;column++){ matrix[row][column]=(int) (Math.random()*100); } } System.out.println(matrix[row][column]); return result; } public static double[] generateRandomDoubleArray(int size){ double[] result = new double[size]; for (int i=0;i<size;i++) result[i]=Math.random()*100; return result; } public static char[] generateRandomCharArray(int size){ char temp; char[] result = new char[size]; int i=0; while(i<size){ temp=(char)(Math.random()*100); if ((temp >= 'a' && temp <= 'z')||(temp >='A' && temp <='Z')){ result[i++]=temp; } } return result; } public static int getMaxOfArray(int[] array){ int max=0; for(int i=0;i<array.length;i++) if(max<array[i]) max=array[i]; return max; } public static int[] reverseArray(int[] array){ int[] rev = new int[array.length]; for(int i=0;i<array.length;i++){ rev[array.length-i-1]=array[i]; } return rev; } public static int countVowels(char[] array){ int count = 0; for(int i=0;i<array.length;i++){ if(array[i]=='a'||array[i]=='e'||array[i]=='i'||array[i]=='o'||array[i]=='u'||array[i]=='A'||array[i]=='E'||array[i]=='I'||array[i]=='O'||array[i]=='U') count++; } return count; } public static int[] generateEvenArray(int from,int to){ int[] result = new int[50]; for(int i=from,j=0;i<=to;i++,j++) if(i%2==0)//for odd number if(!(i%2==0)) result[j]=i; else j--; return result; } public static int[] generatePrimeArray(int from,int to){ int[] arr = new int[50]; for(int i=from,j=0;i<=to;i++,j++) if(isPrime(i)){ arr[j]=i; System.out.println(arr[j]); } else j--; return arr; } public static boolean isPrime(long num){ boolean result=false; long count=0; long i=2; while(i<=num/2){ if(num %i==0) count++; i++; } if(count==0 && num!=1 && num!=0){ result= true; //System.out.println(result); } return result; } // public static boolean isPrime(int n) { // for(int i=2;i<n;i++) { // if(n%i==0) // return false; // } // return true; // } public static void printMatrix(int[][] matrix){ int i,j; for(i=0;i<matrix.length;i++){ for(j=0;j<matrix.length;j++){ System.out.println(matrix[i][j]+" "); } System.out.println(" "); } } public static long sumMatrix(int[][] matrix){ long sum=0; for(int i=0;i<matrix.length;i++) for(int j=0;j<matrix[i].length;j++) sum=sum+matrix[i][j]; return sum; } public static int[] sumRow(int[][] matrix){ int sum[] = new int[matrix.length]; for(int i=0;i<matrix.length;i++) for(int j=0;j<matrix[i].length;j++) sum[i]=sum[i]+matrix[i][j]; return sum; } public static int[] sumColumn(int[][] matrix){ int sum[]= new int[matrix[0].length]; for(int i=0;i<matrix.length;i++) for(int j=0;j<matrix[i].length;j++) sum[j]=sum[j]+matrix[i][j]; return sum; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.Room; import com.google.android.apps.iosched.io.model.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.Lists; import com.google.gson.Gson; import android.content.ContentProviderOperation; import android.content.Context; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class RoomsHandler extends JSONHandler { private static final String TAG = makeLogTag(RoomsHandler.class); public RoomsHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); Rooms roomsJson = new Gson().fromJson(json, Rooms.class); int noOfRooms = roomsJson.rooms.length; for (int i = 0; i < noOfRooms; i++) { parseRoom(roomsJson.rooms[i], batch); } return batch; } private static void parseRoom(Room room, ArrayList<ContentProviderOperation> batch) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Rooms.CONTENT_URI)); builder.withValue(ScheduleContract.Rooms.ROOM_ID, room.id); builder.withValue(ScheduleContract.Rooms.ROOM_NAME, room.name); builder.withValue(ScheduleContract.Rooms.ROOM_FLOOR, room.floor); batch.add(builder.build()); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class SearchSuggestions { public String[] words; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Tracks { Track[] track; public Track[] getTrack() { return track; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class TimeSlot { public String start; public String end; public String title; public String type; public String meta; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class EventSlots { public Day[] day; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Room { public String id; public String name; public String floor; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; import com.google.gson.annotations.SerializedName; public class Track { public String id; public String name; public String color; @SerializedName("abstract") public String _abstract; public int level; public int order_in_level; public int meta; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Day { public String date; public TimeSlot[] slot; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Rooms { public Room[] rooms; }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.map.model; import java.util.Map; public class MapResponse { public MapConfig config; public Map<String, Marker[]> markers; public Map<String, Tile> tiles; }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.map.model; public class Tile { public String filename; public String url; }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.map.model; public class MapConfig { public boolean enableMyLocation; }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.map.model; public class Marker { public String id; public String type; public float lat; public float lng; public String title; public String track; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.SearchSuggestions; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.Lists; import com.google.gson.Gson; import android.app.SearchManager; import android.content.ContentProviderOperation; import android.content.Context; import java.io.IOException; import java.util.ArrayList; public class SearchSuggestHandler extends JSONHandler { public SearchSuggestHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); SearchSuggestions suggestions = new Gson().fromJson(json, SearchSuggestions.class); if (suggestions.words != null) { // Clear out suggestions batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.SearchSuggest.CONTENT_URI)) .build()); // Rebuild suggestions for (String word : suggestions.words) { batch.add(ContentProviderOperation .newInsert(ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.SearchSuggest.CONTENT_URI)) .withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, word) .build()); } } return batch; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import java.io.IOException; /** * General {@link IOException} that indicates a problem occurred while parsing or applying a {@link * JSONHandler}. */ public class HandlerException extends IOException { public HandlerException() { super(); } public HandlerException(String message) { super(message); } public HandlerException(String message, Throwable cause) { super(message); initCause(cause); } @Override public String toString() { if (getCause() != null) { return getLocalizedMessage() + ": " + getCause(); } else { return getLocalizedMessage(); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleDatabase; import com.google.android.apps.iosched.util.*; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.googledevelopers.Googledevelopers; import com.google.api.services.googledevelopers.model.SessionResponse; import com.google.api.services.googledevelopers.model.SessionsResponse; import com.google.api.services.googledevelopers.model.TrackResponse; import com.google.api.services.googledevelopers.model.TracksResponse; import java.io.IOException; import java.util.*; import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import static com.google.android.apps.iosched.util.LogUtils.*; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; public class SessionsHandler { private static final String TAG = makeLogTag(SessionsHandler.class); private static final String BASE_SESSION_URL = "https://developers.google.com/events/io/sessions/"; private static final String EVENT_TYPE_KEYNOTE = Sessions.SESSION_TYPE_KEYNOTE; private static final String EVENT_TYPE_OFFICE_HOURS = Sessions.SESSION_TYPE_OFFICE_HOURS; private static final String EVENT_TYPE_CODELAB = Sessions.SESSION_TYPE_CODELAB; private static final String EVENT_TYPE_SANDBOX = Sessions.SESSION_TYPE_SANDBOX; private static final int PARSE_FLAG_FORCE_SCHEDULE_REMOVE = 1; private static final int PARSE_FLAG_FORCE_SCHEDULE_ADD = 2; private Context mContext; public SessionsHandler(Context context) { mContext = context; } public ArrayList<ContentProviderOperation> fetchAndParse( Googledevelopers conferenceAPI) throws IOException { // Set up the HTTP transport and JSON factory SessionsResponse sessions; SessionsResponse starredSessions = null; TracksResponse tracks; try { sessions = conferenceAPI.events().sessions().list(Config.EVENT_ID).setLimit(9999L).execute(); tracks = conferenceAPI.events().tracks().list(Config.EVENT_ID).execute(); if (sessions == null || sessions.getSessions() == null) { throw new HandlerException("Sessions list was null."); } if (tracks == null || tracks.getTracks() == null) { throw new HandlerException("trackDetails list was null."); } } catch (HandlerException e) { LOGE(TAG, "Fatal: error fetching sessions/tracks", e); return Lists.newArrayList(); } final boolean profileAvailableBefore = PrefUtils.isDevsiteProfileAvailable(mContext); boolean profileAvailableNow = false; try { starredSessions = conferenceAPI.users().events().sessions().list(Config.EVENT_ID).execute(); // If this succeeded, the user has a DevSite profile PrefUtils.markDevSiteProfileAvailable(mContext, true); profileAvailableNow = true; } catch (GoogleJsonResponseException e) { // Hack: If the user doesn't have a developers.google.com profile, the Conference API // will respond with HTTP 401 and include something like // "Provided user does not have a developers.google.com profile" in the message. if (401 == e.getStatusCode() && e.getDetails() != null && e.getDetails().getMessage() != null && e.getDetails().getMessage().contains("developers.google.com")) { LOGE(TAG, "User does not have a developers.google.com profile. Not syncing remote " + "personalized schedule."); starredSessions = null; // Record that the user's profile is offline. If this changes later, we'll re-upload any local // starred sessions. PrefUtils.markDevSiteProfileAvailable(mContext, false); } else { LOGW(TAG, "Auth token invalid, requesting refresh", e); AccountUtils.refreshAuthToken(mContext); } } if (profileAvailableNow && !profileAvailableBefore) { LOGI(TAG, "developers.google.com mode change: DEVSITE_PROFILE_AVAILABLE=false -> true"); // User's DevSite profile has come into existence. Re-upload tracks. ContentResolver cr = mContext.getContentResolver(); String[] projection = new String[] {ScheduleContract.Sessions.SESSION_ID, Sessions.SESSION_TITLE}; Cursor c = cr.query(ScheduleContract.BASE_CONTENT_URI.buildUpon(). appendPath("sessions").appendPath("starred").build(), projection, null, null, null); if (c != null) { c.moveToFirst(); while (!c.isAfterLast()) { String id = c.getString(0); String title = c.getString(1); LOGI(TAG, "Adding session: (" + id + ") " + title); Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(id); SessionsHelper.uploadStarredSession(mContext, sessionUri, true); c.moveToNext(); } } // Hack: Use local starred sessions for now, to give the new sessions time to take effect // TODO(trevorjohns): Upload starred sessions should be synchronous to avoid this hack starredSessions = null; } return buildContentProviderOperations(sessions, starredSessions, tracks); } public ArrayList<ContentProviderOperation> parseString(String sessionsJson, String tracksJson) { JsonFactory jsonFactory = new GsonFactory(); try { SessionsResponse sessions = jsonFactory.fromString(sessionsJson, SessionsResponse.class); TracksResponse tracks = jsonFactory.fromString(tracksJson, TracksResponse.class); return buildContentProviderOperations(sessions, null, tracks); } catch (IOException e) { LOGE(TAG, "Error reading speakers from packaged data", e); return Lists.newArrayList(); } } private ArrayList<ContentProviderOperation> buildContentProviderOperations( SessionsResponse sessions, SessionsResponse starredSessions, TracksResponse tracks) { // If there was no starred sessions response (e.g. there was an auth issue, // or this is a local sync), keep all the locally starred sessions. boolean retainLocallyStarredSessions = (starredSessions == null); final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Build lookup table for starredSessions mappings HashSet<String> starredSessionsMap = new HashSet<String>(); if (starredSessions != null) { List<SessionResponse> starredSessionList = starredSessions.getSessions(); if (starredSessionList != null) { for (SessionResponse session : starredSessionList) { String sessionId = session.getId(); starredSessionsMap.add(sessionId); } } } // Build lookup table for track mappings // Assumes that sessions can only have one track. Not guarenteed by the Conference API, // but is being enforced by conference organizer policy. HashMap<String, TrackResponse> trackMap = new HashMap<String, TrackResponse>(); if (tracks != null) { for (TrackResponse track : tracks.getTracks()) { List<String> sessionIds = track.getSessions(); if (sessionIds != null) { for (String sessionId : sessionIds) { trackMap.put(sessionId, track); } } } } if (sessions != null) { List<SessionResponse> sessionList = sessions.getSessions(); int numSessions = sessionList.size(); if (numSessions > 0) { LOGI(TAG, "Updating sessions data"); Set<String> starredSessionIds = new HashSet<String>(); if (retainLocallyStarredSessions) { Cursor starredSessionsCursor = mContext.getContentResolver().query( Sessions.CONTENT_STARRED_URI, new String[]{ScheduleContract.Sessions.SESSION_ID}, null, null, null); while (starredSessionsCursor.moveToNext()) { starredSessionIds.add(starredSessionsCursor.getString(0)); } starredSessionsCursor.close(); } // Clear out existing sessions batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.CONTENT_URI)) .build()); // Maintain a list of created session block IDs Set<String> blockIds = new HashSet<String>(); // Maintain a map of insert operations for sandbox-only blocks HashMap<String, ContentProviderOperation> sandboxBlocks = new HashMap<String, ContentProviderOperation>(); for (SessionResponse session : sessionList) { int flags = 0; String sessionId = session.getId(); if (retainLocallyStarredSessions) { flags = (starredSessionIds.contains(sessionId) ? PARSE_FLAG_FORCE_SCHEDULE_ADD : PARSE_FLAG_FORCE_SCHEDULE_REMOVE); } if (TextUtils.isEmpty(sessionId)) { LOGW(TAG, "Found session with empty ID in API response."); continue; } // Session title String sessionTitle = session.getTitle(); String sessionSubtype = session.getSubtype(); if (EVENT_TYPE_CODELAB.equals(sessionSubtype)) { sessionTitle = mContext.getString( R.string.codelab_title_template, sessionTitle); } // Whether or not it's in the schedule boolean inSchedule = starredSessionsMap.contains(sessionId); if ((flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0 || (flags & PARSE_FLAG_FORCE_SCHEDULE_REMOVE) != 0) { inSchedule = (flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0; } if (EVENT_TYPE_KEYNOTE.equals(sessionSubtype)) { // Keynotes are always in your schedule. inSchedule = true; } // Clean up session abstract String sessionAbstract = session.getDescription(); if (sessionAbstract != null) { sessionAbstract = sessionAbstract.replace('\r', '\n'); } // Hashtags TrackResponse track = trackMap.get(sessionId); String hashtag = null; if (track != null) { hashtag = ParserUtils.sanitizeId(track.getTitle()); } boolean isLivestream = false; try { isLivestream = session.getIsLivestream(); } catch (NullPointerException ignored) { } String youtubeUrl = session.getYoutubeUrl(); // Get block id long sessionStartTime = session.getStartTimestamp().longValue() * 1000; long sessionEndTime = session.getEndTimestamp().longValue() * 1000; String blockId = ScheduleContract.Blocks.generateBlockId( sessionStartTime, sessionEndTime); if (!blockIds.contains(blockId) && !EVENT_TYPE_SANDBOX.equals(sessionSubtype)) { // New non-sandbox block if (sandboxBlocks.containsKey(blockId)) { sandboxBlocks.remove(blockId); } String blockType; String blockTitle; if (EVENT_TYPE_KEYNOTE.equals(sessionSubtype)) { blockType = ScheduleContract.Blocks.BLOCK_TYPE_KEYNOTE; blockTitle = mContext.getString(R.string.schedule_block_title_keynote); } else if (EVENT_TYPE_CODELAB.equals(sessionSubtype)) { blockType = ScheduleContract.Blocks.BLOCK_TYPE_CODELAB; blockTitle = mContext.getString( R.string.schedule_block_title_code_labs); } else if (EVENT_TYPE_OFFICE_HOURS.equals(sessionSubtype)) { blockType = ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS; blockTitle = mContext.getString( R.string.schedule_block_title_office_hours); } else { blockType = ScheduleContract.Blocks.BLOCK_TYPE_SESSION; blockTitle = mContext.getString( R.string.schedule_block_title_sessions); } batch.add(ContentProviderOperation .newInsert(ScheduleContract.Blocks.CONTENT_URI) .withValue(ScheduleContract.Blocks.BLOCK_ID, blockId) .withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType) .withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle) .withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime) .withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime) .build()); blockIds.add(blockId); } else if (!sandboxBlocks.containsKey(blockId) && !blockIds.contains(blockId) && EVENT_TYPE_SANDBOX.equals(sessionSubtype)) { // New sandbox-only block, add insert operation to map String blockType = ScheduleContract.Blocks.BLOCK_TYPE_SANDBOX; String blockTitle = mContext.getString( R.string.schedule_block_title_sandbox); sandboxBlocks.put(blockId, ContentProviderOperation .newInsert(ScheduleContract.Blocks.CONTENT_URI) .withValue(ScheduleContract.Blocks.BLOCK_ID, blockId) .withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType) .withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle) .withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime) .withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime) .build()); } // Insert session info final ContentProviderOperation.Builder builder; if (EVENT_TYPE_SANDBOX.equals(sessionSubtype)) { // Sandbox companies go in the special sandbox table builder = ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(ScheduleContract.Sandbox.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(ScheduleContract.Sandbox.COMPANY_ID, sessionId) .withValue(ScheduleContract.Sandbox.COMPANY_NAME, sessionTitle) .withValue(ScheduleContract.Sandbox.COMPANY_DESC, sessionAbstract) .withValue(ScheduleContract.Sandbox.COMPANY_URL, makeSessionUrl(sessionId)) .withValue(ScheduleContract.Sandbox.COMPANY_LOGO_URL, session.getIconUrl()) .withValue(ScheduleContract.Sandbox.ROOM_ID, sanitizeId(session.getLocation())) .withValue(ScheduleContract.Sandbox.TRACK_ID, (track != null ? track.getId() : null)) .withValue(ScheduleContract.Sandbox.BLOCK_ID, blockId); batch.add(builder.build()); } else { // All other fields go in the normal sessions table builder = ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Sessions.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(Sessions.SESSION_ID, sessionId) .withValue(Sessions.SESSION_TYPE, sessionSubtype) .withValue(Sessions.SESSION_LEVEL, null) // Not available .withValue(Sessions.SESSION_TITLE, sessionTitle) .withValue(Sessions.SESSION_ABSTRACT, sessionAbstract) .withValue(Sessions.SESSION_HASHTAGS, hashtag) .withValue(Sessions.SESSION_TAGS, null) // Not available .withValue(Sessions.SESSION_URL, makeSessionUrl(sessionId)) .withValue(Sessions.SESSION_LIVESTREAM_URL, isLivestream ? youtubeUrl : null) .withValue(Sessions.SESSION_MODERATOR_URL, null) // Not available .withValue(Sessions.SESSION_REQUIREMENTS, null) // Not available .withValue(Sessions.SESSION_STARRED, inSchedule) .withValue(Sessions.SESSION_YOUTUBE_URL, isLivestream ? null : youtubeUrl) .withValue(Sessions.SESSION_PDF_URL, null) // Not available .withValue(Sessions.SESSION_NOTES_URL, null) // Not available .withValue(Sessions.ROOM_ID, sanitizeId(session.getLocation())) .withValue(Sessions.BLOCK_ID, blockId); batch.add(builder.build()); } // Replace all session speakers final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId); batch.add(ContentProviderOperation .newDelete(ScheduleContract .addCallerIsSyncAdapterParameter(sessionSpeakersUri)) .build()); List<String> presenterIds = session.getPresenterIds(); if (presenterIds != null) { for (String presenterId : presenterIds) { batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri) .withValue(SessionsSpeakers.SESSION_ID, sessionId) .withValue(SessionsSpeakers.SPEAKER_ID, presenterId).build()); } } // Add track mapping if (track != null) { String trackId = track.getId(); if (trackId != null) { final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Sessions.buildTracksDirUri(sessionId)); batch.add(ContentProviderOperation.newInsert(sessionTracksUri) .withValue(ScheduleDatabase.SessionsTracks.SESSION_ID, sessionId) .withValue(ScheduleDatabase.SessionsTracks.TRACK_ID, trackId).build()); } } // Codelabs: Add mapping to codelab table if (EVENT_TYPE_CODELAB.equals(sessionSubtype)) { final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Sessions.buildTracksDirUri(sessionId)); batch.add(ContentProviderOperation.newInsert(sessionTracksUri) .withValue(ScheduleDatabase.SessionsTracks.SESSION_ID, sessionId) .withValue(ScheduleDatabase.SessionsTracks.TRACK_ID, "CODE_LABS").build()); } } // Insert sandbox-only blocks batch.addAll(sandboxBlocks.values()); } } return batch; } private String makeSessionUrl(String sessionId) { if (TextUtils.isEmpty(sessionId)) { return null; } return BASE_SESSION_URL + sessionId; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import android.content.ContentProviderOperation; import android.content.Context; import android.database.Cursor; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.Lists; import com.google.api.services.googledevelopers.Googledevelopers; import com.google.api.services.googledevelopers.model.FeedbackResponse; import com.google.api.services.googledevelopers.model.ModifyFeedbackRequest; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.*; public class FeedbackHandler { private static final String TAG = makeLogTag(FeedbackHandler.class); private Context mContext; public FeedbackHandler(Context context) { mContext = context; } public ArrayList<ContentProviderOperation> uploadNew(Googledevelopers conferenceApi) { // Collect rows of feedback Cursor feedbackCursor = mContext.getContentResolver().query( ScheduleContract.Feedback.CONTENT_URI, null, null, null, null); int sessionIdIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.SESSION_ID); int ratingIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.SESSION_RATING); int relIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_RELEVANCE); int contentIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_CONTENT); int speakerIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_SPEAKER); int willUseIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_WILLUSE); int commentsIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.COMMENTS); final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); while (feedbackCursor.moveToNext()) { String sessionId = feedbackCursor.getString(sessionIdIndex); LOGI(TAG, "Uploading feedback for: " + sessionId); int rating = feedbackCursor.getInt(ratingIndex); int answerRelevance = feedbackCursor.getInt(relIndex); int answerContent = feedbackCursor.getInt(contentIndex); int answerSpeaker = feedbackCursor.getInt(speakerIndex); int answerWillUseRaw = feedbackCursor.getInt(willUseIndex); boolean answerWillUse = (answerWillUseRaw != 0); String comments = feedbackCursor.getString(commentsIndex); ModifyFeedbackRequest feedbackRequest = new ModifyFeedbackRequest(); feedbackRequest.setOverallScore(rating); feedbackRequest.setRelevancyScore(answerRelevance); feedbackRequest.setContentScore(answerContent); feedbackRequest.setSpeakerScore(answerSpeaker); // In this case, -1 means the user didn't answer the question. if (answerWillUseRaw != -1) { feedbackRequest.setWillUse(answerWillUse); } // Only post something If the comments field isn't empty if (comments != null && comments.length() > 0) { feedbackRequest.setAdditionalFeedback(comments); } feedbackRequest.setSessionId(sessionId); feedbackRequest.setEventId(Config.EVENT_ID); try { Googledevelopers.Events.Sessions.Feedback feedback = conferenceApi.events().sessions() .feedback(Config.EVENT_ID, sessionId, feedbackRequest); FeedbackResponse response = feedback.execute(); if (response != null) { LOGI(TAG, "Successfully sent feedback for: " + sessionId + ", comment: " + comments); } else { LOGE(TAG, "Sending logs failed"); } } catch (IOException ioe) { LOGE(TAG, "Sending logs failed and caused IOE", ioe); return batch; } } feedbackCursor.close(); // Clear out feedback forms we've just uploaded batch.add(ContentProviderOperation.newDelete( ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Feedback.CONTENT_URI)) .build()); return batch; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import android.content.ContentProviderOperation; import android.content.Context; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.util.Lists; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.googledevelopers.Googledevelopers; import com.google.api.services.googledevelopers.model.PresenterResponse; import com.google.api.services.googledevelopers.model.PresentersResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import static com.google.android.apps.iosched.util.LogUtils.*; public class SpeakersHandler { private static final String TAG = makeLogTag(SpeakersHandler.class); public SpeakersHandler(Context context) {} public ArrayList<ContentProviderOperation> fetchAndParse( Googledevelopers conferenceAPI) throws IOException { PresentersResponse presenters; try { presenters = conferenceAPI.events().presenters().list(Config.EVENT_ID).execute(); if (presenters == null || presenters.getPresenters() == null) { throw new HandlerException("Speakers list was null."); } } catch (HandlerException e) { LOGE(TAG, "Error fetching speakers", e); return Lists.newArrayList(); } return buildContentProviderOperations(presenters); } public ArrayList<ContentProviderOperation> parseString(String json) { JsonFactory jsonFactory = new GsonFactory(); try { PresentersResponse presenters = jsonFactory.fromString(json, PresentersResponse.class); return buildContentProviderOperations(presenters); } catch (IOException e) { LOGE(TAG, "Error reading speakers from packaged data", e); return Lists.newArrayList(); } } private ArrayList<ContentProviderOperation> buildContentProviderOperations( PresentersResponse presenters) { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); if (presenters != null) { List<PresenterResponse> presenterList = presenters.getPresenters(); int numSpeakers = presenterList.size(); if (numSpeakers > 0) { LOGI(TAG, "Updating presenters data"); // Clear out existing speakers batch.add(ContentProviderOperation.newDelete( ScheduleContract.addCallerIsSyncAdapterParameter( Speakers.CONTENT_URI)) .build()); // Insert latest speaker data for (PresenterResponse presenter : presenterList) { // Hack: Fix speaker URL so that it's not being resized // Depends on thumbnail URL being exactly in the format we want String thumbnail = presenter.getThumbnailUrl(); if (thumbnail != null) { thumbnail = thumbnail.replace("?sz=50", "?sz=100"); } batch.add(ContentProviderOperation.newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Speakers.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(Speakers.SPEAKER_ID, presenter.getId()) .withValue(Speakers.SPEAKER_NAME, presenter.getName()) .withValue(Speakers.SPEAKER_ABSTRACT, presenter.getBio()) .withValue(Speakers.SPEAKER_IMAGE_URL, thumbnail) .withValue(Speakers.SPEAKER_URL, presenter.getPlusoneUrl()) .build()); } } } return batch; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.provider.ScheduleContract; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.Context; import android.content.OperationApplicationException; import android.os.RemoteException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; public abstract class JSONHandler { protected static Context mContext; public JSONHandler(Context context) { mContext = context; } public abstract ArrayList<ContentProviderOperation> parse(String json) throws IOException; public final void parseAndApply(String json) throws IOException { try { final ContentResolver resolver = mContext.getContentResolver(); ArrayList<ContentProviderOperation> batch = parse(json); resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch); } catch (RemoteException e) { throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { throw new RuntimeException("Problem applying batch operation", e); } } public static String parseResource(Context context, int resource) throws IOException { InputStream is = context.getResources().openRawResource(resource); Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } return writer.toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.Day; import com.google.android.apps.iosched.io.model.EventSlots; import com.google.android.apps.iosched.io.model.TimeSlot; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.gson.Gson; import android.content.ContentProviderOperation; import android.content.Context; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class BlocksHandler extends JSONHandler { private static final String TAG = makeLogTag(BlocksHandler.class); public BlocksHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); try { Gson gson = new Gson(); EventSlots eventSlots = gson.fromJson(json, EventSlots.class); int numDays = eventSlots.day.length; //2011-05-10T07:00:00.000-07:00 for (int i = 0; i < numDays; i++) { Day day = eventSlots.day[i]; String date = day.date; TimeSlot[] timeSlots = day.slot; for (TimeSlot timeSlot : timeSlots) { parseSlot(date, timeSlot, batch); } } } catch (Throwable e) { LOGE(TAG, e.toString()); } return batch; } private static void parseSlot(String date, TimeSlot slot, ArrayList<ContentProviderOperation> batch) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(Blocks.CONTENT_URI)); //LOGD(TAG, "Inside parseSlot:" + date + ", " + slot); String start = slot.start; String end = slot.end; String type = Blocks.BLOCK_TYPE_GENERIC; if (slot.type != null) { type = slot.type; } String title = "N_D"; if (slot.title != null) { title = slot.title; } String startTime = date + "T" + start + ":00.000-07:00"; String endTime = date + "T" + end + ":00.000-07:00"; LOGV(TAG, "startTime:" + startTime); long startTimeL = ParserUtils.parseTime(startTime); long endTimeL = ParserUtils.parseTime(endTime); final String blockId = Blocks.generateBlockId(startTimeL, endTimeL); LOGV(TAG, "blockId:" + blockId); LOGV(TAG, "title:" + title); LOGV(TAG, "start:" + startTimeL); builder.withValue(Blocks.BLOCK_ID, blockId); builder.withValue(Blocks.BLOCK_TITLE, title); builder.withValue(Blocks.BLOCK_START, startTimeL); builder.withValue(Blocks.BLOCK_END, endTimeL); builder.withValue(Blocks.BLOCK_TYPE, type); builder.withValue(Blocks.BLOCK_META, slot.meta); batch.add(builder.build()); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import android.content.ContentProviderOperation; import android.content.Context; import android.graphics.Color; import com.google.android.apps.iosched.io.model.Track; import com.google.android.apps.iosched.io.model.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.gson.Gson; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class TracksHandler extends JSONHandler { private static final String TAG = makeLogTag(TracksHandler.class); public TracksHandler(Context context) { super(context); } @Override public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); batch.add(ContentProviderOperation.newDelete( ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Tracks.CONTENT_URI)).build()); Tracks tracksJson = new Gson().fromJson(json, Tracks.class); int noOfTracks = tracksJson.getTrack().length; for (int i = 0; i < noOfTracks; i++) { parseTrack(tracksJson.getTrack()[i], batch); } return batch; } private static void parseTrack(Track track, ArrayList<ContentProviderOperation> batch) { ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Tracks.CONTENT_URI)); builder.withValue(ScheduleContract.Tracks.TRACK_ID, track.id); builder.withValue(ScheduleContract.Tracks.TRACK_NAME, track.name); builder.withValue(ScheduleContract.Tracks.TRACK_COLOR, Color.parseColor(track.color)); builder.withValue(ScheduleContract.Tracks.TRACK_ABSTRACT, track._abstract); builder.withValue(ScheduleContract.Tracks.TRACK_LEVEL, track.level); builder.withValue(ScheduleContract.Tracks.TRACK_ORDER_IN_LEVEL, track.order_in_level); builder.withValue(ScheduleContract.Tracks.TRACK_META, track.meta); builder.withValue(ScheduleContract.Tracks.TRACK_HASHTAG, ParserUtils.sanitizeId(track.name)); batch.add(builder.build()); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import android.content.ContentProviderOperation; import android.content.Context; import android.util.Log; import com.google.android.apps.iosched.io.map.model.MapConfig; import com.google.android.apps.iosched.io.map.model.MapResponse; import com.google.android.apps.iosched.io.map.model.Marker; import com.google.android.apps.iosched.io.map.model.Tile; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.MapUtils; import com.google.gson.Gson; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class MapPropertyHandler extends JSONHandler { private static final String TAG = makeLogTag(MapPropertyHandler.class); private Collection<Tile> mTiles; public MapPropertyHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); MapResponse mapJson = new Gson().fromJson(json, MapResponse.class); parseTileOverlays(mapJson.tiles, batch, mContext); parseMarkers(mapJson.markers, batch); parseConfig(mapJson.config, mContext); mTiles = mapJson.tiles.values(); return batch; } private void parseConfig(MapConfig config, Context mContext) { boolean enableMyLocation = config.enableMyLocation; MapUtils.setMyLocationEnabled(mContext,enableMyLocation); } private void parseMarkers(Map<String, Marker[]> markers, ArrayList<ContentProviderOperation> batch) { for (Entry<String, Marker[]> entry : markers.entrySet()) { String floor = entry.getKey(); // add each Marker for (Marker marker : entry.getValue()) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(ScheduleContract.MapMarkers.CONTENT_URI)); builder.withValue(ScheduleContract.MapMarkers.MARKER_ID, marker.id); builder.withValue(ScheduleContract.MapMarkers.MARKER_FLOOR, floor); builder.withValue(ScheduleContract.MapMarkers.MARKER_LABEL, marker.title); builder.withValue(ScheduleContract.MapMarkers.MARKER_LATITUDE, marker.lat); builder.withValue(ScheduleContract.MapMarkers.MARKER_LONGITUDE, marker.lng); builder.withValue(ScheduleContract.MapMarkers.MARKER_TYPE, marker.type); builder.withValue(ScheduleContract.MapMarkers.MARKER_TRACK, marker.track); batch.add(builder.build()); } } } private void parseTileOverlays(Map<String, Tile> tiles, ArrayList<ContentProviderOperation> batch, Context context) { for (Entry<String, Tile> entry : tiles.entrySet()) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(ScheduleContract.MapTiles.CONTENT_URI)); String floor = entry.getKey(); Tile value = entry.getValue(); builder.withValue( ScheduleContract.MapTiles.TILE_FLOOR, floor); builder.withValue( ScheduleContract.MapTiles.TILE_FILE, value.filename); builder.withValue( ScheduleContract.MapTiles.TILE_URL, value.url); Log.d(TAG, "adding overlay: " + floor + ", " + value.filename); /* * Setup the tile overlay file. Copy it from the app assets or * download it if it does not exist locally. This is done here to * ensure that the data stored in the content provider always points * to valid tile files. */ batch.add(builder.build()); } } public Collection<Tile> getTiles(){ return mTiles; } }
Java