code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
package org.anddev.andengine.entity.particle.modifier;
import org.anddev.andengine.entity.particle.Particle;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:36:18 - 29.06.2010
*/
public class RotationModifier extends BaseSingleValueSpanModifier {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public RotationModifier(final float pFromRotation, final float pToRotation, final float pFromTime, final float pToTime) {
super(pFromRotation, pToRotation, pFromTime, pToTime);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected void onSetInitialValue(final Particle pParticle, final float pRotation) {
pParticle.setRotation(pRotation);
}
@Override
protected void onSetValue(final Particle pParticle, final float pRotation) {
pParticle.setRotation(pRotation);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.entity.particle.modifier;
import org.anddev.andengine.entity.particle.Particle;
import org.anddev.andengine.entity.particle.initializer.IParticleInitializer;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:06:05 - 14.03.2010
*/
public interface IParticleModifier extends IParticleInitializer {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onUpdateParticle(final Particle pParticle);
}
| Java |
package org.anddev.andengine.entity.particle.modifier;
import org.anddev.andengine.entity.particle.Particle;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:10:16 - 04.05.2010
*/
public abstract class BaseSingleValueSpanModifier implements IParticleModifier {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float mFromValue;
private final float mToValue;
private final float mFromTime;
private final float mToTime;
private final float mDuration;
private final float mSpanValue;
// ===========================================================
// Constructors
// ===========================================================
public BaseSingleValueSpanModifier(final float pFromValue, final float pToValue, final float pFromTime, final float pToTime) {
this.mFromValue = pFromValue;
this.mToValue = pToValue;
this.mFromTime = pFromTime;
this.mToTime = pToTime;
this.mSpanValue = this.mToValue - this.mFromValue;
this.mDuration = this.mToTime - this.mFromTime;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract void onSetInitialValue(final Particle pParticle, final float pValue);
protected abstract void onSetValue(final Particle pParticle, final float pValue);
@Override
public void onInitializeParticle(final Particle pParticle) {
this.onSetInitialValue(pParticle, this.mFromValue);
}
@Override
public void onUpdateParticle(final Particle pParticle) {
final float lifeTime = pParticle.getLifeTime();
if(lifeTime > this.mFromTime && lifeTime < this.mToTime) {
final float percent = (lifeTime - this.mFromTime) / this.mDuration;
this.onSetValueInternal(pParticle, percent);
}
}
protected void onSetValueInternal(final Particle pParticle, final float pPercent) {
this.onSetValue(pParticle, this.calculateValue(pPercent));
}
protected final float calculateValue(final float pPercent) {
return this.mFromValue + this.mSpanValue * pPercent;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.entity.particle.modifier;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.entity.particle.Particle;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 21:21:10 - 14.03.2010
*/
public class OffCameraExpireModifier implements IParticleModifier {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final Camera mCamera;
// ===========================================================
// Constructors
// ===========================================================
public OffCameraExpireModifier(final Camera pCamera) {
this.mCamera = pCamera;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public Camera getCamera() {
return this.mCamera;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onInitializeParticle(final Particle pParticle) {
}
@Override
public void onUpdateParticle(final Particle pParticle) {
if(!this.mCamera.isRectangularShapeVisible(pParticle)) {
pParticle.setDead(true);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.entity.particle.modifier;
import org.anddev.andengine.entity.particle.Particle;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:19:46 - 29.06.2010
*/
public abstract class BaseDoubleValueSpanModifier extends BaseSingleValueSpanModifier {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float mFromValueB;
private final float mToValueB;
private final float mSpanValueB;
// ===========================================================
// Constructors
// ===========================================================
public BaseDoubleValueSpanModifier(final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromTime, final float pToTime) {
super(pFromValueA, pToValueA, pFromTime, pToTime);
this.mFromValueB = pFromValueB;
this.mToValueB = pToValueB;
this.mSpanValueB = this.mToValueB - this.mFromValueB;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
@Deprecated
protected void onSetValue(final Particle pParticle, final float pValue) { }
protected abstract void onSetInitialValues(final Particle pParticle, final float pValueA, final float pValueB);
protected abstract void onSetValues(final Particle pParticle, final float pValueA, final float pValueB);
@Override
public void onSetInitialValue(final Particle pParticle, final float pValueA) {
this.onSetInitialValues(pParticle, pValueA, this.mFromValueB);
}
@Override
protected void onSetValueInternal(final Particle pParticle, final float pPercent) {
this.onSetValues(pParticle, super.calculateValue(pPercent), this.calculateValueB(pPercent));
}
// ===========================================================
// Methods
// ===========================================================
protected final float calculateValueB(final float pPercent) {
return this.mFromValueB + this.mSpanValueB * pPercent;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.entity.particle.modifier;
import org.anddev.andengine.entity.particle.Particle;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:19:46 - 29.06.2010
*/
public abstract class BaseTripleValueSpanModifier extends BaseDoubleValueSpanModifier {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float mFromValueC;
private final float mToValueC;
private final float mSpanValueC;
// ===========================================================
// Constructors
// ===========================================================
public BaseTripleValueSpanModifier(final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromValueC, final float pToValueC, final float pFromTime, final float pToTime) {
super(pFromValueA, pToValueA, pFromValueB, pToValueB, pFromTime, pToTime);
this.mFromValueC = pFromValueC;
this.mToValueC = pToValueC;
this.mSpanValueC = this.mToValueC - this.mFromValueC;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract void onSetInitialValues(final Particle pParticle, final float pValueA, final float pValueB, final float pValueC);
protected abstract void onSetValues(final Particle pParticle, final float pValueA, final float pValueB, final float pValueC);
@Override
@Deprecated
protected void onSetValues(final Particle pParticle, final float pValueA, final float pValueB) { }
@Override
public void onSetInitialValues(final Particle pParticle, final float pValueA, final float pValueB) {
this.onSetInitialValues(pParticle, pValueA, pValueB, this.mFromValueC);
}
@Override
protected void onSetValueInternal(final Particle pParticle, final float pPercent) {
this.onSetValues(pParticle, super.calculateValue(pPercent), super.calculateValueB(pPercent), this.calculateValueC(pPercent));
}
// ===========================================================
// Methods
// ===========================================================
private final float calculateValueC(final float pPercent) {
return this.mFromValueC + this.mSpanValueC * pPercent;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.entity.particle.modifier;
import org.anddev.andengine.entity.particle.Particle;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 21:21:10 - 14.03.2010
*/
public class AlphaModifier extends BaseSingleValueSpanModifier {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public AlphaModifier(final float pFromAlpha, final float pToAlpha, final float pFromTime, final float pToTime) {
super(pFromAlpha, pToAlpha, pFromTime, pToTime);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected void onSetInitialValue(final Particle pParticle, final float pAlpha) {
pParticle.setAlpha(pAlpha);
}
@Override
protected void onSetValue(final Particle pParticle, final float pAlpha) {
pParticle.setAlpha(pAlpha);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.entity.shape;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.collision.RectangularShapeCollisionChecker;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.entity.primitive.Line;
import org.anddev.andengine.opengl.vertex.VertexBuffer;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:37:50 - 04.04.2010
*/
public abstract class RectangularShape extends Shape {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected float mBaseWidth;
protected float mBaseHeight;
protected float mWidth;
protected float mHeight;
protected final VertexBuffer mVertexBuffer;
// ===========================================================
// Constructors
// ===========================================================
public RectangularShape(final float pX, final float pY, final float pWidth, final float pHeight, final VertexBuffer pVertexBuffer) {
super(pX, pY);
this.mBaseWidth = pWidth;
this.mBaseHeight = pHeight;
this.mWidth = pWidth;
this.mHeight = pHeight;
this.mVertexBuffer = pVertexBuffer;
this.mRotationCenterX = pWidth * 0.5f;
this.mRotationCenterY = pHeight * 0.5f;
this.mScaleCenterX = this.mRotationCenterX;
this.mScaleCenterY = this.mRotationCenterY;
}
// ===========================================================
// Getter & Setter
// ===========================================================
@Override
public VertexBuffer getVertexBuffer() {
return this.mVertexBuffer;
}
@Override
public float getWidth() {
return this.mWidth;
}
@Override
public float getHeight() {
return this.mHeight;
}
@Override
public float getBaseWidth() {
return this.mBaseWidth;
}
@Override
public float getBaseHeight() {
return this.mBaseHeight;
}
public void setWidth(final float pWidth) {
this.mWidth = pWidth;
this.updateVertexBuffer();
}
public void setHeight(final float pHeight) {
this.mHeight = pHeight;
this.updateVertexBuffer();
}
public void setSize(final float pWidth, final float pHeight) {
this.mWidth = pWidth;
this.mHeight = pHeight;
this.updateVertexBuffer();
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
public void setBaseSize() {
if(this.mWidth != this.mBaseWidth || this.mHeight != this.mBaseHeight) {
this.mWidth = this.mBaseWidth;
this.mHeight = this.mBaseHeight;
this.updateVertexBuffer();
}
}
@Override
protected boolean isCulled(final Camera pCamera) { // TODO Advanced culling!
final float x = this.mX;
final float y = this.mY;
return x > pCamera.getMaxX()
|| y > pCamera.getMaxY()
|| x + this.getWidth() < pCamera.getMinX()
|| y + this.getHeight() < pCamera.getMinY();
}
@Override
protected void drawVertices(final GL10 pGL, final Camera pCamera) {
pGL.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
}
@Override
public void reset() {
super.reset();
this.setBaseSize();
final float baseWidth = this.getBaseWidth();
final float baseHeight = this.getBaseHeight();
this.mRotationCenterX = baseWidth * 0.5f;
this.mRotationCenterY = baseHeight * 0.5f;
this.mScaleCenterX = this.mRotationCenterX;
this.mScaleCenterY = this.mRotationCenterY;
}
@Override
public boolean contains(final float pX, final float pY) {
return RectangularShapeCollisionChecker.checkContains(this, pX, pY);
}
@Override
public float[] getSceneCenterCoordinates() {
return this.convertLocalToSceneCoordinates(this.mWidth * 0.5f, this.mHeight * 0.5f);
}
@Override
public boolean collidesWith(final IShape pOtherShape) {
if(pOtherShape instanceof RectangularShape) {
final RectangularShape pOtherRectangularShape = (RectangularShape) pOtherShape;
return RectangularShapeCollisionChecker.checkCollision(this, pOtherRectangularShape);
} else if(pOtherShape instanceof Line) {
final Line line = (Line) pOtherShape;
return RectangularShapeCollisionChecker.checkCollision(this, line);
} else {
return false;
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.entity.shape;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.scene.Scene.ITouchArea;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:32:52 - 07.07.2010
*/
public interface IShape extends IEntity, ITouchArea {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public boolean isCullingEnabled();
public void setCullingEnabled(final boolean pCullingEnabled);
public float getWidth();
public float getHeight();
public float getBaseWidth();
public float getBaseHeight();
public float getWidthScaled();
public float getHeightScaled();
// public boolean isVisible(final Camera pCamera); // TODO. Could be use for automated culling.
public boolean collidesWith(final IShape pOtherShape);
public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction);
} | Java |
package org.anddev.andengine.entity.shape;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.entity.Entity;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.buffer.BufferObjectManager;
import org.anddev.andengine.opengl.util.GLHelper;
import org.anddev.andengine.opengl.vertex.VertexBuffer;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:51:27 - 13.03.2010
*/
public abstract class Shape extends Entity implements IShape {
// ===========================================================
// Constants
// ===========================================================
public static final int BLENDFUNCTION_SOURCE_DEFAULT = GL10.GL_SRC_ALPHA;
public static final int BLENDFUNCTION_DESTINATION_DEFAULT = GL10.GL_ONE_MINUS_SRC_ALPHA;
public static final int BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT = GL10.GL_ONE;
public static final int BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT = GL10.GL_ONE_MINUS_SRC_ALPHA;
// ===========================================================
// Fields
// ===========================================================
protected int mSourceBlendFunction = BLENDFUNCTION_SOURCE_DEFAULT;
protected int mDestinationBlendFunction = BLENDFUNCTION_DESTINATION_DEFAULT;
private boolean mCullingEnabled = false;
// ===========================================================
// Constructors
// ===========================================================
public Shape(final float pX, final float pY) {
super(pX, pY);
}
// ===========================================================
// Getter & Setter
// ===========================================================
@Override
public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction) {
this.mSourceBlendFunction = pSourceBlendFunction;
this.mDestinationBlendFunction = pDestinationBlendFunction;
}
@Override
public boolean isCullingEnabled() {
return this.mCullingEnabled;
}
@Override
public void setCullingEnabled(final boolean pCullingEnabled) {
this.mCullingEnabled = pCullingEnabled;
}
@Override
public float getWidthScaled() {
return this.getWidth() * this.mScaleX;
}
@Override
public float getHeightScaled() {
return this.getHeight() * this.mScaleY;
}
public boolean isVertexBufferManaged() {
return this.getVertexBuffer().isManaged();
}
/**
* @param pVertexBufferManaged when passing <code>true</code> this {@link Shape} will make its {@link VertexBuffer} unload itself from the active {@link BufferObjectManager}, when this {@link Shape} is finalized/garbage-collected. <b><u>WARNING:</u></b> When passing <code>false</code> one needs to take care of that by oneself!
*/
public void setVertexBufferManaged(final boolean pVertexBufferManaged) {
this.getVertexBuffer().setManaged(pVertexBufferManaged);
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract void onUpdateVertexBuffer();
protected abstract VertexBuffer getVertexBuffer();
protected abstract void drawVertices(final GL10 pGL, final Camera pCamera);
@Override
protected void doDraw(final GL10 pGL, final Camera pCamera) {
this.onInitDraw(pGL);
this.onApplyVertices(pGL);
this.drawVertices(pGL, pCamera);
}
@Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
return false;
}
/**
* Will only be performed if {@link Shape#isCullingEnabled()} is true.
* @param pCamera
* @return <code>true</code> when this object is visible by the {@link Camera}, <code>false</code> otherwise.
*/
protected abstract boolean isCulled(final Camera pCamera);
@Override
protected void onManagedDraw(final GL10 pGL, final Camera pCamera) {
if(!this.mCullingEnabled || !this.isCulled(pCamera)) {
super.onManagedDraw(pGL, pCamera);
}
}
@Override
public void reset() {
super.reset();
this.mSourceBlendFunction = BLENDFUNCTION_SOURCE_DEFAULT;
this.mDestinationBlendFunction = BLENDFUNCTION_DESTINATION_DEFAULT;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
final VertexBuffer vertexBuffer = this.getVertexBuffer();
if(vertexBuffer.isManaged()) {
vertexBuffer.unloadFromActiveBufferObjectManager();
}
}
// ===========================================================
// Methods
// ===========================================================
protected void onInitDraw(final GL10 pGL) {
GLHelper.setColor(pGL, this.mRed, this.mGreen, this.mBlue, this.mAlpha);
GLHelper.enableVertexArray(pGL);
GLHelper.blendFunction(pGL, this.mSourceBlendFunction, this.mDestinationBlendFunction);
}
protected void onApplyVertices(final GL10 pGL) {
if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) {
final GL11 gl11 = (GL11)pGL;
this.getVertexBuffer().selectOnHardware(gl11);
GLHelper.vertexZeroPointer(gl11);
} else {
GLHelper.vertexPointer(pGL, this.getVertexBuffer().getFloatBuffer());
}
}
protected void updateVertexBuffer() {
this.onUpdateVertexBuffer();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.entity;
import java.util.Comparator;
import java.util.List;
import org.anddev.andengine.util.sort.InsertionSorter;
public class ZIndexSorter extends InsertionSorter<IEntity> {
// ===========================================================
// Constants
// ===========================================================
private static ZIndexSorter INSTANCE;
// ===========================================================
// Fields
// ===========================================================
private final Comparator<IEntity> mZIndexComparator = new Comparator<IEntity>() {
@Override
public int compare(final IEntity pEntityA, final IEntity pEntityB) {
return pEntityA.getZIndex() - pEntityB.getZIndex();
}
};
// ===========================================================
// Constructors
// ===========================================================
private ZIndexSorter() {
}
public static ZIndexSorter getInstance() {
if(INSTANCE == null) {
INSTANCE = new ZIndexSorter();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void sort(final IEntity[] pEntities) {
this.sort(pEntities, this.mZIndexComparator);
}
public void sort(final IEntity[] pEntities, final int pStart, final int pEnd) {
this.sort(pEntities, pStart, pEnd, this.mZIndexComparator);
}
public void sort(final List<IEntity> pEntities) {
this.sort(pEntities, this.mZIndexComparator);
}
public void sort(final List<IEntity> pEntities, final int pStart, final int pEnd) {
this.sort(pEntities, pStart, pEnd, this.mZIndexComparator);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | Java |
package org.anddev.andengine.audio.sound;
import org.anddev.andengine.audio.BaseAudioManager;
import android.media.AudioManager;
import android.media.SoundPool;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:22:59 - 11.03.2010
*/
public class SoundManager extends BaseAudioManager<Sound> {
// ===========================================================
// Constants
// ===========================================================
private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5;
// ===========================================================
// Fields
// ===========================================================
private final SoundPool mSoundPool;
// ===========================================================
// Constructors
// ===========================================================
public SoundManager() {
this(MAX_SIMULTANEOUS_STREAMS_DEFAULT);
}
public SoundManager(final int pMaxSimultaneousStreams) {
this.mSoundPool = new SoundPool(pMaxSimultaneousStreams, AudioManager.STREAM_MUSIC, 0);
}
// ===========================================================
// Getter & Setter
// ===========================================================
SoundPool getSoundPool() {
return this.mSoundPool;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
@Override
public void releaseAll() {
super.releaseAll();
this.mSoundPool.release();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.audio.sound;
import org.anddev.andengine.audio.BaseAudioEntity;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:22:15 - 11.03.2010
*/
public class Sound extends BaseAudioEntity {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final int mSoundID;
private int mStreamID = 0;
private int mLoopCount = 0;
private float mRate = 1.0f;
// ===========================================================
// Constructors
// ===========================================================
Sound(final SoundManager pSoundManager, final int pSoundID) {
super(pSoundManager);
this.mSoundID = pSoundID;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void setLoopCount(final int pLoopCount) {
this.mLoopCount = pLoopCount;
if(this.mStreamID != 0) {
this.getAudioManager().getSoundPool().setLoop(this.mStreamID, pLoopCount);
}
}
public void setRate(final float pRate) {
this.mRate = pRate;
if(this.mStreamID != 0) {
this.getAudioManager().getSoundPool().setRate(this.mStreamID, pRate);
}
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
@Override
protected SoundManager getAudioManager() {
return (SoundManager)super.getAudioManager();
}
@Override
public void play() {
final float masterVolume = this.getMasterVolume();
final float leftVolume = this.mLeftVolume * masterVolume;
final float rightVolume = this.mRightVolume * masterVolume;
this.mStreamID = this.getAudioManager().getSoundPool().play(this.mSoundID, leftVolume, rightVolume, 1, this.mLoopCount, this.mRate);
}
@Override
public void stop() {
if(this.mStreamID != 0) {
this.getAudioManager().getSoundPool().stop(this.mStreamID);
}
}
@Override
public void resume() {
if(this.mStreamID != 0) {
this.getAudioManager().getSoundPool().resume(this.mStreamID);
}
}
@Override
public void pause() {
if(this.mStreamID != 0) {
this.getAudioManager().getSoundPool().pause(this.mStreamID);
}
}
@Override
public void release() {
}
@Override
public void setLooping(final boolean pLooping) {
this.setLoopCount((pLooping) ? -1 : 0);
}
@Override
public void setVolume(final float pLeftVolume, final float pRightVolume) {
super.setVolume(pLeftVolume, pRightVolume);
if(this.mStreamID != 0){
final float masterVolume = this.getMasterVolume();
final float leftVolume = this.mLeftVolume * masterVolume;
final float rightVolume = this.mRightVolume * masterVolume;
this.getAudioManager().getSoundPool().setVolume(this.mStreamID, leftVolume, rightVolume);
}
}
@Override
public void onMasterVolumeChanged(final float pMasterVolume) {
this.setVolume(this.mLeftVolume, this.mRightVolume);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.audio.sound;
import java.io.FileDescriptor;
import java.io.IOException;
import android.content.Context;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:23:03 - 11.03.2010
*/
public class SoundFactory {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static String sAssetBasePath = "";
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
/**
* @param pAssetBasePath must end with '<code>/</code>' or have <code>.length() == 0</code>.
*/
public static void setAssetBasePath(final String pAssetBasePath) {
if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) {
SoundFactory.sAssetBasePath = pAssetBasePath;
} else {
throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero.");
}
}
public static void reset() {
SoundFactory.setAssetBasePath("");
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static Sound createSoundFromPath(final SoundManager pSoundManager, final String pPath) throws IOException {
final int soundID = pSoundManager.getSoundPool().load(pPath, 1);
final Sound sound = new Sound(pSoundManager, soundID);
pSoundManager.add(sound);
return sound;
}
public static Sound createSoundFromAsset(final SoundManager pSoundManager, final Context pContext, final String pAssetPath) throws IOException {
final int soundID = pSoundManager.getSoundPool().load(pContext.getAssets().openFd(SoundFactory.sAssetBasePath + pAssetPath), 1);
final Sound sound = new Sound(pSoundManager, soundID);
pSoundManager.add(sound);
return sound;
}
public static Sound createSoundFromResource(final SoundManager pSoundManager, final Context pContext, final int pSoundResID) {
final int soundID = pSoundManager.getSoundPool().load(pContext, pSoundResID, 1);
final Sound sound = new Sound(pSoundManager, soundID);
pSoundManager.add(sound);
return sound;
}
public static Sound createSoundFromFileDescriptor(final SoundManager pSoundManager, final FileDescriptor pFileDescriptor, final long pOffset, final long pLength) throws IOException {
final int soundID = pSoundManager.getSoundPool().load(pFileDescriptor, pOffset, pLength, 1);
final Sound sound = new Sound(pSoundManager, soundID);
pSoundManager.add(sound);
return sound;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.audio.sound;
import org.anddev.andengine.util.Library;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:41:56 - 20.08.2010
*/
public class SoundLibrary extends Library<Sound> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.audio;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:35:37 - 13.06.2010
*/
public abstract class BaseAudioEntity implements IAudioEntity {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final IAudioManager<? extends IAudioEntity> mAudioManager;
protected float mLeftVolume = 1.0f;
protected float mRightVolume = 1.0f;
// ===========================================================
// Constructors
// ===========================================================
public BaseAudioEntity(final IAudioManager<? extends IAudioEntity> pAudioManager) {
this.mAudioManager = pAudioManager;
}
// ===========================================================
// Getter & Setter
// ===========================================================
protected IAudioManager<? extends IAudioEntity> getAudioManager() {
return this.mAudioManager;
}
public float getActualLeftVolume() {
return this.mLeftVolume * this.getMasterVolume();
}
public float getActualRightVolume() {
return this.mRightVolume * this.getMasterVolume();
}
protected float getMasterVolume() {
return this.mAudioManager.getMasterVolume();
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getVolume() {
return (this.mLeftVolume + this.mRightVolume) * 0.5f;
}
@Override
public float getLeftVolume() {
return this.mLeftVolume;
}
@Override
public float getRightVolume() {
return this.mRightVolume;
}
@Override
public final void setVolume(final float pVolume) {
this.setVolume(pVolume, pVolume);
}
@Override
public void setVolume(final float pLeftVolume, final float pRightVolume) {
this.mLeftVolume = pLeftVolume;
this.mRightVolume = pRightVolume;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.audio.music;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:05:49 - 13.06.2010
*/
public class MusicFactory {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static String sAssetBasePath = "";
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
/**
* @param pAssetBasePath must end with '<code>/</code>' or have <code>.length() == 0</code>.
*/
public static void setAssetBasePath(final String pAssetBasePath) {
if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) {
MusicFactory.sAssetBasePath = pAssetBasePath;
} else {
throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero.");
}
}
public static void reset() {
MusicFactory.setAssetBasePath("");
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static Music createMusicFromFile(final MusicManager pMusicManager, final File pFile) throws IOException {
final MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(new FileInputStream(pFile).getFD());
mediaPlayer.prepare();
final Music music = new Music(pMusicManager, mediaPlayer);
pMusicManager.add(music);
return music;
}
public static Music createMusicFromAsset(final MusicManager pMusicManager, final Context pContext, final String pAssetPath) throws IOException {
final MediaPlayer mediaPlayer = new MediaPlayer();
final AssetFileDescriptor assetFileDescritor = pContext.getAssets().openFd(MusicFactory.sAssetBasePath + pAssetPath);
mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength());
mediaPlayer.prepare();
final Music music = new Music(pMusicManager, mediaPlayer);
pMusicManager.add(music);
return music;
}
public static Music createMusicFromResource(final MusicManager pMusicManager, final Context pContext, final int pMusicResID) throws IOException {
final MediaPlayer mediaPlayer = MediaPlayer.create(pContext, pMusicResID);
mediaPlayer.prepare();
final Music music = new Music(pMusicManager, mediaPlayer);
pMusicManager.add(music);
return music;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.audio.music;
import org.anddev.andengine.audio.BaseAudioManager;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:01:23 - 13.06.2010
*/
public class MusicManager extends BaseAudioManager<Music> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public MusicManager() {
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.audio.music;
import org.anddev.andengine.audio.BaseAudioEntity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:53:12 - 13.06.2010
*/
public class Music extends BaseAudioEntity {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final MediaPlayer mMediaPlayer;
// ===========================================================
// Constructors
// ===========================================================
Music(final MusicManager pMusicManager, final MediaPlayer pMediaPlayer) {
super(pMusicManager);
this.mMediaPlayer = pMediaPlayer;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isPlaying() {
return this.mMediaPlayer.isPlaying();
}
public MediaPlayer getMediaPlayer() {
return this.mMediaPlayer;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected MusicManager getAudioManager() {
return (MusicManager)super.getAudioManager();
}
@Override
public void play() {
this.mMediaPlayer.start();
}
@Override
public void stop() {
this.mMediaPlayer.stop();
}
@Override
public void resume() {
this.mMediaPlayer.start();
}
@Override
public void pause() {
this.mMediaPlayer.pause();
}
@Override
public void release() {
this.mMediaPlayer.release();
}
@Override
public void setLooping(final boolean pLooping) {
this.mMediaPlayer.setLooping(pLooping);
}
@Override
public void setVolume(final float pLeftVolume, final float pRightVolume) {
super.setVolume(pLeftVolume, pRightVolume);
final float masterVolume = this.getAudioManager().getMasterVolume();
final float actualLeftVolume = pLeftVolume * masterVolume;
final float actualRightVolume = pRightVolume * masterVolume;
this.mMediaPlayer.setVolume(actualLeftVolume, actualRightVolume);
}
@Override
public void onMasterVolumeChanged(final float pMasterVolume) {
this.setVolume(this.mLeftVolume, this.mRightVolume);
}
// ===========================================================
// Methods
// ===========================================================
public void seekTo(final int pMilliseconds) {
this.mMediaPlayer.seekTo(pMilliseconds);
}
public void setOnCompletionListener(final OnCompletionListener pOnCompletionListener) {
this.mMediaPlayer.setOnCompletionListener(pOnCompletionListener);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.audio;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:02:06 - 13.06.2010
*/
public interface IAudioManager<T extends IAudioEntity> {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public float getMasterVolume();
public void setMasterVolume(final float pMasterVolume);
public void add(final T pAudioEntity);
public void releaseAll();
}
| Java |
package org.anddev.andengine.audio;
import java.util.ArrayList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 18:07:02 - 13.06.2010
*/
public abstract class BaseAudioManager<T extends IAudioEntity> implements IAudioManager<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected final ArrayList<T> mAudioEntities = new ArrayList<T>();
protected float mMasterVolume = 1.0f;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getMasterVolume() {
return this.mMasterVolume;
}
@Override
public void setMasterVolume(final float pMasterVolume) {
this.mMasterVolume = pMasterVolume;
final ArrayList<T> audioEntities = this.mAudioEntities;
for(int i = audioEntities.size() - 1; i >= 0; i--) {
final T audioEntity = audioEntities.get(i);
audioEntity.onMasterVolumeChanged(pMasterVolume);
}
}
@Override
public void add(final T pAudioEntity) {
this.mAudioEntities.add(pAudioEntity);
}
@Override
public void releaseAll() {
final ArrayList<T> audioEntities = this.mAudioEntities;
for(int i = audioEntities.size() - 1; i >= 0; i--) {
final T audioEntity = audioEntities.get(i);
audioEntity.stop();
audioEntity.release();
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.audio;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:53:29 - 13.06.2010
*/
public interface IAudioEntity {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void play();
public void pause();
public void resume();
public void stop();
public float getVolume();
public void setVolume(final float pVolume);
public float getLeftVolume();
public float getRightVolume();
public void setVolume(final float pLeftVolume, final float pRightVolume);
public void onMasterVolumeChanged(final float pMasterVolume);
public void setLooping(final boolean pLooping);
public void release();
}
| Java |
package org.anddev.andengine.ui.activity;
import org.anddev.andengine.audio.music.MusicManager;
import org.anddev.andengine.audio.sound.SoundManager;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.WakeLockOptions;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.opengl.font.FontManager;
import org.anddev.andengine.opengl.texture.TextureManager;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
import org.anddev.andengine.sensor.accelerometer.AccelerometerSensorOptions;
import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener;
import org.anddev.andengine.sensor.location.ILocationListener;
import org.anddev.andengine.sensor.location.LocationSensorOptions;
import org.anddev.andengine.sensor.orientation.IOrientationListener;
import org.anddev.andengine.sensor.orientation.OrientationSensorOptions;
import org.anddev.andengine.ui.IGameInterface;
import org.anddev.andengine.util.ActivityUtils;
import org.anddev.andengine.util.Debug;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.Gravity;
import android.widget.FrameLayout.LayoutParams;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:27:06 - 08.03.2010
*/
public abstract class BaseGameActivity extends BaseActivity implements IGameInterface {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected Engine mEngine;
private WakeLock mWakeLock;
protected RenderSurfaceView mRenderSurfaceView;
protected boolean mHasWindowFocused;
private boolean mPaused;
private boolean mGameLoaded;
// ===========================================================
// Constructors
// ===========================================================
@Override
protected void onCreate(final Bundle pSavedInstanceState) {
super.onCreate(pSavedInstanceState);
this.mPaused = true;
this.mEngine = this.onLoadEngine();
this.applyEngineOptions(this.mEngine.getEngineOptions());
this.onSetContentView();
}
@Override
protected void onResume() {
super.onResume();
if(this.mPaused && this.mHasWindowFocused) {
this.doResume();
}
}
@Override
public void onWindowFocusChanged(final boolean pHasWindowFocus) {
super.onWindowFocusChanged(pHasWindowFocus);
if(pHasWindowFocus) {
if(this.mPaused) {
this.doResume();
}
this.mHasWindowFocused = true;
} else {
if(!this.mPaused) {
this.doPause();
}
this.mHasWindowFocused = false;
}
}
@Override
protected void onPause() {
super.onPause();
if(!this.mPaused) {
this.doPause();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
this.mEngine.interruptUpdateThread();
this.onUnloadResources();
}
@Override
public void onUnloadResources() {
if(this.mEngine.getEngineOptions().needsMusic()) {
this.getMusicManager().releaseAll();
}
if(this.mEngine.getEngineOptions().needsSound()) {
this.getSoundManager().releaseAll();
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
public Engine getEngine() {
return this.mEngine;
}
public TextureManager getTextureManager() {
return this.mEngine.getTextureManager();
}
public FontManager getFontManager() {
return this.mEngine.getFontManager();
}
public SoundManager getSoundManager() {
return this.mEngine.getSoundManager();
}
public MusicManager getMusicManager() {
return this.mEngine.getMusicManager();
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onResumeGame() {
}
@Override
public void onPauseGame() {
}
// ===========================================================
// Methods
// ===========================================================
private void doResume() {
if(!this.mGameLoaded) {
this.onLoadResources();
final Scene scene = this.onLoadScene();
this.mEngine.onLoadComplete(scene);
this.onLoadComplete();
this.mGameLoaded = true;
}
this.mPaused = false;
this.acquireWakeLock(this.mEngine.getEngineOptions().getWakeLockOptions());
this.mEngine.onResume();
this.mRenderSurfaceView.onResume();
this.mEngine.start();
this.onResumeGame();
}
private void doPause() {
this.mPaused = true;
this.releaseWakeLock();
this.mEngine.onPause();
this.mEngine.stop();
this.mRenderSurfaceView.onPause();
this.onPauseGame();
}
public void runOnUpdateThread(final Runnable pRunnable) {
this.mEngine.runOnUpdateThread(pRunnable);
}
protected void onSetContentView() {
this.mRenderSurfaceView = new RenderSurfaceView(this);
this.mRenderSurfaceView.setEGLConfigChooser(false);
this.mRenderSurfaceView.setRenderer(this.mEngine);
this.setContentView(this.mRenderSurfaceView, this.createSurfaceViewLayoutParams());
}
private void acquireWakeLock(final WakeLockOptions pWakeLockOptions) {
if(pWakeLockOptions == WakeLockOptions.SCREEN_ON) {
ActivityUtils.keepScreenOn(this);
} else {
final PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(pWakeLockOptions.getFlag() | PowerManager.ON_AFTER_RELEASE, "AndEngine");
try {
this.mWakeLock.acquire();
} catch (final SecurityException e) {
Debug.e("You have to add\n\t<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>\nto your AndroidManifest.xml !", e);
}
}
}
private void releaseWakeLock() {
if(this.mWakeLock != null && this.mWakeLock.isHeld()) {
this.mWakeLock.release();
}
}
private void applyEngineOptions(final EngineOptions pEngineOptions) {
if(pEngineOptions.isFullscreen()) {
ActivityUtils.requestFullscreen(this);
}
if(pEngineOptions.needsMusic() || pEngineOptions.needsSound()) {
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
switch(pEngineOptions.getScreenOrientation()) {
case LANDSCAPE:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case PORTRAIT:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
}
}
protected LayoutParams createSurfaceViewLayoutParams() {
final LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
layoutParams.gravity = Gravity.CENTER;
return layoutParams;
}
protected void enableVibrator() {
this.mEngine.enableVibrator(this);
}
/**
* @see {@link Engine#enableLocationSensor(Context, ILocationListener, LocationSensorOptions)}
*/
protected void enableLocationSensor(final ILocationListener pLocationListener, final LocationSensorOptions pLocationSensorOptions) {
this.mEngine.enableLocationSensor(this, pLocationListener, pLocationSensorOptions);
}
/**
* @see {@link Engine#disableLocationSensor(Context)}
*/
protected void disableLocationSensor() {
this.mEngine.disableLocationSensor(this);
}
/**
* @see {@link Engine#enableAccelerometerSensor(Context, IAccelerometerListener)}
*/
protected boolean enableAccelerometerSensor(final IAccelerometerListener pAccelerometerListener) {
return this.mEngine.enableAccelerometerSensor(this, pAccelerometerListener);
}
/**
* @see {@link Engine#enableAccelerometerSensor(Context, IAccelerometerListener, AccelerometerSensorOptions)}
*/
protected boolean enableAccelerometerSensor(final IAccelerometerListener pAccelerometerListener, final AccelerometerSensorOptions pAccelerometerSensorOptions) {
return this.mEngine.enableAccelerometerSensor(this, pAccelerometerListener, pAccelerometerSensorOptions);
}
/**
* @see {@link Engine#disableAccelerometerSensor(Context)}
*/
protected boolean disableAccelerometerSensor() {
return this.mEngine.disableAccelerometerSensor(this);
}
/**
* @see {@link Engine#enableOrientationSensor(Context, IOrientationListener)}
*/
protected boolean enableOrientationSensor(final IOrientationListener pOrientationListener) {
return this.mEngine.enableOrientationSensor(this, pOrientationListener);
}
/**
* @see {@link Engine#enableOrientationSensor(Context, IOrientationListener, OrientationSensorOptions)}
*/
protected boolean enableOrientationSensor(final IOrientationListener pOrientationListener, final OrientationSensorOptions pLocationSensorOptions) {
return this.mEngine.enableOrientationSensor(this, pOrientationListener, pLocationSensorOptions);
}
/**
* @see {@link Engine#disableOrientationSensor(Context)}
*/
protected boolean disableOrientationSensor() {
return this.mEngine.disableOrientationSensor(this);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.ui.activity;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:18:50 - 06.10.2010
*/
public abstract class LayoutGameActivity extends BaseGameActivity {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract int getLayoutID();
protected abstract int getRenderSurfaceViewID();
@Override
protected void onSetContentView() {
super.setContentView(this.getLayoutID());
this.mRenderSurfaceView = (RenderSurfaceView) this.findViewById(this.getRenderSurfaceViewID());
this.mRenderSurfaceView.setEGLConfigChooser(false);
this.mRenderSurfaceView.setRenderer(this.mEngine);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.ui.activity;
import java.util.concurrent.Callable;
import org.anddev.andengine.util.ActivityUtils;
import org.anddev.andengine.util.AsyncCallable;
import org.anddev.andengine.util.Callback;
import org.anddev.andengine.util.progress.ProgressCallable;
import android.app.Activity;
import android.app.ProgressDialog;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 18:35:28 - 29.08.2009
*/
public abstract class BaseActivity extends Activity {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
* Performs a task in the background, showing a {@link ProgressDialog},
* while the {@link Callable} is being processed.
*
* @param <T>
* @param pTitleResID
* @param pMessageResID
* @param pErrorMessageResID
* @param pCallable
* @param pCallback
*/
protected <T> void doAsync(final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback) {
this.doAsync(pTitleResID, pMessageResID, pCallable, pCallback, null);
}
/**
* Performs a task in the background, showing a indeterminate {@link ProgressDialog},
* while the {@link Callable} is being processed.
*
* @param <T>
* @param pTitleResID
* @param pMessageResID
* @param pErrorMessageResID
* @param pCallable
* @param pCallback
* @param pExceptionCallback
*/
protected <T> void doAsync(final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
ActivityUtils.doAsync(this, pTitleResID, pMessageResID, pCallable, pCallback, pExceptionCallback);
}
/**
* Performs a task in the background, showing a {@link ProgressDialog} with an ProgressBar,
* while the {@link AsyncCallable} is being processed.
*
* @param <T>
* @param pTitleResID
* @param pMessageResID
* @param pErrorMessageResID
* @param pAsyncCallable
* @param pCallback
*/
protected <T> void doProgressAsync(final int pTitleResID, final ProgressCallable<T> pCallable, final Callback<T> pCallback) {
this.doProgressAsync(pTitleResID, pCallable, pCallback, null);
}
/**
* Performs a task in the background, showing a {@link ProgressDialog} with a ProgressBar,
* while the {@link AsyncCallable} is being processed.
*
* @param <T>
* @param pTitleResID
* @param pMessageResID
* @param pErrorMessageResID
* @param pAsyncCallable
* @param pCallback
* @param pExceptionCallback
*/
protected <T> void doProgressAsync(final int pTitleResID, final ProgressCallable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
ActivityUtils.doProgressAsync(this, pTitleResID, pCallable, pCallback, pExceptionCallback);
}
/**
* Performs a task in the background, showing an indeterminate {@link ProgressDialog},
* while the {@link AsyncCallable} is being processed.
*
* @param <T>
* @param pTitleResID
* @param pMessageResID
* @param pErrorMessageResID
* @param pAsyncCallable
* @param pCallback
* @param pExceptionCallback
*/
protected <T> void doAsync(final int pTitleResID, final int pMessageResID, final AsyncCallable<T> pAsyncCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
ActivityUtils.doAsync(this, pTitleResID, pMessageResID, pAsyncCallable, pCallback, pExceptionCallback);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static class CancelledException extends Exception {
private static final long serialVersionUID = -78123211381435596L;
}
}
| Java |
package org.anddev.andengine.ui.activity;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.IResolutionPolicy;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.SplashScene;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasFactory;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource;
import org.anddev.andengine.opengl.texture.bitmap.BitmapTexture.BitmapTextureFormat;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import android.app.Activity;
import android.content.Intent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 08:25:31 - 03.05.2010
*/
public abstract class BaseSplashActivity extends BaseGameActivity {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private IBitmapTextureAtlasSource mSplashTextureAtlasSource;
private TextureRegion mLoadingScreenTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract ScreenOrientation getScreenOrientation();
protected abstract IBitmapTextureAtlasSource onGetSplashTextureAtlasSource();
protected abstract float getSplashDuration();
protected abstract Class<? extends Activity> getFollowUpActivity();
protected float getSplashScaleFrom() {
return 1f;
}
protected float getSplashScaleTo() {
return 1f;
}
@Override
public void onLoadComplete() {
}
@Override
public Engine onLoadEngine() {
this.mSplashTextureAtlasSource = this.onGetSplashTextureAtlasSource();
final int width = this.mSplashTextureAtlasSource.getWidth();
final int height = this.mSplashTextureAtlasSource.getHeight();
this.mCamera = this.getSplashCamera(width, height);
return new Engine(new EngineOptions(true, this.getScreenOrientation(), this.getSplashResolutionPolicy(width, height), this.mCamera));
}
@Override
public void onLoadResources() {
final BitmapTextureAtlas loadingScreenBitmapTextureAtlas = BitmapTextureAtlasFactory.createForTextureAtlasSourceSize(BitmapTextureFormat.RGBA_8888, this.mSplashTextureAtlasSource, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mLoadingScreenTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(loadingScreenBitmapTextureAtlas, this.mSplashTextureAtlasSource, 0, 0);
this.getEngine().getTextureManager().loadTexture(loadingScreenBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
final float splashDuration = this.getSplashDuration();
final SplashScene splashScene = new SplashScene(this.mCamera, this.mLoadingScreenTextureRegion, splashDuration, this.getSplashScaleFrom(), this.getSplashScaleTo());
splashScene.registerUpdateHandler(new TimerHandler(splashDuration, new ITimerCallback() {
@Override
public void onTimePassed(final TimerHandler pTimerHandler) {
BaseSplashActivity.this.startActivity(new Intent(BaseSplashActivity.this, BaseSplashActivity.this.getFollowUpActivity()));
BaseSplashActivity.this.finish();
}
}));
return splashScene;
}
// ===========================================================
// Methods
// ===========================================================
protected Camera getSplashCamera(final int pSplashwidth, final int pSplashHeight) {
return new Camera(0, 0, pSplashwidth, pSplashHeight);
}
protected IResolutionPolicy getSplashResolutionPolicy(final int pSplashwidth, final int pSplashHeight) {
return new RatioResolutionPolicy(pSplashwidth, pSplashHeight);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.ui;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.entity.scene.Scene;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 12:03:08 - 14.03.2010
*/
public interface IGameInterface {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public Engine onLoadEngine();
public void onLoadResources();
public void onUnloadResources();
public Scene onLoadScene();
public void onLoadComplete();
public void onPauseGame();
public void onResumeGame();
}
| Java |
package org.anddev.andengine.ui.dialog;
import org.anddev.andengine.util.Callback;
import android.content.Context;
import android.content.DialogInterface.OnCancelListener;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 09:46:00 - 14.12.2009
*/
public class StringInputDialogBuilder extends GenericInputDialogBuilder<String> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public StringInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final Callback<String> pSuccessCallback, final OnCancelListener pOnCancelListener) {
super(pContext, pTitleResID, pMessageResID, pErrorResID, pIconResID, pSuccessCallback, pOnCancelListener);
}
public StringInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final String pDefaultText, final Callback<String> pSuccessCallback, final OnCancelListener pOnCancelListener) {
super(pContext, pTitleResID, pMessageResID, pErrorResID, pIconResID, pDefaultText, pSuccessCallback, pOnCancelListener);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected String generateResult(final String pInput) {
return pInput;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.ui.dialog;
import org.anddev.andengine.util.Callback;
import org.anddev.andengine.util.Debug;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 09:35:55 - 14.12.2009
*/
public abstract class GenericInputDialogBuilder<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected final Callback<T> mSuccessCallback;
protected final OnCancelListener mOnCancelListener;
protected final int mTitleResID;
protected final int mMessageResID;
protected final int mIconResID;
protected final Context mContext;
private final int mErrorResID;
private final String mDefaultText;
// ===========================================================
// Constructors
// ===========================================================
public GenericInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final Callback<T> pSuccessCallback, final OnCancelListener pOnCancelListener){
this(pContext, pTitleResID, pMessageResID, pErrorResID, pIconResID, "", pSuccessCallback, pOnCancelListener);
}
public GenericInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final String pDefaultText, final Callback<T> pSuccessCallback, final OnCancelListener pOnCancelListener){
this.mContext = pContext;
this.mTitleResID = pTitleResID;
this.mMessageResID = pMessageResID;
this.mErrorResID = pErrorResID;
this.mIconResID = pIconResID;
this.mDefaultText = pDefaultText;
this.mSuccessCallback = pSuccessCallback;
this.mOnCancelListener = pOnCancelListener;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract T generateResult(final String pInput);
// ===========================================================
// Methods
// ===========================================================
public Dialog create() {
final EditText etInput = new EditText(this.mContext);
etInput.setText(this.mDefaultText);
final AlertDialog.Builder ab = new AlertDialog.Builder(this.mContext);
if(this.mTitleResID != 0) {
ab.setTitle(this.mTitleResID);
}
if(this.mMessageResID != 0) {
ab.setMessage(this.mMessageResID);
}
if(this.mIconResID != 0) {
ab.setIcon(this.mIconResID);
}
this.setView(ab, etInput);
ab.setOnCancelListener(this.mOnCancelListener)
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(final DialogInterface pDialog, final int pWhich) {
final T result;
try{
result = GenericInputDialogBuilder.this.generateResult(etInput.getText().toString());
} catch (final IllegalArgumentException e) {
Debug.e("Error in GenericInputDialogBuilder.generateResult()", e);
Toast.makeText(GenericInputDialogBuilder.this.mContext, GenericInputDialogBuilder.this.mErrorResID, Toast.LENGTH_SHORT).show();
return;
}
GenericInputDialogBuilder.this.mSuccessCallback.onCallback(result);
pDialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new OnClickListener() {
@Override
public void onClick(final DialogInterface pDialog, final int pWhich) {
GenericInputDialogBuilder.this.mOnCancelListener.onCancel(pDialog);
pDialog.dismiss();
}
});
return ab.create();
}
protected void setView(final AlertDialog.Builder pBuilder, final EditText pInputEditText) {
pBuilder.setView(pInputEditText);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.poly2tri.triangulation.point.ardor3d;
import java.util.ArrayList;
import java.util.List;
import org.poly2tri.geometry.polygon.PolygonPoint;
import org.poly2tri.triangulation.TriangulationPoint;
import com.ardor3d.math.Vector3;
public class ArdorVector3PolygonPoint extends PolygonPoint
{
private final Vector3 _p;
public ArdorVector3PolygonPoint( Vector3 point )
{
super( point.getX(), point.getY() );
_p = point;
}
public final double getX()
{
return _p.getX();
}
public final double getY()
{
return _p.getY();
}
public final double getZ()
{
return _p.getZ();
}
public final float getXf()
{
return _p.getXf();
}
public final float getYf()
{
return _p.getYf();
}
public final float getZf()
{
return _p.getZf();
}
public static List<PolygonPoint> toPoints( Vector3[] vpoints )
{
ArrayList<PolygonPoint> points = new ArrayList<PolygonPoint>(vpoints.length);
for( int i=0; i<vpoints.length; i++ )
{
points.add( new ArdorVector3PolygonPoint(vpoints[i]) );
}
return points;
}
public static List<PolygonPoint> toPoints( ArrayList<Vector3> vpoints )
{
int i=0;
ArrayList<PolygonPoint> points = new ArrayList<PolygonPoint>(vpoints.size());
for( Vector3 point : vpoints )
{
points.add( new ArdorVector3PolygonPoint(point) );
}
return points;
}
}
| Java |
package org.poly2tri.triangulation.point.ardor3d;
import java.util.ArrayList;
import java.util.List;
import org.poly2tri.triangulation.TriangulationPoint;
import com.ardor3d.math.Vector3;
public class ArdorVector3Point extends TriangulationPoint
{
private final Vector3 _p;
public ArdorVector3Point( Vector3 point )
{
_p = point;
}
public final double getX()
{
return _p.getX();
}
public final double getY()
{
return _p.getY();
}
public final double getZ()
{
return _p.getZ();
}
public final float getXf()
{
return _p.getXf();
}
public final float getYf()
{
return _p.getYf();
}
public final float getZf()
{
return _p.getZf();
}
@Override
public void set( double x, double y, double z )
{
_p.set( x, y, z );
}
public static List<TriangulationPoint> toPoints( Vector3[] vpoints )
{
ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.length);
for( int i=0; i<vpoints.length; i++ )
{
points.add( new ArdorVector3Point(vpoints[i]) );
}
return points;
}
public static List<TriangulationPoint> toPoints( ArrayList<Vector3> vpoints )
{
int i=0;
ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.size());
for( Vector3 point : vpoints )
{
points.add( new ArdorVector3Point(point) );
}
return points;
}
public static List<TriangulationPoint> toPolygonPoints( Vector3[] vpoints )
{
ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.length);
for( int i=0; i<vpoints.length; i++ )
{
points.add( new ArdorVector3PolygonPoint(vpoints[i]) );
}
return points;
}
public static List<TriangulationPoint> toPolygonPoints( ArrayList<Vector3> vpoints )
{
int i=0;
ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.size());
for( Vector3 point : vpoints )
{
points.add( new ArdorVector3PolygonPoint(point) );
}
return points;
}
}
| Java |
package org.poly2tri.triangulation.tools.ardor3d;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.List;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.geometry.primitives.Point;
import org.poly2tri.transform.coordinate.CoordinateTransform;
import org.poly2tri.transform.coordinate.NoTransform;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.delaunay.DelaunayTriangle;
import org.poly2tri.triangulation.point.TPoint;
import org.poly2tri.triangulation.sets.PointSet;
import com.ardor3d.math.Vector3;
import com.ardor3d.renderer.IndexMode;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.util.geom.BufferUtils;
public class ArdorMeshMapper
{
private static final CoordinateTransform _ct = new NoTransform();
public static void updateTriangleMesh( Mesh mesh,
List<DelaunayTriangle> triangles )
{
updateTriangleMesh( mesh, triangles, _ct );
}
public static void updateTriangleMesh( Mesh mesh,
List<DelaunayTriangle> triangles,
CoordinateTransform pc )
{
FloatBuffer vertBuf;
TPoint point;
mesh.getMeshData().setIndexMode( IndexMode.Triangles );
if( triangles == null || triangles.size() == 0 )
{
return;
}
point = new TPoint(0,0,0);
int size = 3*3*triangles.size();
prepareVertexBuffer( mesh, size );
vertBuf = mesh.getMeshData().getVertexBuffer();
vertBuf.rewind();
for( DelaunayTriangle t : triangles )
{
for( int i=0; i<3; i++ )
{
pc.transform( t.points[i], point );
vertBuf.put(point.getXf());
vertBuf.put(point.getYf());
vertBuf.put(point.getZf());
}
}
}
public static void updateFaceNormals( Mesh mesh,
List<DelaunayTriangle> triangles )
{
updateFaceNormals( mesh, triangles, _ct );
}
public static void updateFaceNormals( Mesh mesh,
List<DelaunayTriangle> triangles,
CoordinateTransform pc )
{
FloatBuffer nBuf;
Vector3 fNormal;
HashMap<DelaunayTriangle,Vector3> fnMap;
int size = 3*3*triangles.size();
fnMap = calculateFaceNormals( triangles, pc );
prepareNormalBuffer( mesh, size );
nBuf = mesh.getMeshData().getNormalBuffer();
nBuf.rewind();
for( DelaunayTriangle t : triangles )
{
fNormal = fnMap.get( t );
for( int i=0; i<3; i++ )
{
nBuf.put(fNormal.getXf());
nBuf.put(fNormal.getYf());
nBuf.put(fNormal.getZf());
}
}
}
public static void updateVertexNormals( Mesh mesh,
List<DelaunayTriangle> triangles )
{
updateVertexNormals( mesh, triangles, _ct );
}
public static void updateVertexNormals( Mesh mesh,
List<DelaunayTriangle> triangles,
CoordinateTransform pc )
{
FloatBuffer nBuf;
TriangulationPoint vertex;
Vector3 vNormal, fNormal;
HashMap<DelaunayTriangle,Vector3> fnMap;
HashMap<TriangulationPoint,Vector3> vnMap = new HashMap<TriangulationPoint,Vector3>(3*triangles.size());
int size = 3*3*triangles.size();
fnMap = calculateFaceNormals( triangles, pc );
// Calculate a vertex normal for each vertex
for( DelaunayTriangle t : triangles )
{
fNormal = fnMap.get( t );
for( int i=0; i<3; i++ )
{
vertex = t.points[i];
vNormal = vnMap.get( vertex );
if( vNormal == null )
{
vNormal = new Vector3( fNormal.getX(), fNormal.getY(), fNormal.getZ() );
vnMap.put( vertex, vNormal );
}
else
{
vNormal.addLocal( fNormal );
}
}
}
// Normalize all normals
for( Vector3 normal : vnMap.values() )
{
normal.normalizeLocal();
}
prepareNormalBuffer( mesh, size );
nBuf = mesh.getMeshData().getNormalBuffer();
nBuf.rewind();
for( DelaunayTriangle t : triangles )
{
for( int i=0; i<3; i++ )
{
vertex = t.points[i];
vNormal = vnMap.get( vertex );
nBuf.put(vNormal.getXf());
nBuf.put(vNormal.getYf());
nBuf.put(vNormal.getZf());
}
}
}
private static HashMap<DelaunayTriangle,Vector3> calculateFaceNormals( List<DelaunayTriangle> triangles,
CoordinateTransform pc )
{
HashMap<DelaunayTriangle,Vector3> normals = new HashMap<DelaunayTriangle,Vector3>(triangles.size());
TPoint point = new TPoint(0,0,0);
// calculate the Face Normals for all triangles
float x1,x2,x3,y1,y2,y3,z1,z2,z3,nx,ny,nz,ux,uy,uz,vx,vy,vz;
double norm;
for( DelaunayTriangle t : triangles )
{
pc.transform( t.points[0], point );
x1 = point.getXf();
y1 = point.getYf();
z1 = point.getZf();
pc.transform( t.points[1], point );
x2 = point.getXf();
y2 = point.getYf();
z2 = point.getZf();
pc.transform( t.points[2], point );
x3 = point.getXf();
y3 = point.getYf();
z3 = point.getZf();
ux = x2 - x1;
uy = y2 - y1;
uz = z2 - z1;
vx = x3 - x1;
vy = y3 - y1;
vz = z3 - z1;
nx = uy*vz - uz*vy;
ny = uz*vx - ux*vz;
nz = ux*vy - uy*vx;
norm = 1/Math.sqrt( nx*nx + ny*ny + nz*nz );
nx *= norm;
ny *= norm;
nz *= norm;
normals.put( t, new Vector3(nx,ny,nz) );
}
return normals;
}
/**
* For now very primitive!
*
* Assumes a single texture and that the triangles form a xy-monotone surface
* <p>
* A continuous surface S in R3 is called xy-monotone, if every line parallel
* to the z-axis intersects it at a single point at most.
*
* @param mesh
* @param scale
*/
public static void updateTextureCoordinates( Mesh mesh,
List<DelaunayTriangle> triangles,
double scale,
double angle )
{
TriangulationPoint vertex;
FloatBuffer tcBuf;
float width,maxX,minX,maxY,minY,x,y,xn,yn;
maxX = Float.NEGATIVE_INFINITY;
minX = Float.POSITIVE_INFINITY;
maxY = Float.NEGATIVE_INFINITY;
minY = Float.POSITIVE_INFINITY;
for( DelaunayTriangle t : triangles )
{
for( int i=0; i<3; i++ )
{
vertex = t.points[i];
x = vertex.getXf();
y = vertex.getYf();
maxX = x > maxX ? x : maxX;
minX = x < minX ? x : minX;
maxY = y > maxY ? y : maxY;
minY = y < minY ? x : minY;
}
}
width = maxX-minX > maxY-minY ? maxX-minX : maxY-minY;
width *= scale;
tcBuf = prepareTextureCoordinateBuffer(mesh,0,2*3*triangles.size());
tcBuf.rewind();
for( DelaunayTriangle t : triangles )
{
for( int i=0; i<3; i++ )
{
vertex = t.points[i];
x = vertex.getXf()-(maxX-minX)/2;
y = vertex.getYf()-(maxY-minY)/2;
xn = (float)(x*Math.cos(angle)-y*Math.sin(angle));
yn = (float)(y*Math.cos(angle)+x*Math.sin(angle));
tcBuf.put( xn/width );
tcBuf.put( yn/width );
}
}
}
/**
* Assuming:
* 1. That given U anv V aren't collinear.
* 2. That O,U and V can be projected in the XY plane
*
* @param mesh
* @param triangles
* @param o
* @param u
* @param v
*/
public static void updateTextureCoordinates( Mesh mesh,
List<DelaunayTriangle> triangles,
double scale,
Point o,
Point u,
Point v )
{
FloatBuffer tcBuf;
float x,y,a,b;
final float ox = (float)scale*o.getXf();
final float oy = (float)scale*o.getYf();
final float ux = (float)scale*u.getXf();
final float uy = (float)scale*u.getYf();
final float vx = (float)scale*v.getXf();
final float vy = (float)scale*v.getYf();
final float vCu = (vx*uy-vy*ux);
final boolean doX = Math.abs( ux ) > Math.abs( uy );
tcBuf = prepareTextureCoordinateBuffer(mesh,0,2*3*triangles.size());
tcBuf.rewind();
for( DelaunayTriangle t : triangles )
{
for( int i=0; i<3; i++ )
{
x = t.points[i].getXf()-ox;
y = t.points[i].getYf()-oy;
// Calculate the texture coordinate in the UV plane
a = (uy*x - ux*y)/vCu;
if( doX )
{
b = (x - a*vx)/ux;
}
else
{
b = (y - a*vy)/uy;
}
tcBuf.put( a );
tcBuf.put( b );
}
}
}
// FloatBuffer vBuf,tcBuf;
// float width,maxX,minX,maxY,minY,x,y,xn,yn;
//
// maxX = Float.NEGATIVE_INFINITY;
// minX = Float.POSITIVE_INFINITY;
// maxY = Float.NEGATIVE_INFINITY;
// minY = Float.POSITIVE_INFINITY;
//
// vBuf = mesh.getMeshData().getVertexBuffer();
// for( int i=0; i < vBuf.limit()-1; i+=3 )
// {
// x = vBuf.get(i);
// y = vBuf.get(i+1);
//
// maxX = x > maxX ? x : maxX;
// minX = x < minX ? x : minX;
// maxY = y > maxY ? y : maxY;
// minY = y < minY ? x : minY;
// }
//
// width = maxX-minX > maxY-minY ? maxX-minX : maxY-minY;
// width *= scale;
//
// vBuf = mesh.getMeshData().getVertexBuffer();
// tcBuf = prepareTextureCoordinateBuffer(mesh,0,2*vBuf.limit()/3);
// tcBuf.rewind();
//
// for( int i=0; i < vBuf.limit()-1; i+=3 )
// {
// x = vBuf.get(i)-(maxX-minX)/2;
// y = vBuf.get(i+1)-(maxY-minY)/2;
// xn = (float)(x*Math.cos(angle)-y*Math.sin(angle));
// yn = (float)(y*Math.cos(angle)+x*Math.sin(angle));
// tcBuf.put( xn/width );
// tcBuf.put( yn/width );
// }
public static void updateTriangleMesh( Mesh mesh, PointSet ps, CoordinateTransform pc )
{
updateTriangleMesh( mesh, ps.getTriangles(), pc );
}
/**
* Will populate a given Mesh's vertex,index buffer and set IndexMode.Triangles<br>
* Will also increase buffer sizes if needed by creating new buffers.
*
* @param mesh
* @param ps
*/
public static void updateTriangleMesh( Mesh mesh, PointSet ps )
{
updateTriangleMesh( mesh, ps.getTriangles() );
}
public static void updateTriangleMesh( Mesh mesh, Polygon p )
{
updateTriangleMesh( mesh, p.getTriangles() );
}
public static void updateTriangleMesh( Mesh mesh, Polygon p, CoordinateTransform pc )
{
updateTriangleMesh( mesh, p.getTriangles(), pc );
}
public static void updateVertexBuffer( Mesh mesh, List<? extends Point> list )
{
FloatBuffer vertBuf;
int size = 3*list.size();
prepareVertexBuffer( mesh, size );
if( size == 0 )
{
return;
}
vertBuf = mesh.getMeshData().getVertexBuffer();
vertBuf.rewind();
for( Point p : list )
{
vertBuf.put(p.getXf()).put(p.getYf()).put(p.getZf());
}
}
public static void updateIndexBuffer( Mesh mesh, int[] index )
{
IntBuffer indexBuf;
if( index == null || index.length == 0 )
{
return;
}
int size = index.length;
prepareIndexBuffer( mesh, size );
indexBuf = mesh.getMeshData().getIndexBuffer();
indexBuf.rewind();
for( int i=0; i<size; i+=2 )
{
indexBuf.put(index[i]).put( index[i+1] );
}
}
private static void prepareVertexBuffer( Mesh mesh, int size )
{
FloatBuffer vertBuf;
vertBuf = mesh.getMeshData().getVertexBuffer();
if( vertBuf == null || vertBuf.capacity() < size )
{
vertBuf = BufferUtils.createFloatBuffer( size );
mesh.getMeshData().setVertexBuffer( vertBuf );
}
else
{
vertBuf.limit( size );
mesh.getMeshData().updateVertexCount();
}
}
private static void prepareNormalBuffer( Mesh mesh, int size )
{
FloatBuffer nBuf;
nBuf = mesh.getMeshData().getNormalBuffer();
if( nBuf == null || nBuf.capacity() < size )
{
nBuf = BufferUtils.createFloatBuffer( size );
mesh.getMeshData().setNormalBuffer( nBuf );
}
else
{
nBuf.limit( size );
}
}
private static void prepareIndexBuffer( Mesh mesh, int size)
{
IntBuffer indexBuf = mesh.getMeshData().getIndexBuffer();
if( indexBuf == null || indexBuf.capacity() < size )
{
indexBuf = BufferUtils.createIntBuffer( size );
mesh.getMeshData().setIndexBuffer( indexBuf );
}
else
{
indexBuf.limit( size );
}
}
private static FloatBuffer prepareTextureCoordinateBuffer( Mesh mesh, int index, int size )
{
FloatBuffer tcBuf;
tcBuf = mesh.getMeshData().getTextureBuffer( index );
if( tcBuf == null || tcBuf.capacity() < size )
{
tcBuf = BufferUtils.createFloatBuffer( size );
mesh.getMeshData().setTextureBuffer( tcBuf, index );
}
else
{
tcBuf.limit( size );
}
return tcBuf;
}
}
| Java |
package org.poly2tri.polygon.ardor3d;
import java.util.ArrayList;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.triangulation.point.ardor3d.ArdorVector3Point;
import org.poly2tri.triangulation.point.ardor3d.ArdorVector3PolygonPoint;
import com.ardor3d.math.Vector3;
public class ArdorPolygon extends Polygon
{
public ArdorPolygon( Vector3[] points )
{
super( ArdorVector3PolygonPoint.toPoints( points ) );
}
public ArdorPolygon( ArrayList<Vector3> points )
{
super( ArdorVector3PolygonPoint.toPoints( points ) );
}
}
| Java |
package org.poly2tri.examples.ardor3d;
import java.util.ArrayList;
import org.poly2tri.Poly2Tri;
import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.geometry.polygon.PolygonPoint;
import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper;
import com.ardor3d.framework.FrameHandler;
import com.ardor3d.input.logical.LogicalLayer;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.renderer.state.WireframeState;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.scenegraph.Node;
import com.google.inject.Inject;
public class CDTHoleExample extends P2TSimpleExampleBase
{
public static void main(final String[] args)
{
start(CDTHoleExample.class);
}
@Inject
public CDTHoleExample( LogicalLayer logicalLayer, FrameHandler frameHandler )
{
super( logicalLayer, frameHandler );
}
@Override
protected void initExample()
{
super.initExample();
Node node = new Node();
node.setRenderState( new WireframeState() );
_node.attachChild( node );
Polygon circle;
Polygon hole;
circle = createCirclePolygon( 64, 25, 1 );
hole = createCirclePolygon( 32, 25, 0.25, -0.5, -0.5 );
circle.addHole( hole );
hole = createCirclePolygon( 64, 25, 0.5, 0.25, 0.25 );
circle.addHole( hole );
Mesh mesh = new Mesh();
mesh.setDefaultColor( ColorRGBA.RED );
mesh.setTranslation( 0, 0, 0.01 );
node.attachChild( mesh );
Mesh mesh2 = new Mesh();
mesh2.setDefaultColor( ColorRGBA.BLUE );
_node.attachChild( mesh2 );
Poly2Tri.triangulate( circle );
ArdorMeshMapper.updateTriangleMesh( mesh, circle );
ArdorMeshMapper.updateTriangleMesh( mesh2, circle );
}
private Polygon createCirclePolygon( int n, double scale, double radius )
{
return createCirclePolygon( n, scale, radius, 0, 0 );
}
private Polygon createCirclePolygon( int n,
double scale,
double radius,
double x,
double y )
{
if( n < 3 ) n=3;
PolygonPoint[] points = new PolygonPoint[n];
for( int i=0; i<n; i++ )
{
points[i] = new PolygonPoint( scale*(x + radius*Math.cos( (2.0*Math.PI*i)/n )),
scale*(y + radius*Math.sin( (2.0*Math.PI*i)/n ) ));
}
return new Polygon( points );
}
}
| Java |
package org.poly2tri.examples.ardor3d.base;
import java.net.URISyntaxException;
import org.lwjgl.opengl.Display;
import com.ardor3d.example.ExampleBase;
import com.ardor3d.framework.FrameHandler;
import com.ardor3d.image.Texture;
import com.ardor3d.image.Image.Format;
import com.ardor3d.input.logical.LogicalLayer;
import com.ardor3d.renderer.queue.RenderBucketType;
import com.ardor3d.renderer.state.BlendState;
import com.ardor3d.renderer.state.TextureState;
import com.ardor3d.renderer.state.WireframeState;
import com.ardor3d.scenegraph.Node;
import com.ardor3d.scenegraph.hint.LightCombineMode;
import com.ardor3d.scenegraph.shape.Quad;
import com.ardor3d.util.TextureManager;
import com.ardor3d.util.resource.ResourceLocatorTool;
import com.ardor3d.util.resource.SimpleResourceLocator;
import com.google.inject.Inject;
public abstract class P2TSimpleExampleBase extends ExampleBase
{
protected Node _node;
protected Quad _logotype;
protected int _width,_height;
@Inject
public P2TSimpleExampleBase( LogicalLayer logicalLayer, FrameHandler frameHandler )
{
super( logicalLayer, frameHandler );
}
@Override
protected void initExample()
{
_canvas.setVSyncEnabled( true );
_canvas.getCanvasRenderer().getCamera().setLocation(0, 0, 65);
_width = Display.getDisplayMode().getWidth();
_height = Display.getDisplayMode().getHeight();
_root.getSceneHints().setLightCombineMode( LightCombineMode.Off );
_node = new Node();
_node.getSceneHints().setLightCombineMode( LightCombineMode.Off );
// _node.setRenderState( new WireframeState() );
_root.attachChild( _node );
try {
SimpleResourceLocator srl = new SimpleResourceLocator(ExampleBase.class.getClassLoader().getResource("org/poly2tri/examples/data/"));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_MODEL, srl);
SimpleResourceLocator sr2 = new SimpleResourceLocator(ExampleBase.class.getClassLoader().getResource("org/poly2tri/examples/textures/"));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, sr2);
} catch (final URISyntaxException ex) {
ex.printStackTrace();
}
_logotype = new Quad("box", 128, 128 );
_logotype.setTranslation( 74, _height - 74, 0 );
_logotype.getSceneHints().setRenderBucketType( RenderBucketType.Ortho );
BlendState bs = new BlendState();
bs.setBlendEnabled( true );
bs.setEnabled( true );
bs.setSourceFunction(BlendState.SourceFunction.SourceAlpha);
bs.setDestinationFunction(BlendState.DestinationFunction.OneMinusSourceAlpha);
_logotype.setRenderState( bs );
TextureState ts = new TextureState();
ts.setEnabled(true);
ts.setTexture(TextureManager.load("poly2tri_logotype_256x256.png",
Texture.MinificationFilter.Trilinear,
Format.GuessNoCompression, true));
_logotype.setRenderState(ts);
_root.attachChild( _logotype );
}
}
| Java |
package org.poly2tri.examples.ardor3d.base;
import java.nio.FloatBuffer;
import java.util.List;
import org.poly2tri.geometry.polygon.PolygonSet;
import org.poly2tri.triangulation.TriangulationAlgorithm;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.TriangulationProcess;
import org.poly2tri.triangulation.delaunay.DelaunayTriangle;
import org.poly2tri.triangulation.delaunay.sweep.DTSweepContext;
import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper;
import com.ardor3d.framework.Canvas;
import com.ardor3d.framework.FrameHandler;
import com.ardor3d.input.Key;
import com.ardor3d.input.logical.InputTrigger;
import com.ardor3d.input.logical.KeyPressedCondition;
import com.ardor3d.input.logical.LogicalLayer;
import com.ardor3d.input.logical.TriggerAction;
import com.ardor3d.input.logical.TwoInputStates;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.math.Vector3;
import com.ardor3d.renderer.IndexMode;
import com.ardor3d.renderer.queue.RenderBucketType;
import com.ardor3d.renderer.state.WireframeState;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.scenegraph.MeshData;
import com.ardor3d.scenegraph.Node;
import com.ardor3d.scenegraph.Point;
import com.ardor3d.scenegraph.hint.LightCombineMode;
import com.ardor3d.ui.text.BasicText;
import com.ardor3d.util.ReadOnlyTimer;
import com.ardor3d.util.geom.BufferUtils;
public abstract class P2TExampleBase extends P2TSimpleExampleBase
{
protected TriangulationProcess _process;
protected CDTSweepMesh _cdtSweepMesh;
protected CDTSweepPoints _cdtSweepPoints;
protected PolygonSet _polygonSet;
private long _processTimestamp;
/** Text fields used to present info about the example. */
protected final BasicText _exampleInfo[] = new BasicText[7];
public P2TExampleBase( LogicalLayer logicalLayer, FrameHandler frameHandler )
{
super( logicalLayer, frameHandler );
}
@Override
protected void initExample()
{
super.initExample();
// Warmup the triangulation code for better performance
// when we need triangulation during runtime
// Poly2Tri.warmup();
_process = new TriangulationProcess(TriangulationAlgorithm.DTSweep);
_cdtSweepPoints = new CDTSweepPoints();
_cdtSweepMesh = new CDTSweepMesh();
_node.attachChild( _cdtSweepPoints.getSceneNode() );
_node.attachChild( _cdtSweepMesh.getSceneNode() );
final Node textNodes = new Node("Text");
textNodes.getSceneHints().setRenderBucketType(RenderBucketType.Ortho);
textNodes.getSceneHints().setLightCombineMode(LightCombineMode.Off);
_root.attachChild( textNodes );
for (int i = 0; i < _exampleInfo.length; i++)
{
_exampleInfo[i] = BasicText.createDefaultTextLabel("Text", "", 16);
_exampleInfo[i].setTranslation(new Vector3(10, (_exampleInfo.length-i-1) * 20 + 10, 0));
textNodes.attachChild(_exampleInfo[i]);
}
updateText();
}
protected DTSweepContext getContext()
{
return (DTSweepContext)_process.getContext();
}
/**
* Update text information.
*/
protected void updateText()
{
_exampleInfo[0].setText("");
_exampleInfo[1].setText("[Home] Toggle wireframe");
_exampleInfo[2].setText("[End] Toggle vertex points");
}
@Override
protected void updateExample(final ReadOnlyTimer timer)
{
if( _process.isDone() && _processTimestamp != _process.getTimestamp() )
{
_processTimestamp = _process.getTimestamp();
updateMesh();
_exampleInfo[0].setText("[" + _process.getTriangulationTime() + "ms] " + _process.getPointCount() + " points" );
}
}
public void exit()
{
super.exit();
_process.shutdown();
}
protected void triangulate()
{
_process.triangulate( _polygonSet );
}
protected void updateMesh()
{
if( _process.getContext().getTriangulatable() != null )
{
if( _process.getContext().isDebugEnabled() )
{
if( _process.isDone() )
{
_cdtSweepMesh.update( _process.getContext().getTriangulatable().getTriangles() );
_cdtSweepPoints.update( _process.getContext().getTriangulatable().getPoints() );
}
else
{
_cdtSweepMesh.update( _process.getContext().getTriangles() );
_cdtSweepPoints.update( _process.getContext().getPoints() );
}
}
else
{
_cdtSweepMesh.update( _polygonSet.getPolygons().get(0).getTriangles() );
_cdtSweepPoints.update( _polygonSet.getPolygons().get(0).getPoints() );
}
}
}
@Override
public void registerInputTriggers()
{
super.registerInputTriggers();
_controlHandle.setMoveSpeed( 10 );
// HOME - toogleWireframe
_logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.HOME ), new TriggerAction() {
public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf )
{
_cdtSweepMesh.toogleWireframe();
}
} ) );
// END - tooglePoints
_logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.END ), new TriggerAction() {
public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf )
{
_cdtSweepPoints.toogleVisibile();
}
} ) );
}
protected abstract class SceneElement<A>
{
protected Node _node;
public SceneElement(String name)
{
_node = new Node(name);
_node.getSceneHints().setAllPickingHints( false );
}
public abstract void update( A element );
public Node getSceneNode()
{
return _node;
}
}
protected class CDTSweepPoints extends SceneElement<List<TriangulationPoint>>
{
private Point m_point = new Point();
private boolean _pointsVisible = true;
public CDTSweepPoints()
{
super("Mesh");
m_point.setDefaultColor( ColorRGBA.RED );
m_point.setPointSize( 1 );
m_point.setTranslation( 0, 0, 0.01 );
_node.attachChild( m_point );
MeshData md = m_point.getMeshData();
int size = 1000;
FloatBuffer vertBuf = BufferUtils.createFloatBuffer( (int)size*3 );
md.setVertexBuffer( vertBuf );
}
public void toogleVisibile()
{
if( _pointsVisible )
{
m_point.removeFromParent();
_pointsVisible = false;
}
else
{
_node.attachChild( m_point );
_pointsVisible = true;
}
}
@Override
public void update( List<TriangulationPoint> list )
{
ArdorMeshMapper.updateVertexBuffer( m_point, list );
}
}
protected class CDTSweepMesh extends SceneElement<List<DelaunayTriangle>>
{
private Mesh m_mesh = new Mesh();
private WireframeState _ws = new WireframeState();
public CDTSweepMesh()
{
super("Mesh");
MeshData md;
m_mesh.setDefaultColor( ColorRGBA.BLUE );
m_mesh.setRenderState( _ws );
_node.attachChild( m_mesh );
md = m_mesh.getMeshData();
int size = 1000;
FloatBuffer vertBuf = BufferUtils.createFloatBuffer( (int)size*3*3 );
md.setVertexBuffer( vertBuf );
md.setIndexMode( IndexMode.Triangles );
}
public void toogleWireframe()
{
if( _ws.isEnabled() )
{
_ws.setEnabled( false );
}
else
{
_ws.setEnabled( true );
}
}
@Override
public void update( List<DelaunayTriangle> triangles )
{
ArdorMeshMapper.updateTriangleMesh( m_mesh, triangles );
}
}
}
| Java |
package org.poly2tri.examples.ardor3d.misc;
public enum ExampleModels
{
Test ("test.dat",1,0,0,true),
Two ("2.dat",1,0,0,true),
Debug ("debug.dat",1,0,0,false),
Debug2 ("debug2.dat",1,0,0,false),
Bird ("bird.dat",1,0,0,false),
Custom ("funny.dat",1,0,0,false),
Diamond ("diamond.dat",1,0,0,false),
Dude ("dude.dat",1,-0.1,0,true),
Nazca_heron ("nazca_heron.dat",1.3,0,0.35,false),
Nazca_monkey ("nazca_monkey.dat",1,0,0,false),
Star ("star.dat",1,0,0,false),
Strange ("strange.dat",1,0,0,true),
Tank ("tank.dat",1.3,0,0,true);
private final static String m_basePath = "org/poly2tri/examples/data/";
private String m_filename;
private double m_scale;
private double m_x;
private double m_y;
private boolean _invertedYAxis;
ExampleModels( String filename, double scale, double x, double y, boolean invertedY )
{
m_filename = filename;
m_scale = scale;
m_x = x;
m_y = y;
_invertedYAxis = invertedY;
}
public String getFilename()
{
return m_basePath + m_filename;
}
public double getScale()
{
return m_scale;
}
public double getX()
{
return m_x;
}
public double getY()
{
return m_y;
}
public boolean invertedYAxis()
{
return _invertedYAxis;
}
} | Java |
/**
* Copyright (c) 2008-2009 Ardor Labs, Inc.
*
* This file is part of Ardor3D.
*
* Ardor3D is free software: you can redistribute it and/or modify it
* under the terms of its license which may be found in the accompanying
* LICENSE file or at <http://www.ardor3d.com/LICENSE>.
*/
package org.poly2tri.examples.ardor3d.misc;
import java.nio.FloatBuffer;
import com.ardor3d.math.Vector3;
import com.ardor3d.math.type.ReadOnlyVector3;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.util.geom.BufferUtils;
public class Triangle extends Mesh
{
private static final long serialVersionUID = 1L;
public Triangle()
{
this( "Triangle" );
}
public Triangle(final String name )
{
this( name,
new Vector3( Math.cos( Math.toRadians( 90 ) ), Math.sin( Math.toRadians( 90 ) ), 0 ),
new Vector3( Math.cos( Math.toRadians( 210 ) ), Math.sin( Math.toRadians( 210 ) ), 0 ),
new Vector3( Math.cos( Math.toRadians( 330 ) ), Math.sin( Math.toRadians( 330 ) ), 0 ));
}
public Triangle(final String name,
ReadOnlyVector3 a,
ReadOnlyVector3 b,
ReadOnlyVector3 c )
{
super(name);
initialize(a,b,c);
}
/**
* <code>resize</code> changes the width and height of the given quad by altering its vertices.
*
* @param width
* the new width of the <code>Quad</code>.
* @param height
* the new height of the <code>Quad</code>.
*/
// public void resize( double radius )
// {
// _meshData.getVertexBuffer().clear();
// _meshData.getVertexBuffer().put((float) (-width / 2)).put((float) (height / 2)).put(0);
// _meshData.getVertexBuffer().put((float) (-width / 2)).put((float) (-height / 2)).put(0);
// _meshData.getVertexBuffer().put((float) (width / 2)).put((float) (-height / 2)).put(0);
// _meshData.getVertexBuffer().put((float) (width / 2)).put((float) (height / 2)).put(0);
// }
/**
* <code>initialize</code> builds the data for the <code>Quad</code> object.
*
* @param width
* the width of the <code>Quad</code>.
* @param height
* the height of the <code>Quad</code>.
*/
private void initialize(ReadOnlyVector3 a, ReadOnlyVector3 b, ReadOnlyVector3 c )
{
final int verts = 3;
_meshData.setVertexBuffer(BufferUtils.createVector3Buffer(3));
_meshData.setNormalBuffer(BufferUtils.createVector3Buffer(3));
final FloatBuffer tbuf = BufferUtils.createVector2Buffer(3);
_meshData.setTextureBuffer(tbuf, 0);
_meshData.setIndexBuffer(BufferUtils.createIntBuffer(3));
Vector3 ba = Vector3.fetchTempInstance();
Vector3 ca = Vector3.fetchTempInstance();
ba.set( b ).subtractLocal( a );
ca.set( c ).subtractLocal( a );
ba.crossLocal( ca ).normalizeLocal();
_meshData.getNormalBuffer().put(ba.getXf()).put(ba.getYf()).put(ba.getZf());
_meshData.getNormalBuffer().put(ba.getXf()).put(ba.getYf()).put(ba.getZf());
_meshData.getNormalBuffer().put(ba.getXf()).put(ba.getYf()).put(ba.getZf());
Vector3.releaseTempInstance( ba );
Vector3.releaseTempInstance( ca );
tbuf.put(0).put(1);
tbuf.put(0).put(0);
tbuf.put(1).put(0);
_meshData.getIndexBuffer().put(0);
_meshData.getIndexBuffer().put(1);
_meshData.getIndexBuffer().put(2);
_meshData.getVertexBuffer().put(a.getXf()).put(a.getYf()).put(a.getZf());
_meshData.getVertexBuffer().put(b.getXf()).put(b.getYf()).put(b.getZf());
_meshData.getVertexBuffer().put(c.getXf()).put(c.getYf()).put(c.getZf());
}
} | Java |
package org.poly2tri.examples.ardor3d.misc;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.polygon.ardor3d.ArdorPolygon;
import org.poly2tri.triangulation.TriangulationPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ardor3d.math.Vector3;
public class PolygonLoader
{
private final static Logger logger = LoggerFactory.getLogger( PolygonLoader.class );
public static Polygon loadModel( ExampleModels model, double scale ) throws FileNotFoundException, IOException
{
String line;
ArrayList<Vector3> points = new ArrayList<Vector3>();
InputStream istream = PolygonLoader.class.getClassLoader().getResourceAsStream( model.getFilename() );
if( istream == null )
{
throw new FileNotFoundException( "Couldn't find " + model );
}
InputStreamReader ir = new InputStreamReader( istream );
BufferedReader reader = new BufferedReader( ir );
while( ( line = reader.readLine() ) != null )
{
StringTokenizer tokens = new StringTokenizer( line, " ," );
points.add( new Vector3( Float.valueOf( tokens.nextToken() ).floatValue(),
Float.valueOf( tokens.nextToken() ).floatValue(),
0f ));
}
if( points.isEmpty() )
{
throw new IOException( "no data in file " + model );
}
// Rescale models so they are centered at 0,0 and don't fall outside the
// unit square
double maxX, maxY, minX, minY;
maxX = minX = points.get( 0 ).getX();
if( model.invertedYAxis() )
{
maxY = minY = -points.get( 0 ).getY();
}
else
{
maxY = minY = points.get( 0 ).getY();
}
for( Vector3 p : points )
{
if( model.invertedYAxis() )
{
p.setY( -p.getY() );
}
maxX = p.getX() > maxX ? p.getX() : maxX;
maxY = p.getY() > maxY ? p.getY() : maxY;
minX = p.getX() < minX ? p.getX() : minX;
minY = p.getY() < minY ? p.getY() : minY;
}
double width, height, xScale, yScale;
width = maxX - minX;
height = maxY - minY;
xScale = scale * 1f / width;
yScale = scale * 1f / height;
// System.out.println("scale/height=" + SCALE + "/" + height );
// System.out.println("scale=" + yScale);
for( Vector3 p : points )
{
if( model.invertedYAxis() )
{
p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 );
}
else
{
p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 );
}
p.multiplyLocal( xScale < yScale ? xScale : yScale );
}
return new ArdorPolygon( points);
}
public static void saveModel( String path, TriangulationPoint[] points )
{
FileWriter writer = null;
BufferedWriter w = null;
String file = path+System.currentTimeMillis()+".dat";
try
{
writer = new FileWriter(file);
w = new BufferedWriter(writer);
for( TriangulationPoint p : points )
{
w.write( Float.toString( p.getXf() ) +" "+ Float.toString( p.getYf() ));
w.newLine();
}
logger.info( "Saved polygon\n" + file );
}
catch( IOException e )
{
logger.error( "Failed to save model" );
}
finally
{
if( w != null )
{
try
{
w.close();
}
catch( IOException e2 )
{
}
}
}
}
/**
* This is a very unoptimal dump of the triangles as absolute lines.
* For manual importation to an SVG<br>
*
* @param path
* @param ps
*/
// public static void saveTriLine( String path, PolygonSet ps )
// {
// FileWriter writer = null;
// BufferedWriter w = null;
// String file = path+System.currentTimeMillis()+".tri";
//
// if( ps.getTriangles() == null || ps.getTriangles().isEmpty() )
// {
// return;
// }
//
// try
// {
//
// writer = new FileWriter(file);
// w = new BufferedWriter(writer);
// for( DelaunayTriangle t : ps.getTriangles() )
// {
// for( int i=0; i<3; i++ )
// {
// w.write( Float.toString( t.points[i].getXf() ) +","+ Float.toString( t.points[i].getYf() )+" ");
// }
//// w.newLine();
// }
// logger.info( "Saved triangle lines\n" + file );
// }
// catch( IOException e )
// {
// logger.error( "Failed to save triangle lines" + e.getMessage() );
// }
// finally
// {
// if( w != null )
// {
// try
// {
// w.close();
// }
// catch( IOException e2 )
// {
// }
// }
// }
// }
}
| Java |
package org.poly2tri.examples.ardor3d.misc;
public enum ExampleSets
{
Example1 ("example1.dat",1,0,0,true),
Example2 ("example2.dat",1,0,0,true),
Example3 ("example3.dat",1,0,0,false),
Example4 ("example4.dat",1,0,0,false);
private final static String m_basePath = "org/poly2tri/examples/data/pointsets/";
private String m_filename;
private double m_scale;
private double m_x;
private double m_y;
private boolean _invertedYAxis;
ExampleSets( String filename, double scale, double x, double y, boolean invertedY )
{
m_filename = filename;
m_scale = scale;
m_x = x;
m_y = y;
_invertedYAxis = invertedY;
}
public String getFilename()
{
return m_basePath + m_filename;
}
public double getScale()
{
return m_scale;
}
public double getX()
{
return m_x;
}
public double getY()
{
return m_y;
}
public boolean invertedYAxis()
{
return _invertedYAxis;
}
} | Java |
package org.poly2tri.examples.ardor3d.misc;
import org.poly2tri.triangulation.point.TPoint;
public class MyPoint extends TPoint
{
int index;
public MyPoint( double x, double y )
{
super( x, y );
}
public void setIndex(int i)
{
index = i;
}
public int getIndex()
{
return index;
}
public boolean equals(Object other)
{
if (!(other instanceof MyPoint)) return false;
MyPoint p = (MyPoint)other;
return getX() == p.getX() && getY() == p.getY();
}
public int hashCode() { return (int)getX() + (int)getY(); }
}
| Java |
package org.poly2tri.examples.ardor3d.misc;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.geometry.polygon.PolygonSet;
import org.poly2tri.polygon.ardor3d.ArdorPolygon;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.delaunay.DelaunayTriangle;
import org.poly2tri.triangulation.point.TPoint;
import org.poly2tri.triangulation.sets.PointSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ardor3d.math.Vector3;
public class DataLoader
{
private final static Logger logger = LoggerFactory.getLogger( DataLoader.class );
public static Polygon loadModel( ExampleModels model, double scale )
throws FileNotFoundException, IOException
{
String line;
ArrayList<Vector3> points = new ArrayList<Vector3>();
InputStream istream = DataLoader.class.getClassLoader().getResourceAsStream( model.getFilename() );
if( istream == null )
{
throw new FileNotFoundException( "Couldn't find " + model );
}
InputStreamReader ir = new InputStreamReader( istream );
BufferedReader reader = new BufferedReader( ir );
while( ( line = reader.readLine() ) != null )
{
StringTokenizer tokens = new StringTokenizer( line, " ," );
points.add( new Vector3( Double.valueOf( tokens.nextToken() ).doubleValue(),
Double.valueOf( tokens.nextToken() ).doubleValue(),
0f ));
}
if( points.isEmpty() )
{
throw new IOException( "no data in file " + model );
}
// Rescale models so they are centered at 0,0 and don't fall outside the
// unit square
double maxX, maxY, minX, minY;
maxX = minX = points.get( 0 ).getX();
if( model.invertedYAxis() )
{
maxY = minY = -points.get( 0 ).getY();
}
else
{
maxY = minY = points.get( 0 ).getY();
}
for( Vector3 p : points )
{
if( model.invertedYAxis() )
{
p.setY( -p.getY() );
}
maxX = p.getX() > maxX ? p.getX() : maxX;
maxY = p.getY() > maxY ? p.getY() : maxY;
minX = p.getX() < minX ? p.getX() : minX;
minY = p.getY() < minY ? p.getY() : minY;
}
double width, height, xScale, yScale;
width = maxX - minX;
height = maxY - minY;
xScale = scale * 1f / width;
yScale = scale * 1f / height;
// System.out.println("scale/height=" + SCALE + "/" + height );
// System.out.println("scale=" + yScale);
for( Vector3 p : points )
{
if( model.invertedYAxis() )
{
p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 );
}
else
{
p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 );
}
p.multiplyLocal( xScale < yScale ? xScale : yScale );
}
return new ArdorPolygon( points);
}
public static PointSet loadPointSet( ExampleSets set, double scale )
throws FileNotFoundException, IOException
{
String line;
ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>();
InputStream istream = DataLoader.class.getClassLoader().getResourceAsStream( set.getFilename() );
if( istream == null )
{
throw new FileNotFoundException( "Couldn't find " + set );
}
InputStreamReader ir = new InputStreamReader( istream );
BufferedReader reader = new BufferedReader( ir );
while( ( line = reader.readLine() ) != null )
{
StringTokenizer tokens = new StringTokenizer( line, " ," );
points.add( new TPoint( scale*Float.valueOf( tokens.nextToken() ).floatValue(),
scale*Float.valueOf( tokens.nextToken() ).floatValue() ));
}
if( points.isEmpty() )
{
throw new IOException( "no data in file " + set );
}
// Rescale models so they are centered at 0,0 and don't fall outside the
// unit square
// double maxX, maxY, minX, minY;
// maxX = minX = points.get( 0 ).getX();
// if( set.invertedYAxis() )
// {
// maxY = minY = -points.get( 0 ).getY();
// }
// else
// {
// maxY = minY = points.get( 0 ).getY();
// }
// for( TPoint p : points )
// {
// if( set.invertedYAxis() )
// {
// p.setY( -p.getY() );
// }
// maxX = p.getX() > maxX ? p.getX() : maxX;
// maxY = p.getY() > maxY ? p.getY() : maxY;
// minX = p.getX() < minX ? p.getX() : minX;
// minY = p.getY() < minY ? p.getY() : minY;
// }
//
// double width, height, xScale, yScale;
// width = maxX - minX;
// height = maxY - minY;
// xScale = scale * 1f / width;
// yScale = scale * 1f / height;
//
// // System.out.println("scale/height=" + SCALE + "/" + height );
// // System.out.println("scale=" + yScale);
//
// for( TPoint p : points )
// {
// if( set.invertedYAxis() )
// {
// p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 );
// }
// else
// {
// p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 );
// }
// p.multiplyLocal( xScale < yScale ? xScale : yScale );
// }
return new PointSet( points );
}
public static void saveModel( String path, TriangulationPoint[] points )
{
FileWriter writer = null;
BufferedWriter w = null;
String file = path+System.currentTimeMillis()+".dat";
try
{
writer = new FileWriter(file);
w = new BufferedWriter(writer);
for( TriangulationPoint p : points )
{
w.write( Float.toString( p.getXf() ) +" "+ Float.toString( p.getYf() ));
w.newLine();
}
logger.info( "Saved polygon\n" + file );
}
catch( IOException e )
{
logger.error( "Failed to save model" );
}
finally
{
if( w != null )
{
try
{
w.close();
}
catch( IOException e2 )
{
}
}
}
}
/**
* This is a very unoptimal dump of the triangles as absolute lines.
* For manual importation to an SVG<br>
*
* @param path
* @param ps
*/
public static void saveTriLine( String path, PolygonSet ps )
{
FileWriter writer = null;
BufferedWriter w = null;
String file = path+System.currentTimeMillis()+".tri";
if( ps.getPolygons() == null || ps.getPolygons().isEmpty() )
{
return;
}
try
{
writer = new FileWriter(file);
w = new BufferedWriter(writer);
for( DelaunayTriangle t : ps.getPolygons().get(0).getTriangles() )
{
for( int i=0; i<3; i++ )
{
w.write( Float.toString( t.points[i].getXf() ) +","+ Float.toString( t.points[i].getYf() )+" ");
}
// w.newLine();
}
logger.info( "Saved triangle lines\n" + file );
}
catch( IOException e )
{
logger.error( "Failed to save triangle lines" + e.getMessage() );
}
finally
{
if( w != null )
{
try
{
w.close();
}
catch( IOException e2 )
{
}
}
}
}
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.examples.ardor3d;
import java.io.IOException;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;
import org.poly2tri.examples.ardor3d.base.P2TExampleBase;
import org.poly2tri.examples.ardor3d.misc.DataLoader;
import org.poly2tri.examples.ardor3d.misc.ExampleModels;
import org.poly2tri.examples.ardor3d.misc.Triangle;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.geometry.polygon.PolygonSet;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.delaunay.DelaunayTriangle;
import org.poly2tri.triangulation.delaunay.sweep.AdvancingFront;
import org.poly2tri.triangulation.delaunay.sweep.AdvancingFrontNode;
import org.poly2tri.triangulation.delaunay.sweep.DTSweepConstraint;
import org.poly2tri.triangulation.delaunay.sweep.DTSweepContext;
import org.poly2tri.triangulation.point.TPoint;
import org.poly2tri.triangulation.sets.ConstrainedPointSet;
import org.poly2tri.triangulation.sets.PointSet;
import org.poly2tri.triangulation.util.PolygonGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ardor3d.framework.Canvas;
import com.ardor3d.framework.FrameHandler;
import com.ardor3d.input.Key;
import com.ardor3d.input.logical.InputTrigger;
import com.ardor3d.input.logical.KeyPressedCondition;
import com.ardor3d.input.logical.LogicalLayer;
import com.ardor3d.input.logical.TriggerAction;
import com.ardor3d.input.logical.TwoInputStates;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.renderer.IndexMode;
import com.ardor3d.renderer.state.WireframeState;
import com.ardor3d.scenegraph.Line;
import com.ardor3d.scenegraph.Point;
import com.ardor3d.util.ReadOnlyTimer;
import com.ardor3d.util.geom.BufferUtils;
import com.google.inject.Inject;
/**
* Toggle Model with PageUp and PageDown<br>
* Toggle Wireframe with Home<br>
* Toggle Vertex points with End<br>
* Use 1 and 2 to generate random polygons<br>
*
* @author Thomas
*
*/
public class CDTModelExample extends P2TExampleBase
{
private final static Logger logger = LoggerFactory.getLogger( CDTModelExample.class );
private ExampleModels m_currentModel = ExampleModels.Two;
private static double SCALE = 50;
private Line m_line;
// Build parameters
private int m_vertexCount = 10000;
// Scene components
private CDTSweepAdvancingFront _cdtSweepAdvancingFront;
private CDTSweepActiveNode _cdtSweepActiveNode;
private CDTSweepActiveTriangles _cdtSweepActiveTriangle;
private CDTSweepActiveEdge _cdtSweepActiveEdge;
// private GUICircumCircle m_circumCircle;
private int m_stepCount = 0;
private boolean m_autoStep = true;
private final String m_dataPath = "src/main/resources/org/poly2tri/examples/data/";
public static void main(final String[] args)
{
start(CDTModelExample.class);
}
@Inject
public CDTModelExample( LogicalLayer logicalLayer, FrameHandler frameHandler )
{
super( logicalLayer, frameHandler );
}
protected void updateExample(final ReadOnlyTimer timer)
{
super.updateExample( timer );
if( getContext().isDebugEnabled() )
{
int count = _process.getStepCount();
if( m_stepCount < count )
{
_process.requestRead();
if( _process.isReadable() )
{
updateMesh();
m_stepCount = count;
if( m_autoStep )
{
_process.resume();
}
}
}
}
}
@Override
protected void initExample()
{
super.initExample();
// getContext().isDebugEnabled( true );
if( getContext().isDebugEnabled() )
{
_cdtSweepAdvancingFront = new CDTSweepAdvancingFront();
_node.attachChild( _cdtSweepAdvancingFront.getSceneNode() );
_cdtSweepActiveNode = new CDTSweepActiveNode();
_node.attachChild( _cdtSweepActiveNode.getSceneNode() );
_cdtSweepActiveTriangle = new CDTSweepActiveTriangles();
_node.attachChild( _cdtSweepActiveTriangle.getSceneNode() );
_cdtSweepActiveEdge = new CDTSweepActiveEdge();
_node.attachChild( _cdtSweepActiveEdge.getSceneNode() );
// m_circumCircle = new GUICircumCircle();
// m_node.attachChild( m_circumCircle.getSceneNode() );
}
buildModel(m_currentModel);
triangulate();
}
/**
* Update text information.
*/
protected void updateText()
{
super.updateText();
_exampleInfo[3].setText("[PageUp] Next model");
_exampleInfo[4].setText("[PageDown] Previous model");
_exampleInfo[5].setText("[1] Generate polygon type A ");
_exampleInfo[6].setText("[2] Generate polygon type B ");
}
private void buildModel( ExampleModels model )
{
Polygon poly;
if( model != null )
{
try
{
poly = DataLoader.loadModel( model, SCALE );
_polygonSet = new PolygonSet( poly );
}
catch( IOException e )
{
logger.info( "Failed to load model {}", e.getMessage() );
model = null;
}
}
if( model == null )
{
_polygonSet = new PolygonSet( PolygonGenerator.RandomCircleSweep( SCALE, m_vertexCount ) );
}
}
private ConstrainedPointSet buildCustom()
{
ArrayList<TriangulationPoint> list = new ArrayList<TriangulationPoint>(20);
int[] index;
list.add( new TPoint(2.2715518,-4.5233157) );
list.add( new TPoint(3.4446202,-3.5232647) );
list.add( new TPoint(4.7215156,-4.5233157) );
list.add( new TPoint(6.0311967,-3.5232647) );
list.add( new TPoint(3.4446202,-7.2578132) );
list.add( new TPoint(.81390847,-3.5232647) );
index = new int[]{3,5};
return new ConstrainedPointSet( list, index );
}
protected void triangulate()
{
super.triangulate();
m_stepCount = 0;
}
protected void updateMesh()
{
super.updateMesh();
DTSweepContext tcx = getContext();
if( tcx.isDebugEnabled() )
{
_cdtSweepActiveTriangle.update( tcx );
_cdtSweepActiveEdge.update( tcx );
_cdtSweepActiveNode.update( tcx );
_cdtSweepAdvancingFront.update( tcx );
// m_circumCircle.update( tcx.getCircumCircle() );
}
}
@Override
public void registerInputTriggers()
{
super.registerInputTriggers();
// SPACE - toggle models
_logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.PAGEUP_PRIOR ), new TriggerAction() {
public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf )
{
int index;
index = (m_currentModel.ordinal()+1)%ExampleModels.values().length;
m_currentModel = ExampleModels.values()[index];
buildModel(m_currentModel);
_node.setScale( m_currentModel.getScale() );
triangulate();
}
} ) );
// SPACE - toggle models backwards
_logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.PAGEDOWN_NEXT ), new TriggerAction() {
public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf )
{
int index;
index = ((m_currentModel.ordinal()-1)%ExampleModels.values().length + ExampleModels.values().length)%ExampleModels.values().length;
m_currentModel = ExampleModels.values()[index];
buildModel(m_currentModel);
_node.setScale( m_currentModel.getScale() );
triangulate();
}
} ) );
_logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.ONE ), new TriggerAction() {
public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf )
{
_polygonSet = new PolygonSet( PolygonGenerator.RandomCircleSweep( SCALE, m_vertexCount ) );
triangulate();
}
} ) );
_logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.TWO ), new TriggerAction() {
public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf )
{
_polygonSet = new PolygonSet( PolygonGenerator.RandomCircleSweep2( SCALE, 200 ) );
triangulate();
}
} ) );
// X -start
_logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.X ), new TriggerAction() {
public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf )
{
// Lets create a TriangulationProcess that allows you to step thru the TriangulationAlgorithm
// _process.getContext().isDebugEnabled( true );
// _process.triangulate();
// m_stepCount = 0;
}
} ) );
// C - step
_logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.C ), new TriggerAction() {
public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf )
{
// updateMesh();
_process.resume();
}
} ) );
// Z - toggle autostep
_logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.Z ), new TriggerAction() {
public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf )
{
m_autoStep = m_autoStep ? false : true;
}
} ) );
// space - save triangle lines
_logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.SPACE ), new TriggerAction() {
public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf )
{
// PolygonLoader.saveTriLine( m_dataPath, _polygonSet );
m_stepCount = 0;
_process.triangulate( buildCustom() );
}
} ) );
}
class CDTSweepAdvancingFront extends SceneElement<DTSweepContext>
{
protected Line m_nodeLines;
protected Point m_frontPoints;
protected Line m_frontLine;
public CDTSweepAdvancingFront()
{
super("AdvancingFront");
m_frontLine = new Line();
m_frontLine.getMeshData().setIndexMode( IndexMode.LineStrip );
m_frontLine.getMeshData().setVertexBuffer( BufferUtils.createVector3Buffer( 800 ) );
m_frontLine.setDefaultColor( ColorRGBA.ORANGE );
m_frontLine.setTranslation( 0, 0.05, 0 );
_node.attachChild( m_frontLine );
m_frontPoints = new Point();
m_frontPoints.getMeshData().setVertexBuffer( m_frontLine.getMeshData().getVertexBuffer() );
m_frontPoints.setPointSize( 6 );
m_frontPoints.setDefaultColor( ColorRGBA.ORANGE );
m_frontPoints.setTranslation( 0, 0.05, 0 );
_node.attachChild( m_frontPoints );
m_nodeLines = new Line();
m_nodeLines.getMeshData().setIndexMode( IndexMode.Lines );
m_nodeLines.getMeshData().setVertexBuffer( BufferUtils.createVector3Buffer( 2*800 ) );
m_nodeLines.setDefaultColor( ColorRGBA.YELLOW );
m_nodeLines.setTranslation( 0, 0.05, 0 );
_node.attachChild( m_nodeLines );
}
@Override
public void update( DTSweepContext tcx )
{
AdvancingFront front = ((DTSweepContext)tcx).getAdvancingFront();
AdvancingFrontNode node;
DelaunayTriangle tri;
if( front == null ) return;
FloatBuffer fb = m_frontLine.getMeshData().getVertexBuffer();
FloatBuffer nodeVert = m_nodeLines.getMeshData().getVertexBuffer();
fb.limit( fb.capacity() );
nodeVert.limit( fb.capacity() );
fb.rewind();
nodeVert.rewind();
int count=0;
node = front.head;
TriangulationPoint point;
do
{
point = node.getPoint();
fb.put( point.getXf() ).put( point.getYf() ).put( point.getZf() );
tri = node.getTriangle();
if( tri != null )
{
nodeVert.put( point.getXf() ).put( point.getYf() ).put( point.getZf() );
nodeVert.put( ( tri.points[0].getXf() + tri.points[1].getXf() + tri.points[2].getXf() )/3 );
nodeVert.put( ( tri.points[0].getYf() + tri.points[1].getYf() + tri.points[2].getYf() )/3 );
nodeVert.put( ( tri.points[0].getZf() + tri.points[1].getZf() + tri.points[2].getZf() )/3 );
}
count++;
} while( (node = node.getNext()) != null );
fb.limit( 3*count );
nodeVert.limit( 2*count*3 );
}
}
// class GUICircumCircle extends SceneElement<Tuple2<TriangulationPoint,Double>>
// {
// private int VCNT = 64;
// private Line m_circle = new Line();
//
// public GUICircumCircle()
// {
// super("CircumCircle");
// m_circle.getMeshData().setIndexMode( IndexMode.LineLoop );
// m_circle.getMeshData().setVertexBuffer( BufferUtils.createVector3Buffer( VCNT ) );
// m_circle.setDefaultColor( ColorRGBA.WHITE );
// m_circle.setLineWidth( 1 );
// m_node.attachChild( m_circle );
// }
//
// @Override
// public void update( Tuple2<TriangulationPoint,Double> circle )
// {
// float x,y;
// if( circle.a != null )
// {
// FloatBuffer fb = m_circle.getMeshData().getVertexBuffer();
// fb.rewind();
// for( int i=0; i < VCNT; i++ )
// {
// x = (float)circle.a.getX() + (float)(circle.b*Math.cos( 2*Math.PI*((double)i%VCNT)/VCNT ));
// y = (float)circle.a.getY() + (float)(circle.b*Math.sin( 2*Math.PI*((double)i%VCNT)/VCNT ));
// fb.put( x ).put( y ).put( 0 );
// }
// }
// else
// {
// m_node.detachAllChildren();
// }
// }
// }
class CDTSweepMeshExtended extends CDTSweepMesh
{
// private Line m_conLine = new Line();
public CDTSweepMeshExtended()
{
super();
// Line that show the connection between triangles
// m_conLine.setDefaultColor( ColorRGBA.RED );
// m_conLine.getMeshData().setIndexMode( IndexMode.Lines );
// m_node.attachChild( m_conLine );
//
// vertBuf = BufferUtils.createFloatBuffer( size*3*3*3 );
// m_conLine.getMeshData().setVertexBuffer( vertBuf );
}
@Override
public void update( List<DelaunayTriangle> triangles )
{
super.update( triangles );
// MeshData md;
// Vector3 v1 = Vector3.fetchTempInstance();
// Vector3 v2 = Vector3.fetchTempInstance();
// FloatBuffer v2Buf;
//
//
// md = m_mesh.getMeshData();
// v2Buf = m_conLine.getMeshData().getVertexBuffer();
//
//// logger.info( "Triangle count [{}]", tcx.getMap().size() );
//
// int size = 2*3*3*ps.getTriangles().size();
// if( v2Buf.capacity() < size )
// {
// v2Buf = BufferUtils.createFloatBuffer( size );
// m_conLine.getMeshData().setVertexBuffer( v2Buf );
// }
// else
// {
// v2Buf.limit( 2*size );
// }
//
// v2Buf.rewind();
// int lineCount=0;
// ArdorVector3Point p;
// for( DelaunayTriangle t : ps.getTriangles() )
// {
// v1.set( t.points[0] ).addLocal( t.points[1] ).addLocal( t.points[2] ).multiplyLocal( 1.0d/3 );
// if( t.neighbors[0] != null )
// {
// v2.set( t.points[2] ).subtractLocal( t.points[1] ).multiplyLocal( 0.5 ).addLocal( t.points[1] );
// v2Buf.put( v1.getXf() ).put( v1.getYf() ).put( v1.getZf() );
// v2Buf.put( v2.getXf() ).put( v2.getYf() ).put( v2.getZf() );
// lineCount++;
// }
// if( t.neighbors[1] != null )
// {
// v2.set( t.points[0] ).subtractLocal( t.points[2] ).multiplyLocal( 0.5 ).addLocal( t.points[2] );
// v2Buf.put( v1.getXf() ).put( v1.getYf() ).put( v1.getZf() );
// v2Buf.put( v2.getXf() ).put( v2.getYf() ).put( v2.getZf() );
// lineCount++;
// }
// if( t.neighbors[2] != null )
// {
// v2.set( t.points[1] ).subtractLocal( t.points[0] ).multiplyLocal( 0.5 ).addLocal( t.points[0] );
// v2Buf.put( v1.getXf() ).put( v1.getYf() ).put( v1.getZf() );
// v2Buf.put( v2.getXf() ).put( v2.getYf() ).put( v2.getZf() );
// lineCount++;
// }
// }
// v2Buf.limit( 2*3*lineCount );
// Vector3.releaseTempInstance( v1 );
// Vector3.releaseTempInstance( v2 );
}
}
class CDTSweepActiveEdge extends SceneElement<DTSweepContext>
{
private Line m_edgeLine = new Line();
public CDTSweepActiveEdge()
{
super("ActiveEdge");
m_edgeLine.getMeshData().setIndexMode( IndexMode.Lines );
m_edgeLine.getMeshData().setVertexBuffer( BufferUtils.createVector3Buffer( 2 ) );
m_edgeLine.setDefaultColor( ColorRGBA.YELLOW );
m_edgeLine.setLineWidth( 3 );
}
@Override
public void update( DTSweepContext tcx )
{
DTSweepConstraint edge = tcx.getDebugContext().getActiveConstraint();
if( edge != null )
{
FloatBuffer fb = m_edgeLine.getMeshData().getVertexBuffer();
fb.rewind();
fb.put( edge.getP().getXf() ).put( edge.getP().getYf() ).put( 0 );
fb.put( edge.getQ().getXf() ).put( edge.getQ().getYf() ).put( 0 );
_node.attachChild( m_edgeLine );
}
else
{
_node.detachAllChildren();
}
}
}
class CDTSweepActiveTriangles extends SceneElement<DTSweepContext>
{
private Triangle m_a = new Triangle();
private Triangle m_b = new Triangle();
public CDTSweepActiveTriangles()
{
super("ActiveTriangles");
_node.getSceneHints().setAllPickingHints( false );
m_a.setDefaultColor( new ColorRGBA( 0.8f,0.8f,0.8f,1.0f ) );
m_b.setDefaultColor( new ColorRGBA( 0.5f,0.5f,0.5f,1.0f ) );
}
public void setScale( double scale )
{
m_a.setScale( scale );
m_b.setScale( scale );
}
@Override
public void update( DTSweepContext tcx )
{
DelaunayTriangle t,t2;
t = tcx.getDebugContext().getPrimaryTriangle();
t2 = tcx.getDebugContext().getSecondaryTriangle();
_node.detachAllChildren();
if( t != null )
{
FloatBuffer fb = m_a.getMeshData().getVertexBuffer();
fb.rewind();
fb.put( t.points[0].getXf() ).put( t.points[0].getYf() ).put( t.points[0].getZf() );
fb.put( t.points[1].getXf() ).put( t.points[1].getYf() ).put( t.points[1].getZf() );
fb.put( t.points[2].getXf() ).put( t.points[2].getYf() ).put( t.points[2].getZf() );
_node.attachChild( m_a );
}
if( t2 != null )
{
FloatBuffer fb = m_b.getMeshData().getVertexBuffer();
fb.rewind();
fb.put( t2.points[0].getXf() ).put( t2.points[0].getYf() ).put( t2.points[0].getZf() );
fb.put( t2.points[1].getXf() ).put( t2.points[1].getYf() ).put( t2.points[1].getZf() );
fb.put( t2.points[2].getXf() ).put( t2.points[2].getYf() ).put( t2.points[2].getZf() );
_node.attachChild( m_b );
}
}
}
class CDTSweepActiveNode extends SceneElement<DTSweepContext>
{
private Triangle m_a = new Triangle();
private Triangle m_b = new Triangle();
private Triangle m_c = new Triangle();
public CDTSweepActiveNode()
{
super("WorkingNode");
_node.setRenderState( new WireframeState() );
m_a.setDefaultColor( ColorRGBA.DARK_GRAY );
m_b.setDefaultColor( ColorRGBA.LIGHT_GRAY );
m_c.setDefaultColor( ColorRGBA.DARK_GRAY );
setScale( 0.5 );
}
public void setScale( double scale )
{
m_a.setScale( scale );
m_b.setScale( scale );
m_c.setScale( scale );
}
@Override
public void update( DTSweepContext tcx )
{
AdvancingFrontNode node = tcx.getDebugContext().getActiveNode();
TriangulationPoint p;
if( node != null )
{
if( node.getPrevious() != null )
{
p = node.getPrevious().getPoint();
m_a.setTranslation( p.getXf(), p.getYf(), p.getZf() );
}
p = node.getPoint();
m_b.setTranslation( p.getXf(), p.getYf(), p.getZf() );
if( node.getNext() != null )
{
p = node.getNext().getPoint();
m_c.setTranslation( p.getXf(), p.getYf(), p.getZf() );
}
_node.attachChild( m_a );
_node.attachChild( m_b );
_node.attachChild( m_c );
}
else
{
_node.detachAllChildren();
}
}
}
}
| Java |
package org.poly2tri.examples.ardor3d;
import java.io.IOException;
import java.util.ArrayList;
import org.poly2tri.Poly2Tri;
import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase;
import org.poly2tri.examples.ardor3d.misc.DataLoader;
import org.poly2tri.examples.ardor3d.misc.ExampleSets;
import org.poly2tri.triangulation.TriangulationAlgorithm;
import org.poly2tri.triangulation.TriangulationContext;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.point.TPoint;
import org.poly2tri.triangulation.sets.PointSet;
import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper;
import org.poly2tri.triangulation.util.PointGenerator;
import com.ardor3d.framework.FrameHandler;
import com.ardor3d.input.logical.LogicalLayer;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.renderer.state.WireframeState;
import com.ardor3d.scenegraph.Mesh;
import com.google.inject.Inject;
public class DTUniformDistributionExample extends P2TSimpleExampleBase
{
public static void main(final String[] args)
{
start(DTUniformDistributionExample.class);
}
@Inject
public DTUniformDistributionExample( LogicalLayer logicalLayer, FrameHandler frameHandler )
{
super( logicalLayer, frameHandler );
}
@Override
protected void initExample()
{
super.initExample();
PointSet ps;
Mesh mesh;
mesh = new Mesh();
mesh.setDefaultColor( ColorRGBA.BLUE );
mesh.setRenderState( new WireframeState() );
_node.attachChild( mesh );
try
{
ps = DataLoader.loadPointSet( ExampleSets.Example2, 0.1 );
ps = new PointSet( PointGenerator.uniformDistribution( 10000, 60 ) );
Poly2Tri.triangulate( ps );
ArdorMeshMapper.updateTriangleMesh( mesh, ps );
}
catch( IOException e )
{}
}
}
| Java |
package org.poly2tri.examples.ardor3d;
import java.util.List;
import org.poly2tri.Poly2Tri;
import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.point.TPoint;
import org.poly2tri.triangulation.sets.ConstrainedPointSet;
import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper;
import org.poly2tri.triangulation.util.PointGenerator;
import com.ardor3d.framework.FrameHandler;
import com.ardor3d.input.logical.LogicalLayer;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.scenegraph.Mesh;
import com.google.inject.Inject;
public class CDTUniformDistributionExample extends P2TSimpleExampleBase
{
public static void main(final String[] args)
{
start(CDTUniformDistributionExample.class);
}
@Inject
public CDTUniformDistributionExample( LogicalLayer logicalLayer, FrameHandler frameHandler )
{
super( logicalLayer, frameHandler );
}
@Override
protected void initExample()
{
super.initExample();
Mesh mesh = new Mesh();
mesh.setDefaultColor( ColorRGBA.BLUE );
_node.attachChild( mesh );
double scale = 100;
int size = 1000;
int index = (int)(Math.random()*size);
List<TriangulationPoint> points = PointGenerator.uniformDistribution( size, scale );
// Lets add a constraint that cuts the uniformDistribution in half
points.add( new TPoint(0,scale/2) );
points.add( new TPoint(0,-scale/2) );
index = size;
ConstrainedPointSet cps = new ConstrainedPointSet( points, new int[]{ index, index+1 } );
Poly2Tri.triangulate( cps );
ArdorMeshMapper.updateTriangleMesh( mesh, cps );
}
}
| Java |
package org.poly2tri.examples.ardor3d;
import java.util.ArrayList;
import org.poly2tri.Poly2Tri;
import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.geometry.polygon.PolygonPoint;
import org.poly2tri.triangulation.point.TPoint;
import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper;
import org.poly2tri.triangulation.util.PolygonGenerator;
import com.ardor3d.framework.FrameHandler;
import com.ardor3d.input.logical.LogicalLayer;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.renderer.state.WireframeState;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.scenegraph.Node;
import com.google.inject.Inject;
public class CDTSteinerPointExample extends P2TSimpleExampleBase
{
public static void main(final String[] args)
{
start(CDTSteinerPointExample.class);
}
@Inject
public CDTSteinerPointExample( LogicalLayer logicalLayer, FrameHandler frameHandler )
{
super( logicalLayer, frameHandler );
}
@Override
protected void initExample()
{
super.initExample();
Node node = new Node();
node.setRenderState( new WireframeState() );
_node.attachChild( node );
Polygon poly;
poly = createCirclePolygon( 32, 1.5 );
// top left
Mesh mesh = new Mesh();
mesh.setDefaultColor( ColorRGBA.BLUE );
mesh.setTranslation( -2, 2, 0 );
node.attachChild( mesh );
Poly2Tri.triangulate( poly );
ArdorMeshMapper.updateTriangleMesh( mesh, poly );
// bottom left
mesh = new Mesh();
mesh.setDefaultColor( ColorRGBA.RED );
mesh.setTranslation( -2, -2, 0 );
node.attachChild( mesh );
poly.addSteinerPoint( new TPoint(0,0) );
Poly2Tri.triangulate( poly );
ArdorMeshMapper.updateTriangleMesh( mesh, poly );
poly = PolygonGenerator.RandomCircleSweep2( 4, 200 );
// top right
mesh = new Mesh();
mesh.setDefaultColor( ColorRGBA.BLUE );
mesh.setTranslation( 2, 2, 0 );
node.attachChild( mesh );
Poly2Tri.triangulate( poly );
ArdorMeshMapper.updateTriangleMesh( mesh, poly );
// bottom right
mesh = new Mesh();
mesh.setDefaultColor( ColorRGBA.RED );
mesh.setTranslation( 2, -2, 0 );
node.attachChild( mesh );
poly.addSteinerPoint( new TPoint(0,0) );
Poly2Tri.triangulate( poly );
ArdorMeshMapper.updateTriangleMesh( mesh, poly );
}
private Polygon createCirclePolygon( int n, double radius )
{
if( n < 3 ) n=3;
PolygonPoint[] points = new PolygonPoint[n];
for( int i=0; i<n; i++ )
{
points[i] = new PolygonPoint( radius*Math.cos( (2.0*Math.PI*i)/n ),
radius*Math.sin( (2.0*Math.PI*i)/n ) );
}
return new Polygon( points );
}
}
| Java |
package org.poly2tri.examples;
import org.poly2tri.Poly2Tri;
import org.poly2tri.triangulation.sets.PointSet;
import org.poly2tri.triangulation.util.PointGenerator;
public class ProfilingExample
{
public static void main(final String[] args)
throws Exception
{
PointSet ps = new PointSet( PointGenerator.uniformDistribution( 50, 500000 ) );
for( int i=0; i<1; i++ )
{
Poly2Tri.triangulate( ps );
}
Thread.sleep( 10000000 );
}
public void startProfiling()
throws Exception
{
}
}
| Java |
package org.poly2tri.examples.geotools;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.opengis.feature.Feature;
import org.opengis.feature.GeometryAttribute;
import org.poly2tri.Poly2Tri;
import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.geometry.polygon.PolygonPoint;
import org.poly2tri.geometry.polygon.PolygonSet;
import org.poly2tri.transform.coordinate.CoordinateTransform;
import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ardor3d.example.ExampleBase;
import com.ardor3d.framework.Canvas;
import com.ardor3d.framework.FrameHandler;
import com.ardor3d.image.Image;
import com.ardor3d.image.Texture;
import com.ardor3d.image.Texture.WrapMode;
import com.ardor3d.input.MouseButton;
import com.ardor3d.input.logical.InputTrigger;
import com.ardor3d.input.logical.LogicalLayer;
import com.ardor3d.input.logical.MouseButtonClickedCondition;
import com.ardor3d.input.logical.TriggerAction;
import com.ardor3d.input.logical.TwoInputStates;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.math.MathUtils;
import com.ardor3d.math.Matrix3;
import com.ardor3d.math.Vector3;
import com.ardor3d.renderer.queue.RenderBucketType;
import com.ardor3d.renderer.state.BlendState;
import com.ardor3d.renderer.state.MaterialState;
import com.ardor3d.renderer.state.WireframeState;
import com.ardor3d.renderer.state.ZBufferState;
import com.ardor3d.renderer.state.BlendState.BlendEquation;
import com.ardor3d.scenegraph.FloatBufferData;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.scenegraph.Node;
import com.ardor3d.scenegraph.extension.Skybox;
import com.ardor3d.scenegraph.extension.Skybox.Face;
import com.ardor3d.scenegraph.hint.LightCombineMode;
import com.ardor3d.scenegraph.shape.Sphere;
import com.ardor3d.util.ReadOnlyTimer;
import com.ardor3d.util.TextureManager;
import com.ardor3d.util.resource.ResourceLocatorTool;
import com.ardor3d.util.resource.SimpleResourceLocator;
import com.google.inject.Inject;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.MultiLineString;
import com.vividsolutions.jts.geom.MultiPolygon;
/**
* Hello world!
*
*/
public class WorldExample extends P2TSimpleExampleBase
{
private final static Logger logger = LoggerFactory.getLogger( WorldExample.class );
private final static CoordinateTransform _wgs84 = new WGS84GeodeticTransform(100);
private Node _worldNode;
private Skybox _skybox;
private final Matrix3 rotate = new Matrix3();
private double angle = 0;
private boolean _doRotate = true;
/**
* We use one PolygonSet for each country since countries can have islands
* and be composed of multiple polygons
*/
private ArrayList<PolygonSet> _countries = new ArrayList<PolygonSet>();
@Inject
public WorldExample( LogicalLayer logicalLayer, FrameHandler frameHandler )
{
super( logicalLayer, frameHandler );
}
public static void main( String[] args )
throws Exception
{
try
{
start(WorldExample.class);
}
catch( RuntimeException e )
{
logger.error( "WorldExample failed due to a runtime exception" );
}
}
@Override
protected void updateExample( ReadOnlyTimer timer )
{
if( _doRotate )
{
angle += timer.getTimePerFrame() * 10;
angle %= 360;
rotate.fromAngleNormalAxis(angle * MathUtils.DEG_TO_RAD, Vector3.UNIT_Z);
_worldNode.setRotation(rotate);
}
}
@Override
protected void initExample()
{
super.initExample();
try
{
importShape(100);
}
catch( IOException e )
{
}
_canvas.getCanvasRenderer().getCamera().setLocation(200, 200, 200);
_canvas.getCanvasRenderer().getCamera().lookAt( 0, 0, 0, Vector3.UNIT_Z );
_worldNode = new Node("shape");
// _worldNode.setRenderState( new WireframeState() );
_node.attachChild( _worldNode );
buildSkyBox();
Sphere seas = new Sphere("seas", Vector3.ZERO, 64, 64, 100.2f);
seas.setDefaultColor( new ColorRGBA(0,0,0.5f,0.25f) );
seas.getSceneHints().setRenderBucketType( RenderBucketType.Transparent );
BlendState bs = new BlendState();
bs.setBlendEnabled( true );
bs.setEnabled( true );
bs.setBlendEquationAlpha( BlendEquation.Max );
bs.setSourceFunction(BlendState.SourceFunction.SourceAlpha);
bs.setDestinationFunction(BlendState.DestinationFunction.OneMinusSourceAlpha);
seas.setRenderState( bs );
ZBufferState zb = new ZBufferState();
zb.setEnabled( true );
zb.setWritable( false );
seas.setRenderState( zb );
_worldNode.attachChild( seas );
Sphere core = new Sphere("seas", Vector3.ZERO, 16, 16, 10f);
core.getSceneHints().setLightCombineMode( LightCombineMode.Replace );
MaterialState ms = new MaterialState();
ms.setEmissive( new ColorRGBA(0.8f,0.2f,0,0.9f) );
core.setRenderState( ms );
_worldNode.attachChild( core );
Mesh mesh;
for( PolygonSet ps : _countries )
{
Poly2Tri.triangulate( ps );
float value = 1-0.9f*(float)Math.random();
for( Polygon p : ps.getPolygons() )
{
mesh = new Mesh();
mesh.setDefaultColor( new ColorRGBA( value, value, value, 1.0f ) );
_worldNode.attachChild( mesh );
ArdorMeshMapper.updateTriangleMesh( mesh, p, _wgs84 );
}
}
}
protected void importShape( double rescale )
throws IOException
{
// URL url = WorldExample.class.getResource( "/z5UKI.shp" );
URL url = WorldExample.class.getResource( "/earth/countries.shp" );
url.getFile();
ShapefileDataStore ds = new ShapefileDataStore(url);
FeatureSource featureSource = ds.getFeatureSource();
// for( int i=0; i < ds.getTypeNames().length; i++)
// {
// System.out.println("ShapefileDataStore.typename=" + ds.getTypeNames()[i] );
// }
FeatureCollection fc = featureSource.getFeatures();
// System.out.println( "featureCollection.ID=" + fc.getID() );
// System.out.println( "featureCollection.schema=" + fc.getSchema() );
// System.out.println( "featureCollection.Bounds[minX,maxX,minY,maxY]=["
// + fc.getBounds().getMinX() + "," +
// + fc.getBounds().getMaxX() + "," +
// + fc.getBounds().getMinY() + "," +
// + fc.getBounds().getMaxY() + "]" );
// double width, height, xScale, yScale, scale, dX, dY;
// width = fc.getBounds().getMaxX() - fc.getBounds().getMinX();
// height = fc.getBounds().getMaxY() - fc.getBounds().getMinY();
// dX = fc.getBounds().getMinX() + width/2;
// dY = fc.getBounds().getMinY() + height/2;
// xScale = rescale * 1f / width;
// yScale = rescale * 1f / height;
// scale = xScale < yScale ? xScale : yScale;
FeatureIterator fi;
Feature f;
GeometryAttribute geoAttrib;
Polygon polygon;
PolygonSet polygonSet;
fi = fc.features();
while( fi.hasNext() )
{
polygonSet = new PolygonSet();
f = fi.next();
geoAttrib = f.getDefaultGeometryProperty();
// System.out.println( "Feature.Identifier:" + f.getIdentifier() );
// System.out.println( "Feature.Name:" + f.getName() );
// System.out.println( "Feature.Type:" + f.getType() );
// System.out.println( "Feature.Descriptor:" + geoAttrib.getDescriptor() );
// System.out.println( "GeoAttrib.Identifier=" + geoAttrib.getIdentifier() );
// System.out.println( "GeoAttrib.Name=" + geoAttrib.getName() );
// System.out.println( "GeoAttrib.Type.Name=" + geoAttrib.getType().getName() );
// System.out.println( "GeoAttrib.Type.Binding=" + geoAttrib.getType().getBinding() );
// System.out.println( "GeoAttrib.Value=" + geoAttrib.getValue() );
if( geoAttrib.getType().getBinding() == MultiLineString.class )
{
MultiLineString mls = (MultiLineString)geoAttrib.getValue();
Coordinate[] coords = mls.getCoordinates();
// System.out.println( "MultiLineString.coordinates=" + coords.length );
ArrayList<PolygonPoint> points = new ArrayList<PolygonPoint>(coords.length);
for( int i=0; i<coords.length; i++)
{
points.add( new PolygonPoint(coords[i].x,coords[i].y) );
// System.out.println( "[x,y]=[" + coords[i].x + "," + coords[i].y + "]" );
}
polygonSet.add( new Polygon(points) );
}
else if( geoAttrib.getType().getBinding() == MultiPolygon.class )
{
MultiPolygon mp = (MultiPolygon)geoAttrib.getValue();
// System.out.println( "MultiPolygon.NumGeometries=" + mp.getNumGeometries() );
for( int i=0; i<mp.getNumGeometries(); i++ )
{
com.vividsolutions.jts.geom.Polygon jtsPolygon = (com.vividsolutions.jts.geom.Polygon)mp.getGeometryN(i);
polygon = buildPolygon( jtsPolygon );
polygonSet.add( polygon );
}
}
_countries.add( polygonSet );
}
}
private static Polygon buildPolygon( com.vividsolutions.jts.geom.Polygon jtsPolygon )
{
Polygon polygon;
LinearRing shell;
ArrayList<PolygonPoint> points;
// Envelope envelope;
// System.out.println( "MultiPolygon.points=" + jtsPolygon.getNumPoints() );
// System.out.println( "MultiPolygon.NumInteriorRing=" + jtsPolygon.getNumInteriorRing() );
// envelope = jtsPolygon.getEnvelopeInternal();
shell = (LinearRing)jtsPolygon.getExteriorRing();
Coordinate[] coords = shell.getCoordinates();
points = new ArrayList<PolygonPoint>(coords.length);
// Skipping last coordinate since JTD defines a shell as a LineString that start with
// same first and last coordinate
for( int j=0; j<coords.length-1; j++)
{
points.add( new PolygonPoint(coords[j].x,coords[j].y) );
}
polygon = new Polygon(points);
return polygon;
}
//
// private void refinePolygon()
// {
//
// }
/**
* Builds the sky box.
*/
private void buildSkyBox()
{
_skybox = new Skybox("skybox", 300, 300, 300);
try {
SimpleResourceLocator sr2 = new SimpleResourceLocator(ExampleBase.class.getClassLoader().getResource("org/poly2tri/examples/geotools/textures/"));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, sr2);
} catch (final URISyntaxException ex) {
ex.printStackTrace();
}
final String dir = "";
final Texture stars = TextureManager.load(dir + "stars.gif",
Texture.MinificationFilter.Trilinear,
Image.Format.GuessNoCompression, true);
_skybox.setTexture(Skybox.Face.North, stars);
_skybox.setTexture(Skybox.Face.West, stars);
_skybox.setTexture(Skybox.Face.South, stars);
_skybox.setTexture(Skybox.Face.East, stars);
_skybox.setTexture(Skybox.Face.Up, stars);
_skybox.setTexture(Skybox.Face.Down, stars);
_skybox.getTexture( Skybox.Face.North ).setWrap( WrapMode.Repeat );
for( Face f : Face.values() )
{
FloatBufferData fbd = _skybox.getFace(f).getMeshData().getTextureCoords().get( 0 );
fbd.getBuffer().clear();
fbd.getBuffer().put( 0 ).put( 4 );
fbd.getBuffer().put( 0 ).put( 0 );
fbd.getBuffer().put( 4 ).put( 0 );
fbd.getBuffer().put( 4 ).put( 4 );
}
_node.attachChild( _skybox );
}
@Override
public void registerInputTriggers()
{
super.registerInputTriggers();
// SPACE - toggle models
_logicalLayer.registerTrigger( new InputTrigger( new MouseButtonClickedCondition(MouseButton.RIGHT), new TriggerAction() {
public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf )
{
_doRotate = _doRotate ? false : true;
}
} ) );
}
/*
* http://en.wikipedia.org/wiki/Longitude#Degree_length
* http://www.colorado.edu/geography/gcraft/notes/datum/gif/llhxyz.gif
*
* x (in m) = Latitude * 60 * 1852
* y (in m) = (PI/180) * cos(Longitude) * (637813.7^2 / sqrt( (637813.7 * cos(Longitude))^2 + (635675.23 * sin(Longitude))^2 ) )
* z (in m) = Altitude
*
* The 'quick and dirty' method (assuming the Earth is a perfect sphere):
*
* x = longitude*60*1852*cos(latitude)
* y = latitude*60*1852
*
* Latitude and longitude must be in decimal degrees, x and y are in meters.
* The origin of the xy-grid is the intersection of the 0-degree meridian
* and the equator, where x is positive East and y is positive North.
*
* So, why the 1852? I'm using the (original) definition of a nautical mile
* here: 1 nautical mile = the length of one arcminute on the equator (hence
* the 60*1852; I'm converting the lat/lon degrees to lat/lon minutes).
*/
}
| Java |
package org.poly2tri.geometry.primitives;
public abstract class Point
{
public abstract double getX();
public abstract double getY();
public abstract double getZ();
public abstract float getXf();
public abstract float getYf();
public abstract float getZf();
public abstract void set( double x, double y, double z );
protected static int calculateHashCode( double x, double y, double z)
{
int result = 17;
final long a = Double.doubleToLongBits(x);
result += 31 * result + (int) (a ^ (a >>> 32));
final long b = Double.doubleToLongBits(y);
result += 31 * result + (int) (b ^ (b >>> 32));
final long c = Double.doubleToLongBits(z);
result += 31 * result + (int) (c ^ (c >>> 32));
return result;
}
}
| Java |
package org.poly2tri.geometry.primitives;
public abstract class Edge<A extends Point>
{
protected A p;
protected A q;
public A getP()
{
return p;
}
public A getQ()
{
return q;
}
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.geometry.polygon;
import java.util.ArrayList;
import java.util.List;
public class PolygonSet
{
protected ArrayList<Polygon> _polygons = new ArrayList<Polygon>();
public PolygonSet()
{
}
public PolygonSet( Polygon poly )
{
_polygons.add( poly );
}
public void add( Polygon p )
{
_polygons.add( p );
}
public List<Polygon> getPolygons()
{
return _polygons;
}
}
| Java |
package org.poly2tri.geometry.polygon;
import org.poly2tri.triangulation.point.TPoint;
public class PolygonPoint extends TPoint
{
protected PolygonPoint _next;
protected PolygonPoint _previous;
public PolygonPoint( double x, double y )
{
super( x, y );
}
public PolygonPoint( double x, double y, double z )
{
super( x, y, z );
}
public void setPrevious( PolygonPoint p )
{
_previous = p;
}
public void setNext( PolygonPoint p )
{
_next = p;
}
public PolygonPoint getNext()
{
return _next;
}
public PolygonPoint getPrevious()
{
return _previous;
}
}
| Java |
package org.poly2tri.geometry.polygon;
public class PolygonUtil
{
/**
* TODO
* @param polygon
*/
public static void validate( Polygon polygon )
{
// TODO: implement
// 1. Check for duplicate points
// 2. Check for intersecting sides
}
}
| Java |
package org.poly2tri.geometry.polygon;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.poly2tri.triangulation.Triangulatable;
import org.poly2tri.triangulation.TriangulationContext;
import org.poly2tri.triangulation.TriangulationMode;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.delaunay.DelaunayTriangle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Polygon implements Triangulatable
{
private final static Logger logger = LoggerFactory.getLogger( Polygon.class );
protected ArrayList<TriangulationPoint> _points = new ArrayList<TriangulationPoint>();
protected ArrayList<TriangulationPoint> _steinerPoints;
protected ArrayList<Polygon> _holes;
protected List<DelaunayTriangle> m_triangles;
protected PolygonPoint _last;
/**
* To create a polygon we need atleast 3 separate points
*
* @param p1
* @param p2
* @param p3
*/
public Polygon( PolygonPoint p1, PolygonPoint p2, PolygonPoint p3 )
{
p1._next = p2;
p2._next = p3;
p3._next = p1;
p1._previous = p3;
p2._previous = p1;
p3._previous = p2;
_points.add( p1 );
_points.add( p2 );
_points.add( p3 );
}
/**
* Requires atleast 3 points
* @param points - ordered list of points forming the polygon.
* No duplicates are allowed
*/
public Polygon( List<PolygonPoint> points )
{
// Lets do one sanity check that first and last point hasn't got same position
// Its something that often happen when importing polygon data from other formats
if( points.get(0).equals( points.get(points.size()-1) ) )
{
logger.warn( "Removed duplicate point");
points.remove( points.size()-1 );
}
_points.addAll( points );
}
/**
* Requires atleast 3 points
*
* @param points
*/
public Polygon( PolygonPoint[] points )
{
this( Arrays.asList( points ) );
}
public TriangulationMode getTriangulationMode()
{
return TriangulationMode.POLYGON;
}
public int pointCount()
{
int count = _points.size();
if( _steinerPoints != null )
{
count += _steinerPoints.size();
}
return count;
}
public void addSteinerPoint( TriangulationPoint point )
{
if( _steinerPoints == null )
{
_steinerPoints = new ArrayList<TriangulationPoint>();
}
_steinerPoints.add( point );
}
public void addSteinerPoints( List<TriangulationPoint> points )
{
if( _steinerPoints == null )
{
_steinerPoints = new ArrayList<TriangulationPoint>();
}
_steinerPoints.addAll( points );
}
public void clearSteinerPoints()
{
if( _steinerPoints != null )
{
_steinerPoints.clear();
}
}
/**
* Assumes: that given polygon is fully inside the current polygon
* @param poly - a subtraction polygon
*/
public void addHole( Polygon poly )
{
if( _holes == null )
{
_holes = new ArrayList<Polygon>();
}
_holes.add( poly );
// XXX: tests could be made here to be sure it is fully inside
// addSubtraction( poly.getPoints() );
}
/**
* Will insert a point in the polygon after given point
*
* @param a
* @param b
* @param p
*/
public void insertPointAfter( PolygonPoint a, PolygonPoint newPoint )
{
// Validate that
int index = _points.indexOf( a );
if( index != -1 )
{
newPoint.setNext( a.getNext() );
newPoint.setPrevious( a );
a.getNext().setPrevious( newPoint );
a.setNext( newPoint );
_points.add( index+1, newPoint );
}
else
{
throw new RuntimeException( "Tried to insert a point into a Polygon after a point not belonging to the Polygon" );
}
}
public void addPoints( List<PolygonPoint> list )
{
PolygonPoint first;
for( PolygonPoint p : list )
{
p.setPrevious( _last );
if( _last != null )
{
p.setNext( _last.getNext() );
_last.setNext( p );
}
_last = p;
_points.add( p );
}
first = (PolygonPoint)_points.get(0);
_last.setNext( first );
first.setPrevious( _last );
}
/**
* Will add a point after the last point added
*
* @param p
*/
public void addPoint(PolygonPoint p )
{
p.setPrevious( _last );
p.setNext( _last.getNext() );
_last.setNext( p );
_points.add( p );
}
public void removePoint( PolygonPoint p )
{
PolygonPoint next, prev;
next = p.getNext();
prev = p.getPrevious();
prev.setNext( next );
next.setPrevious( prev );
_points.remove( p );
}
public PolygonPoint getPoint()
{
return _last;
}
public List<TriangulationPoint> getPoints()
{
return _points;
}
public List<DelaunayTriangle> getTriangles()
{
return m_triangles;
}
public void addTriangle( DelaunayTriangle t )
{
m_triangles.add( t );
}
public void addTriangles( List<DelaunayTriangle> list )
{
m_triangles.addAll( list );
}
public void clearTriangulation()
{
if( m_triangles != null )
{
m_triangles.clear();
}
}
/**
* Creates constraints and populates the context with points
*/
public void prepareTriangulation( TriangulationContext<?> tcx )
{
if( m_triangles == null )
{
m_triangles = new ArrayList<DelaunayTriangle>( _points.size() );
}
else
{
m_triangles.clear();
}
// Outer constraints
for( int i = 0; i < _points.size()-1 ; i++ )
{
tcx.newConstraint( _points.get( i ), _points.get( i+1 ) );
}
tcx.newConstraint( _points.get( 0 ), _points.get( _points.size()-1 ) );
tcx.addPoints( _points );
// Hole constraints
if( _holes != null )
{
for( Polygon p : _holes )
{
for( int i = 0; i < p._points.size()-1 ; i++ )
{
tcx.newConstraint( p._points.get( i ), p._points.get( i+1 ) );
}
tcx.newConstraint( p._points.get( 0 ), p._points.get( p._points.size()-1 ) );
tcx.addPoints( p._points );
}
}
if( _steinerPoints != null )
{
tcx.addPoints( _steinerPoints );
}
}
}
| Java |
package org.poly2tri.triangulation;
public abstract class TriangulationDebugContext
{
protected TriangulationContext<?> _tcx;
public TriangulationDebugContext( TriangulationContext<?> tcx )
{
_tcx = tcx;
}
public abstract void clear();
}
| Java |
package org.poly2tri.triangulation;
public enum TriangulationMode
{
UNCONSTRAINED,CONSTRAINED,POLYGON;
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.triangulation.point;
import org.poly2tri.triangulation.TriangulationPoint;
public class TPoint extends TriangulationPoint
{
private double _x;
private double _y;
private double _z;
public TPoint( double x, double y )
{
this( x, y, 0 );
}
public TPoint( double x, double y, double z )
{
_x = x;
_y = y;
_z = z;
}
public double getX() { return _x; }
public double getY() { return _y; }
public double getZ() { return _z; }
public float getXf() { return (float)_x; }
public float getYf() { return (float)_y; }
public float getZf() { return (float)_z; }
@Override
public void set( double x, double y, double z )
{
_x = x;
_y = y;
_z = z;
}
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.triangulation.point;
import java.nio.FloatBuffer;
import org.poly2tri.triangulation.TriangulationPoint;
public class FloatBufferPoint extends TriangulationPoint
{
private final FloatBuffer _fb;
private final int _ix,_iy,_iz;
public FloatBufferPoint( FloatBuffer fb, int index )
{
_fb = fb;
_ix = index;
_iy = index+1;
_iz = index+2;
}
public final double getX()
{
return _fb.get( _ix );
}
public final double getY()
{
return _fb.get( _iy );
}
public final double getZ()
{
return _fb.get( _iz );
}
public final float getXf()
{
return _fb.get( _ix );
}
public final float getYf()
{
return _fb.get( _iy );
}
public final float getZf()
{
return _fb.get( _iz );
}
@Override
public void set( double x, double y, double z )
{
_fb.put( _ix, (float)x );
_fb.put( _iy, (float)y );
_fb.put( _iz, (float)z );
}
public static TriangulationPoint[] toPoints( FloatBuffer fb )
{
FloatBufferPoint[] points = new FloatBufferPoint[fb.limit()/3];
for( int i=0,j=0; i<points.length; i++, j+=3 )
{
points[i] = new FloatBufferPoint(fb, j);
}
return points;
}
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.triangulation;
import java.util.ArrayList;
import java.util.List;
import org.poly2tri.triangulation.delaunay.DelaunayTriangle;
public abstract class TriangulationContext<A extends TriangulationDebugContext>
{
protected A _debug;
protected boolean _debugEnabled = false;
protected ArrayList<DelaunayTriangle> _triList = new ArrayList<DelaunayTriangle>();
protected ArrayList<TriangulationPoint> _points = new ArrayList<TriangulationPoint>(200);
protected TriangulationMode _triangulationMode;
protected Triangulatable _triUnit;
private boolean _terminated = false;
private boolean _waitUntilNotified;
private int _stepTime = -1;
private int _stepCount = 0;
public int getStepCount() { return _stepCount; }
public void done()
{
_stepCount++;
}
public abstract TriangulationAlgorithm algorithm();
public void prepareTriangulation( Triangulatable t )
{
_triUnit = t;
_triangulationMode = t.getTriangulationMode();
t.prepareTriangulation( this );
}
public abstract TriangulationConstraint newConstraint( TriangulationPoint a, TriangulationPoint b );
public void addToList( DelaunayTriangle triangle )
{
_triList.add( triangle );
}
public List<DelaunayTriangle> getTriangles()
{
return _triList;
}
public Triangulatable getTriangulatable()
{
return _triUnit;
}
public List<TriangulationPoint> getPoints()
{
return _points;
}
public synchronized void update(String message)
{
if( _debugEnabled )
{
try
{
synchronized( this )
{
_stepCount++;
if( _stepTime > 0 )
{
wait( (int)_stepTime );
/** Can we resume execution or are we expected to wait? */
if( _waitUntilNotified )
{
wait();
}
}
else
{
wait();
}
// We have been notified
_waitUntilNotified = false;
}
}
catch( InterruptedException e )
{
update("Triangulation was interrupted");
}
}
if( _terminated )
{
throw new RuntimeException( "Triangulation process terminated before completion");
}
}
public void clear()
{
_points.clear();
_terminated = false;
if( _debug != null )
{
_debug.clear();
}
_stepCount=0;
}
public TriangulationMode getTriangulationMode()
{
return _triangulationMode;
}
public synchronized void waitUntilNotified(boolean b)
{
_waitUntilNotified = b;
}
public void terminateTriangulation()
{
_terminated=true;
}
public boolean isDebugEnabled()
{
return _debugEnabled;
}
public abstract void isDebugEnabled( boolean b );
public A getDebugContext()
{
return _debug;
}
public void addPoints( List<TriangulationPoint> points )
{
_points.addAll( points );
}
}
| Java |
package org.poly2tri.triangulation;
import java.util.List;
import org.poly2tri.triangulation.delaunay.DelaunayTriangle;
public interface Triangulatable
{
/**
* Preparations needed before triangulation start should be handled here
* @param tcx
*/
public void prepareTriangulation( TriangulationContext<?> tcx );
public List<DelaunayTriangle> getTriangles();
public List<TriangulationPoint> getPoints();
public void addTriangle( DelaunayTriangle t );
public void addTriangles( List<DelaunayTriangle> list );
public void clearTriangulation();
public TriangulationMode getTriangulationMode();
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.triangulation;
import java.util.ArrayList;
import org.poly2tri.geometry.primitives.Point;
import org.poly2tri.triangulation.delaunay.sweep.DTSweepConstraint;
public abstract class TriangulationPoint extends Point
{
// List of edges this point constitutes an upper ending point (CDT)
private ArrayList<DTSweepConstraint> edges;
@Override
public String toString()
{
return "[" + getX() + "," + getY() + "]";
}
public abstract double getX();
public abstract double getY();
public abstract double getZ();
public abstract float getXf();
public abstract float getYf();
public abstract float getZf();
public abstract void set( double x, double y, double z );
public ArrayList<DTSweepConstraint> getEdges()
{
return edges;
}
public void addEdge( DTSweepConstraint e )
{
if( edges == null )
{
edges = new ArrayList<DTSweepConstraint>();
}
edges.add( e );
}
public boolean hasEdges()
{
return edges != null;
}
/**
* @param p - edge destination point
* @return the edge from this point to given point
*/
public DTSweepConstraint getEdge( TriangulationPoint p )
{
for( DTSweepConstraint c : edges )
{
if( c.p == p )
{
return c;
}
}
return null;
}
public boolean equals(Object obj)
{
if( obj instanceof TriangulationPoint )
{
TriangulationPoint p = (TriangulationPoint)obj;
return getX() == p.getX() && getY() == p.getY();
}
return super.equals( obj );
}
public int hashCode()
{
long bits = java.lang.Double.doubleToLongBits(getX());
bits ^= java.lang.Double.doubleToLongBits(getY()) * 31;
return (((int) bits) ^ ((int) (bits >> 32)));
}
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.triangulation.delaunay;
import java.util.ArrayList;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.delaunay.sweep.DTSweepConstraint;
import org.poly2tri.triangulation.point.TPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DelaunayTriangle
{
private final static Logger logger = LoggerFactory.getLogger( DelaunayTriangle.class );
/** Neighbor pointers */
public final DelaunayTriangle[] neighbors = new DelaunayTriangle[3];
/** Flags to determine if an edge is a Constrained edge */
public final boolean[] cEdge = new boolean[] { false, false, false };
/** Flags to determine if an edge is a Delauney edge */
public final boolean[] dEdge = new boolean[] { false, false, false };
/** Has this triangle been marked as an interior triangle? */
protected boolean interior = false;
public final TriangulationPoint[] points = new TriangulationPoint[3];
public DelaunayTriangle( TriangulationPoint p1, TriangulationPoint p2, TriangulationPoint p3 )
{
points[0] = p1;
points[1] = p2;
points[2] = p3;
}
public int index( TriangulationPoint p )
{
if( p == points[0] )
{
return 0;
}
else if( p == points[1] )
{
return 1;
}
else if( p == points[2] )
{
return 2;
}
throw new RuntimeException("Calling index with a point that doesn't exist in triangle");
}
public int indexCW( TriangulationPoint p )
{
int index = index(p);
switch( index )
{
case 0: return 2;
case 1: return 0;
default: return 1;
}
}
public int indexCCW( TriangulationPoint p )
{
int index = index(p);
switch( index )
{
case 0: return 1;
case 1: return 2;
default: return 0;
}
}
public boolean contains( TriangulationPoint p )
{
return ( p == points[0] || p == points[1] || p == points[2] );
}
public boolean contains( DTSweepConstraint e )
{
return ( contains( e.p ) && contains( e.q ) );
}
public boolean contains( TriangulationPoint p, TriangulationPoint q )
{
return ( contains( p ) && contains( q ) );
}
// Update neighbor pointers
private void markNeighbor( TriangulationPoint p1,
TriangulationPoint p2,
DelaunayTriangle t )
{
if( ( p1 == points[2] && p2 == points[1] ) || ( p1 == points[1] && p2 == points[2] ) )
{
neighbors[0] = t;
}
else if( ( p1 == points[0] && p2 == points[2] ) || ( p1 == points[2] && p2 == points[0] ) )
{
neighbors[1] = t;
}
else if( ( p1 == points[0] && p2 == points[1] ) || ( p1 == points[1] && p2 == points[0] ) )
{
neighbors[2] = t;
}
else
{
logger.error( "Neighbor error, please report!" );
// throw new Exception("Neighbor error, please report!");
}
}
/* Exhaustive search to update neighbor pointers */
public void markNeighbor( DelaunayTriangle t )
{
if( t.contains( points[1], points[2] ) )
{
neighbors[0] = t;
t.markNeighbor( points[1], points[2], this );
}
else if( t.contains( points[0], points[2] ) )
{
neighbors[1] = t;
t.markNeighbor( points[0], points[2], this );
}
else if( t.contains( points[0], points[1] ) )
{
neighbors[2] = t;
t.markNeighbor( points[0], points[1], this );
}
else
{
logger.error( "markNeighbor failed" );
}
}
public void clearNeighbors()
{
neighbors[0] = neighbors[1] = neighbors[2] = null;
}
public void clearNeighbor( DelaunayTriangle triangle )
{
if( neighbors[0] == triangle )
{
neighbors[0] = null;
}
else if( neighbors[1] == triangle )
{
neighbors[1] = null;
}
else
{
neighbors[2] = null;
}
}
/**
* Clears all references to all other triangles and points
*/
public void clear()
{
DelaunayTriangle t;
for( int i=0; i<3; i++ )
{
t = neighbors[i];
if( t != null )
{
t.clearNeighbor( this );
}
}
clearNeighbors();
points[0]=points[1]=points[2]=null;
}
/**
* @param t - opposite triangle
* @param p - the point in t that isn't shared between the triangles
* @return
*/
public TriangulationPoint oppositePoint( DelaunayTriangle t, TriangulationPoint p )
{
assert t != this : "self-pointer error";
return pointCW( t.pointCW(p) );
}
// The neighbor clockwise to given point
public DelaunayTriangle neighborCW( TriangulationPoint point )
{
if( point == points[0] )
{
return neighbors[1];
}
else if( point == points[1] )
{
return neighbors[2];
}
return neighbors[0];
}
// The neighbor counter-clockwise to given point
public DelaunayTriangle neighborCCW( TriangulationPoint point )
{
if( point == points[0] )
{
return neighbors[2];
}
else if( point == points[1] )
{
return neighbors[0];
}
return neighbors[1];
}
// The neighbor across to given point
public DelaunayTriangle neighborAcross( TriangulationPoint opoint )
{
if( opoint == points[0] )
{
return neighbors[0];
}
else if( opoint == points[1] )
{
return neighbors[1];
}
return neighbors[2];
}
// The point counter-clockwise to given point
public TriangulationPoint pointCCW( TriangulationPoint point )
{
if( point == points[0] )
{
return points[1];
}
else if( point == points[1] )
{
return points[2];
}
else if( point == points[2] )
{
return points[0];
}
logger.error( "point location error" );
throw new RuntimeException("[FIXME] point location error");
}
// The point counter-clockwise to given point
public TriangulationPoint pointCW( TriangulationPoint point )
{
if( point == points[0] )
{
return points[2];
}
else if( point == points[1] )
{
return points[0];
}
else if( point == points[2] )
{
return points[1];
}
logger.error( "point location error" );
throw new RuntimeException("[FIXME] point location error");
}
// Legalize triangle by rotating clockwise around oPoint
public void legalize( TriangulationPoint oPoint, TriangulationPoint nPoint )
{
if( oPoint == points[0] )
{
points[1] = points[0];
points[0] = points[2];
points[2] = nPoint;
}
else if( oPoint == points[1] )
{
points[2] = points[1];
points[1] = points[0];
points[0] = nPoint;
}
else if( oPoint == points[2] )
{
points[0] = points[2];
points[2] = points[1];
points[1] = nPoint;
}
else
{
logger.error( "legalization error" );
throw new RuntimeException("legalization bug");
}
}
public void printDebug()
{
System.out.println( points[0] + "," + points[1] + "," + points[2] );
}
// Finalize edge marking
public void markNeighborEdges()
{
for( int i = 0; i < 3; i++ )
{
if( cEdge[i] )
{
switch( i )
{
case 0:
if( neighbors[0] != null )
neighbors[0].markConstrainedEdge( points[1], points[2] );
break;
case 1:
if( neighbors[1] != null )
neighbors[1].markConstrainedEdge( points[0], points[2] );
break;
case 2:
if( neighbors[2] != null )
neighbors[2].markConstrainedEdge( points[0], points[1] );
break;
}
}
}
}
public void markEdge( DelaunayTriangle triangle )
{
for( int i = 0; i < 3; i++ )
{
if( cEdge[i] )
{
switch( i )
{
case 0:
triangle.markConstrainedEdge( points[1], points[2] );
break;
case 1:
triangle.markConstrainedEdge( points[0], points[2] );
break;
case 2:
triangle.markConstrainedEdge( points[0], points[1] );
break;
}
}
}
}
public void markEdge( ArrayList<DelaunayTriangle> tList )
{
for( DelaunayTriangle t : tList )
{
for( int i = 0; i < 3; i++ )
{
if( t.cEdge[i] )
{
switch( i )
{
case 0:
markConstrainedEdge( t.points[1], t.points[2] );
break;
case 1:
markConstrainedEdge( t.points[0], t.points[2] );
break;
case 2:
markConstrainedEdge( t.points[0], t.points[1] );
break;
}
}
}
}
}
public void markConstrainedEdge( int index )
{
cEdge[index] = true;
}
public void markConstrainedEdge( DTSweepConstraint edge )
{
markConstrainedEdge( edge.p, edge.q );
if( ( edge.q == points[0] && edge.p == points[1] )
|| ( edge.q == points[1] && edge.p == points[0] ) )
{
cEdge[2] = true;
}
else if( ( edge.q == points[0] && edge.p == points[2] )
|| ( edge.q == points[2] && edge.p == points[0] ) )
{
cEdge[1] = true;
}
else if( ( edge.q == points[1] && edge.p == points[2] )
|| ( edge.q == points[2] && edge.p == points[1] ) )
{
cEdge[0] = true;
}
}
// Mark edge as constrained
public void markConstrainedEdge( TriangulationPoint p, TriangulationPoint q )
{
if( ( q == points[0] && p == points[1] ) || ( q == points[1] && p == points[0] ) )
{
cEdge[2] = true;
}
else if( ( q == points[0] && p == points[2] ) || ( q == points[2] && p == points[0] ) )
{
cEdge[1] = true;
}
else if( ( q == points[1] && p == points[2] ) || ( q == points[2] && p == points[1] ) )
{
cEdge[0] = true;
}
}
public double area()
{
double a = (points[0].getX() - points[2].getX())*(points[1].getY() - points[0].getY());
double b = (points[0].getX() - points[1].getX())*(points[2].getY() - points[0].getY());
return 0.5*Math.abs( a - b );
}
public TPoint centroid()
{
double cx = ( points[0].getX() + points[1].getX() + points[2].getX() ) / 3d;
double cy = ( points[0].getY() + points[1].getY() + points[2].getY() ) / 3d;
return new TPoint( cx, cy );
}
/**
* Get the neighbor that share this edge
*
* @param constrainedEdge
* @return index of the shared edge or -1 if edge isn't shared
*/
public int edgeIndex( TriangulationPoint p1, TriangulationPoint p2 )
{
if( points[0] == p1 )
{
if( points[1] == p2 )
{
return 2;
}
else if( points[2] == p2 )
{
return 1;
}
}
else if( points[1] == p1 )
{
if( points[2] == p2 )
{
return 0;
}
else if( points[0] == p2 )
{
return 2;
}
}
else if( points[2] == p1 )
{
if( points[0] == p2 )
{
return 1;
}
else if( points[1] == p2 )
{
return 0;
}
}
return -1;
}
public boolean getConstrainedEdgeCCW( TriangulationPoint p )
{
if( p == points[0] )
{
return cEdge[2];
}
else if( p == points[1] )
{
return cEdge[0];
}
return cEdge[1];
}
public boolean getConstrainedEdgeCW( TriangulationPoint p )
{
if( p == points[0] )
{
return cEdge[1];
}
else if( p == points[1] )
{
return cEdge[2];
}
return cEdge[0];
}
public boolean getConstrainedEdgeAcross( TriangulationPoint p )
{
if( p == points[0] )
{
return cEdge[0];
}
else if( p == points[1] )
{
return cEdge[1];
}
return cEdge[2];
}
public void setConstrainedEdgeCCW( TriangulationPoint p, boolean ce )
{
if( p == points[0] )
{
cEdge[2] = ce;
}
else if( p == points[1] )
{
cEdge[0] = ce;
}
else
{
cEdge[1] = ce;
}
}
public void setConstrainedEdgeCW( TriangulationPoint p, boolean ce )
{
if( p == points[0] )
{
cEdge[1] = ce;
}
else if( p == points[1] )
{
cEdge[2] = ce;
}
else
{
cEdge[0] = ce;
}
}
public void setConstrainedEdgeAcross( TriangulationPoint p, boolean ce )
{
if( p == points[0] )
{
cEdge[0] = ce;
}
else if( p == points[1] )
{
cEdge[1] = ce;
}
else
{
cEdge[2] = ce;
}
}
public boolean getDelunayEdgeCCW( TriangulationPoint p )
{
if( p == points[0] )
{
return dEdge[2];
}
else if( p == points[1] )
{
return dEdge[0];
}
return dEdge[1];
}
public boolean getDelunayEdgeCW( TriangulationPoint p )
{
if( p == points[0] )
{
return dEdge[1];
}
else if( p == points[1] )
{
return dEdge[2];
}
return dEdge[0];
}
public boolean getDelunayEdgeAcross( TriangulationPoint p )
{
if( p == points[0] )
{
return dEdge[0];
}
else if( p == points[1] )
{
return dEdge[1];
}
return dEdge[2];
}
public void setDelunayEdgeCCW( TriangulationPoint p, boolean e )
{
if( p == points[0] )
{
dEdge[2] = e;
}
else if( p == points[1] )
{
dEdge[0] = e;
}
else
{
dEdge[1] = e;
}
}
public void setDelunayEdgeCW( TriangulationPoint p, boolean e )
{
if( p == points[0] )
{
dEdge[1] = e;
}
else if( p == points[1] )
{
dEdge[2] = e;
}
else
{
dEdge[0] = e;
}
}
public void setDelunayEdgeAcross( TriangulationPoint p, boolean e )
{
if( p == points[0] )
{
dEdge[0] = e;
}
else if( p == points[1] )
{
dEdge[1] = e;
}
else
{
dEdge[2] = e;
}
}
public void clearDelunayEdges()
{
dEdge[0] = false;
dEdge[1] = false;
dEdge[2] = false;
}
public boolean isInterior()
{
return interior;
}
public void isInterior( boolean b )
{
interior = b;
}
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.triangulation.delaunay.sweep;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.delaunay.DelaunayTriangle;
public class AdvancingFrontNode
{
protected AdvancingFrontNode next = null;
protected AdvancingFrontNode prev = null;
protected final Double key; // XXX: BST
protected final double value;
protected final TriangulationPoint point;
protected DelaunayTriangle triangle;
public AdvancingFrontNode( TriangulationPoint point )
{
this.point = point;
value = point.getX();
key = Double.valueOf( value ); // XXX: BST
}
public AdvancingFrontNode getNext()
{
return next;
}
public AdvancingFrontNode getPrevious()
{
return prev;
}
public TriangulationPoint getPoint()
{
return point;
}
public DelaunayTriangle getTriangle()
{
return triangle;
}
public boolean hasNext()
{
return next != null;
}
public boolean hasPrevious()
{
return prev != null;
}
}
| Java |
package org.poly2tri.triangulation.delaunay.sweep;
import org.poly2tri.triangulation.TriangulationContext;
import org.poly2tri.triangulation.TriangulationDebugContext;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.delaunay.DelaunayTriangle;
public class DTSweepDebugContext extends TriangulationDebugContext
{
/*
* Fields used for visual representation of current triangulation
*/
protected DelaunayTriangle _primaryTriangle;
protected DelaunayTriangle _secondaryTriangle;
protected TriangulationPoint _activePoint;
protected AdvancingFrontNode _activeNode;
protected DTSweepConstraint _activeConstraint;
public DTSweepDebugContext( DTSweepContext tcx )
{
super( tcx );
}
public boolean isDebugContext()
{
return true;
}
// private Tuple2<TPoint,Double> m_circumCircle = new Tuple2<TPoint,Double>( new TPoint(), new Double(0) );
// public Tuple2<TPoint,Double> getCircumCircle() { return m_circumCircle; }
public DelaunayTriangle getPrimaryTriangle()
{
return _primaryTriangle;
}
public DelaunayTriangle getSecondaryTriangle()
{
return _secondaryTriangle;
}
public AdvancingFrontNode getActiveNode()
{
return _activeNode;
}
public DTSweepConstraint getActiveConstraint()
{
return _activeConstraint;
}
public TriangulationPoint getActivePoint()
{
return _activePoint;
}
public void setPrimaryTriangle( DelaunayTriangle triangle )
{
_primaryTriangle = triangle;
_tcx.update("setPrimaryTriangle");
}
public void setSecondaryTriangle( DelaunayTriangle triangle )
{
_secondaryTriangle = triangle;
_tcx.update("setSecondaryTriangle");
}
public void setActivePoint( TriangulationPoint point )
{
_activePoint = point;
}
public void setActiveConstraint( DTSweepConstraint e )
{
_activeConstraint = e;
_tcx.update("setWorkingSegment");
}
public void setActiveNode( AdvancingFrontNode node )
{
_activeNode = node;
_tcx.update("setWorkingNode");
}
@Override
public void clear()
{
_primaryTriangle = null;
_secondaryTriangle = null;
_activePoint = null;
_activeNode = null;
_activeConstraint = null;
}
// public void setWorkingCircumCircle( TPoint point, TPoint point2, TPoint point3 )
// {
// double dx,dy;
//
// CircleXY.circumCenter( point, point2, point3, m_circumCircle.a );
// dx = m_circumCircle.a.getX()-point.getX();
// dy = m_circumCircle.a.getY()-point.getY();
// m_circumCircle.b = Double.valueOf( Math.sqrt( dx*dx + dy*dy ) );
//
// }
}
| Java |
package org.poly2tri.triangulation.delaunay.sweep;
import java.util.Comparator;
import org.poly2tri.triangulation.TriangulationPoint;
public class DTSweepPointComparator implements Comparator<TriangulationPoint>
{
public int compare( TriangulationPoint p1, TriangulationPoint p2 )
{
if(p1.getY() < p2.getY() )
{
return -1;
}
else if( p1.getY() > p2.getY())
{
return 1;
}
else
{
if(p1.getX() < p2.getX())
{
return -1;
}
else if( p1.getX() > p2.getX() )
{
return 1;
}
else
{
return 0;
}
}
}
}
| Java |
package org.poly2tri.triangulation.delaunay.sweep;
public class PointOnEdgeException extends RuntimeException
{
/**
*
*/
private static final long serialVersionUID = 1L;
public PointOnEdgeException( String msg )
{
super(msg);
}
}
| Java |
package org.poly2tri.triangulation.delaunay.sweep;
public class AdvancingFrontIndex<A>
{
double _min,_max;
IndexNode<A> _root;
public AdvancingFrontIndex( double min, double max, int depth )
{
if( depth > 5 ) depth = 5;
_root = createIndex( depth );
}
private IndexNode<A> createIndex( int n )
{
IndexNode<A> node = null;
if( n > 0 )
{
node = new IndexNode<A>();
node.bigger = createIndex( n-1 );
node.smaller = createIndex( n-1 );
}
return node;
}
public A fetchAndRemoveIndex( A key )
{
return null;
}
public A fetchAndInsertIndex( A key )
{
return null;
}
class IndexNode<A>
{
A value;
IndexNode<A> smaller;
IndexNode<A> bigger;
double range;
}
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.triangulation;
public enum TriangulationAlgorithm
{
DTSweep
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.triangulation;
public enum TriangulationProcessEvent
{
Started,Waiting,Failed,Aborted,Done
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.triangulation.sets;
import java.util.ArrayList;
import java.util.List;
import org.poly2tri.triangulation.Triangulatable;
import org.poly2tri.triangulation.TriangulationContext;
import org.poly2tri.triangulation.TriangulationMode;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.delaunay.DelaunayTriangle;
public class PointSet implements Triangulatable
{
List<TriangulationPoint> _points;
List<DelaunayTriangle> _triangles;
public PointSet( List<TriangulationPoint> points )
{
_points = new ArrayList<TriangulationPoint>();
_points.addAll( points );
}
public TriangulationMode getTriangulationMode()
{
return TriangulationMode.UNCONSTRAINED;
}
public List<TriangulationPoint> getPoints()
{
return _points;
}
public List<DelaunayTriangle> getTriangles()
{
return _triangles;
}
public void addTriangle( DelaunayTriangle t )
{
_triangles.add( t );
}
public void addTriangles( List<DelaunayTriangle> list )
{
_triangles.addAll( list );
}
public void clearTriangulation()
{
_triangles.clear();
}
public void prepareTriangulation( TriangulationContext<?> tcx )
{
if( _triangles == null )
{
_triangles = new ArrayList<DelaunayTriangle>( _points.size() );
}
else
{
_triangles.clear();
}
tcx.addPoints( _points );
}
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.triangulation.util;
public class Tuple2<A,B>
{
public A a;
public B b;
public Tuple2(A a,B b)
{
this.a = a;
this.b = b;
}
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.triangulation.util;
public class Tuple3<A,B,C>
{
public A a;
public B b;
public C c;
public Tuple3(A a,B b,C c)
{
this.a = a;
this.b = b;
this.c = c;
}
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.triangulation.util;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.geometry.polygon.PolygonPoint;
public class PolygonGenerator
{
private static final double PI_2 = 2.0*Math.PI;
public static Polygon RandomCircleSweep( double scale, int vertexCount )
{
PolygonPoint point;
PolygonPoint[] points;
double radius = scale/4;
points = new PolygonPoint[vertexCount];
for(int i=0; i<vertexCount; i++)
{
do
{
if( i%250 == 0 )
{
radius += scale/2*(0.5 - Math.random());
}
else if( i%50 == 0 )
{
radius += scale/5*(0.5 - Math.random());
}
else
{
radius += 25*scale/vertexCount*(0.5 - Math.random());
}
radius = radius > scale/2 ? scale/2 : radius;
radius = radius < scale/10 ? scale/10 : radius;
} while( radius < scale/10 || radius > scale/2 );
point = new PolygonPoint( radius*Math.cos( (PI_2*i)/vertexCount ),
radius*Math.sin( (PI_2*i)/vertexCount ) );
points[i] = point;
}
return new Polygon( points );
}
public static Polygon RandomCircleSweep2( double scale, int vertexCount )
{
PolygonPoint point;
PolygonPoint[] points;
double radius = scale/4;
points = new PolygonPoint[vertexCount];
for(int i=0; i<vertexCount; i++)
{
do
{
radius += scale/5*(0.5 - Math.random());
radius = radius > scale/2 ? scale/2 : radius;
radius = radius < scale/10 ? scale/10 : radius;
} while( radius < scale/10 || radius > scale/2 );
point = new PolygonPoint( radius*Math.cos( (PI_2*i)/vertexCount ),
radius*Math.sin( (PI_2*i)/vertexCount ) );
points[i] = point;
}
return new Polygon( points );
}
}
| Java |
package org.poly2tri.triangulation.util;
import java.util.ArrayList;
import java.util.List;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.point.TPoint;
public class PointGenerator
{
public static List<TriangulationPoint> uniformDistribution( int n, double scale )
{
ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>();
for( int i=0; i<n; i++ )
{
points.add( new TPoint( scale*(0.5 - Math.random()), scale*(0.5 - Math.random()) ) );
}
return points;
}
public static List<TriangulationPoint> uniformGrid( int n, double scale )
{
double x=0;
double size = scale/n;
double halfScale = 0.5*scale;
ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>();
for( int i=0; i<n+1; i++ )
{
x = halfScale - i*size;
for( int j=0; j<n+1; j++ )
{
points.add( new TPoint( x, halfScale - j*size ) );
}
}
return points;
}
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.triangulation;
public interface TriangulationProcessListener
{
public void triangulationEvent( TriangulationProcessEvent e, Triangulatable unit );
}
| Java |
package org.poly2tri.transform.coordinate;
/**
* A transform that aligns the XY plane normal [0,0,1] with any given target normal
*
* http://www.cs.brown.edu/~jfh/papers/Moller-EBA-1999/paper.pdf
*
* @author thahlen@gmail.com
*
*/
public class XYToAnyTransform extends Matrix3Transform
{
/**
* Assumes target normal is normalized
*/
public XYToAnyTransform( double nx, double ny, double nz )
{
setTargetNormal( nx, ny, nz );
}
/**
* Assumes target normal is normalized
*
* @param nx
* @param ny
* @param nz
*/
public void setTargetNormal( double nx, double ny, double nz )
{
double h,f,c,vx,vy,hvx;
vx = ny;
vy = -nx;
c = nz;
h = (1-c)/(1-c*c);
hvx = h*vx;
f = (c < 0) ? -c : c;
if( f < 1.0 - 1.0E-4 )
{
m00=c + hvx*vx;
m01=hvx*vy;
m02=-vy;
m10=hvx*vy;
m11=c + h*vy*vy;
m12=vx;
m20=vy;
m21=-vx;
m22=c;
}
else
{
// if "from" and "to" vectors are nearly parallel
m00=1;
m01=0;
m02=0;
m10=0;
m11=1;
m12=0;
m20=0;
m21=0;
if( c > 0 )
{
m22=1;
}
else
{
m22=-1;
}
}
}
}
| Java |
package org.poly2tri.transform.coordinate;
import java.util.List;
import org.poly2tri.geometry.primitives.Point;
public class NoTransform implements CoordinateTransform
{
public void transform( Point p, Point store )
{
store.set( p.getX(), p.getY(), p.getZ() );
}
public void transform( Point p )
{
}
public void transform( List<? extends Point> list )
{
}
}
| Java |
package org.poly2tri.transform.coordinate;
/**
* A transform that aligns given source normal with the XY plane normal [0,0,1]
*
* @author thahlen@gmail.com
*/
public class AnyToXYTransform extends Matrix3Transform
{
/**
* Assumes source normal is normalized
*/
public AnyToXYTransform( double nx, double ny, double nz )
{
setSourceNormal( nx, ny, nz );
}
/**
* Assumes source normal is normalized
*
* @param nx
* @param ny
* @param nz
*/
public void setSourceNormal( double nx, double ny, double nz )
{
double h,f,c,vx,vy,hvx;
vx = -ny;
vy = nx;
c = nz;
h = (1-c)/(1-c*c);
hvx = h*vx;
f = (c < 0) ? -c : c;
if( f < 1.0 - 1.0E-4 )
{
m00=c + hvx*vx;
m01=hvx*vy;
m02=-vy;
m10=hvx*vy;
m11=c + h*vy*vy;
m12=vx;
m20=vy;
m21=-vx;
m22=c;
}
else
{
// if "from" and "to" vectors are nearly parallel
m00=1;
m01=0;
m02=0;
m10=0;
m11=1;
m12=0;
m20=0;
m21=0;
if( c > 0 )
{
m22=1;
}
else
{
m22=-1;
}
}
}
}
| Java |
package org.poly2tri.transform.coordinate;
import java.util.List;
import org.poly2tri.geometry.primitives.Point;
public abstract class Matrix3Transform implements CoordinateTransform
{
protected double m00,m01,m02,m10,m11,m12,m20,m21,m22;
public void transform( Point p, Point store )
{
final double px = p.getX();
final double py = p.getY();
final double pz = p.getZ();
store.set(m00 * px + m01 * py + m02 * pz,
m10 * px + m11 * py + m12 * pz,
m20 * px + m21 * py + m22 * pz );
}
public void transform( Point p )
{
final double px = p.getX();
final double py = p.getY();
final double pz = p.getZ();
p.set(m00 * px + m01 * py + m02 * pz,
m10 * px + m11 * py + m12 * pz,
m20 * px + m21 * py + m22 * pz );
}
public void transform( List<? extends Point> list )
{
for( Point p : list )
{
transform( p );
}
}
}
| Java |
package org.poly2tri.transform.coordinate;
import java.util.List;
import org.poly2tri.geometry.primitives.Point;
public abstract interface CoordinateTransform
{
public abstract void transform( Point p, Point store );
public abstract void transform( Point p );
public abstract void transform( List<? extends Point> list );
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.geometry.polygon.PolygonSet;
import org.poly2tri.triangulation.Triangulatable;
import org.poly2tri.triangulation.TriangulationAlgorithm;
import org.poly2tri.triangulation.TriangulationContext;
import org.poly2tri.triangulation.TriangulationMode;
import org.poly2tri.triangulation.TriangulationProcess;
import org.poly2tri.triangulation.delaunay.sweep.DTSweep;
import org.poly2tri.triangulation.delaunay.sweep.DTSweepContext;
import org.poly2tri.triangulation.sets.ConstrainedPointSet;
import org.poly2tri.triangulation.sets.PointSet;
import org.poly2tri.triangulation.util.PolygonGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Poly2Tri
{
private final static Logger logger = LoggerFactory.getLogger( Poly2Tri.class );
private static final TriangulationAlgorithm _defaultAlgorithm = TriangulationAlgorithm.DTSweep;
public static void triangulate( PolygonSet ps )
{
TriangulationContext<?> tcx = createContext( _defaultAlgorithm );
for( Polygon p : ps.getPolygons() )
{
tcx.prepareTriangulation( p );
triangulate( tcx );
tcx.clear();
}
}
public static void triangulate( Polygon p )
{
triangulate( _defaultAlgorithm, p );
}
public static void triangulate( ConstrainedPointSet cps )
{
triangulate( _defaultAlgorithm, cps );
}
public static void triangulate( PointSet ps )
{
triangulate( _defaultAlgorithm, ps );
}
public static TriangulationContext<?> createContext( TriangulationAlgorithm algorithm )
{
switch( algorithm )
{
case DTSweep:
default:
return new DTSweepContext();
}
}
public static void triangulate( TriangulationAlgorithm algorithm,
Triangulatable t )
{
TriangulationContext<?> tcx;
// long time = System.nanoTime();
tcx = createContext( algorithm );
tcx.prepareTriangulation( t );
triangulate( tcx );
// logger.info( "Triangulation of {} points [{}ms]", tcx.getPoints().size(), ( System.nanoTime() - time ) / 1e6 );
}
public static void triangulate( TriangulationContext<?> tcx )
{
switch( tcx.algorithm() )
{
case DTSweep:
default:
DTSweep.triangulate( (DTSweepContext)tcx );
}
}
/**
* Will do a warmup run to let the JVM optimize the triangulation code
*/
public static void warmup()
{
/*
* After a method is run 10000 times, the Hotspot compiler will compile
* it into native code. Periodically, the Hotspot compiler may recompile
* the method. After an unspecified amount of time, then the compilation
* system should become quiet.
*/
Polygon poly = PolygonGenerator.RandomCircleSweep2( 50, 50000 );
TriangulationProcess process = new TriangulationProcess();
process.triangulate( poly );
}
}
| Java |
package br.com.teckstoq.views.telasArquivos;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import br.com.teckstoq.utilitarios.buscaCep;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
@SuppressWarnings("serial")
public class tela_cad_filial extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField campoMatricula;
private JTextField campoNomeFilial;
private JTextField campoCnpjFilia;
private JTextField campoInsEstaFilial;
private JLabel lblMtricula;
private JLabel lblNome;
private JLabel lblCpf;
private JLabel lblRg;
private JLabel lblEndereo;
private JTextField campoEnd;
private JLabel lblNumero;
private JTextField campaNu;
private JLabel lblBairro;
private JTextField campaBairro;
private JLabel lblCidade;
private JTextField campoCidade;
private JLabel lblEstado;
private JTextField CampoEstado;
private JLabel lblFone;
private JTextField campoFone1;
private JLabel lblFone_1;
private JTextField campoFone2;
private JLabel lblEmail;
private JTextField camapoEmail;
private JTextField campoCep;
private JLabel label;
private JTextField campoSite;
private JButton btnCadastrar;
private JLabel lblEmpresaMatriz;
@SuppressWarnings("rawtypes")
private JComboBox comboBoxEmprasaMae;
@SuppressWarnings("rawtypes")
public tela_cad_filial() {
setResizable(false);
setIconImage(Toolkit.getDefaultToolkit().getImage(tela_cad_filial.class.getResource("/br/com/teckstoq/imagens/iconeBorda1.png")));
setTitle("Prefer\u00EAncias");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
campaBairro.setText(null);
campoCep.setText(null);
campoCidade.setText(null);
campoEnd.setText(null);
CampoEstado.setText(null);
campoCnpjFilia.setText(null);
campoMatricula.setText(null);
campoInsEstaFilial.setText(null);
campoNomeFilial.setText(null);
campoFone1.setText(null);
campoFone2.setText(null);
campoSite.setText(null);
camapoEmail.setText(null);
tela_cad_filial.this.dispose();
}
});
setBounds(100, 100, 725, 518);
setResizable(false);
setModal(true);
setLocationRelativeTo(null);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPanel.setBackground(new Color(13, 88, 114));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
JLabel lblCadastroEFuncionrio = new JLabel("CADASTRO DE EMPRESA");
lblCadastroEFuncionrio.setFont(new Font("Agency FB", Font.BOLD, 23));
lblCadastroEFuncionrio.setForeground(Color.WHITE);
lblCadastroEFuncionrio.setBounds(10, 11, 202, 28);
contentPanel.add(lblCadastroEFuncionrio);
campoMatricula = new JTextField();
campoMatricula.setBounds(10, 74, 86, 20);
contentPanel.add(campoMatricula);
campoMatricula.setColumns(10);
campoNomeFilial = new JTextField();
campoNomeFilial.setColumns(10);
campoNomeFilial.setBounds(10, 123, 470, 20);
contentPanel.add(campoNomeFilial);
campoCnpjFilia = new JTextField();
campoCnpjFilia.setColumns(10);
campoCnpjFilia.setBounds(10, 171, 110, 20);
contentPanel.add(campoCnpjFilia);
campoInsEstaFilial = new JTextField();
campoInsEstaFilial.setColumns(10);
campoInsEstaFilial.setBounds(130, 171, 110, 20);
contentPanel.add(campoInsEstaFilial);
lblMtricula = new JLabel("M\u00E1tricula");
lblMtricula.setForeground(Color.WHITE);
lblMtricula.setFont(new Font("Arial", Font.BOLD, 15));
lblMtricula.setBounds(10, 56, 65, 18);
contentPanel.add(lblMtricula);
lblNome = new JLabel("Nome");
lblNome.setForeground(Color.WHITE);
lblNome.setFont(new Font("Arial", Font.BOLD, 15));
lblNome.setBounds(10, 105, 41, 18);
contentPanel.add(lblNome);
lblCpf = new JLabel("CNPJ");
lblCpf.setForeground(Color.WHITE);
lblCpf.setFont(new Font("Arial", Font.BOLD, 15));
lblCpf.setBounds(10, 154, 40, 18);
contentPanel.add(lblCpf);
lblRg = new JLabel("Inscri\u00E7\u00E3o Estadual");
lblRg.setForeground(Color.WHITE);
lblRg.setFont(new Font("Arial", Font.BOLD, 15));
lblRg.setBounds(130, 154, 129, 18);
contentPanel.add(lblRg);
lblEndereo = new JLabel("CEP");
lblEndereo.setForeground(Color.WHITE);
lblEndereo.setFont(new Font("Arial", Font.BOLD, 15));
lblEndereo.setBounds(10, 202, 31, 18);
contentPanel.add(lblEndereo);
campoEnd = new JTextField();
campoEnd.setColumns(10);
campoEnd.setBounds(222, 225, 258, 20);
contentPanel.add(campoEnd);
lblNumero = new JLabel("Numero");
lblNumero.setForeground(Color.WHITE);
lblNumero.setFont(new Font("Arial", Font.BOLD, 15));
lblNumero.setBounds(10, 256, 56, 18);
contentPanel.add(lblNumero);
campaNu = new JTextField();
campaNu.setColumns(10);
campaNu.setBounds(10, 279, 65, 20);
contentPanel.add(campaNu);
lblBairro = new JLabel("Bairro");
lblBairro.setForeground(Color.WHITE);
lblBairro.setFont(new Font("Arial", Font.BOLD, 15));
lblBairro.setBounds(85, 256, 44, 18);
contentPanel.add(lblBairro);
campaBairro = new JTextField();
campaBairro.setColumns(10);
campaBairro.setBounds(85, 279, 184, 20);
contentPanel.add(campaBairro);
lblCidade = new JLabel("Cidade");
lblCidade.setForeground(Color.WHITE);
lblCidade.setFont(new Font("Arial", Font.BOLD, 15));
lblCidade.setBounds(279, 256, 50, 18);
contentPanel.add(lblCidade);
campoCidade = new JTextField();
campoCidade.setColumns(10);
campoCidade.setBounds(279, 279, 118, 20);
contentPanel.add(campoCidade);
lblEstado = new JLabel("Estado");
lblEstado.setForeground(Color.WHITE);
lblEstado.setFont(new Font("Arial", Font.BOLD, 15));
lblEstado.setBounds(407, 256, 49, 18);
contentPanel.add(lblEstado);
CampoEstado = new JTextField();
CampoEstado.setColumns(10);
CampoEstado.setBounds(407, 279, 73, 20);
contentPanel.add(CampoEstado);
lblFone = new JLabel("Fone 1");
lblFone.setForeground(Color.WHITE);
lblFone.setFont(new Font("Arial", Font.BOLD, 15));
lblFone.setBounds(10, 310, 48, 18);
contentPanel.add(lblFone);
campoFone1 = new JTextField();
campoFone1.setColumns(10);
campoFone1.setBounds(10, 333, 110, 20);
contentPanel.add(campoFone1);
lblFone_1 = new JLabel("Fone 2");
lblFone_1.setForeground(Color.WHITE);
lblFone_1.setFont(new Font("Arial", Font.BOLD, 15));
lblFone_1.setBounds(130, 310, 48, 18);
contentPanel.add(lblFone_1);
campoFone2 = new JTextField();
campoFone2.setColumns(10);
campoFone2.setBounds(130, 333, 110, 20);
contentPanel.add(campoFone2);
lblEmail = new JLabel("E-mail");
lblEmail.setForeground(Color.WHITE);
lblEmail.setFont(new Font("Arial", Font.BOLD, 15));
lblEmail.setBounds(250, 310, 43, 18);
contentPanel.add(lblEmail);
camapoEmail = new JTextField();
camapoEmail.setColumns(10);
camapoEmail.setBounds(250, 333, 230, 20);
contentPanel.add(camapoEmail);
campoCep = new JTextField();
campoCep.setColumns(10);
campoCep.setBounds(10, 225, 110, 20);
contentPanel.add(campoCep);
label = new JLabel("Endere\u00E7o");
label.setForeground(Color.WHITE);
label.setFont(new Font("Arial", Font.BOLD, 15));
label.setBounds(222, 202, 69, 18);
contentPanel.add(label);
JButton btnBuscar = new JButton("Buscar");
btnBuscar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
buscaCep cep = new buscaCep();
String cepdigitado = campoCep.getText().toString();
campoEnd.setText(cep.getEndereco(cepdigitado));
campaBairro.setText(cep.getBairro(cepdigitado));
campoCidade.setText(cep.getCidade(cepdigitado));
CampoEstado.setText(cep.getUF(cepdigitado));
campaNu.setFocusable(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnBuscar.setBounds(127, 224, 85, 23);
contentPanel.add(btnBuscar);
JLabel lblLogin = new JLabel("Site");
lblLogin.setForeground(Color.WHITE);
lblLogin.setFont(new Font("Arial", Font.BOLD, 15));
lblLogin.setBounds(10, 364, 28, 18);
contentPanel.add(lblLogin);
campoSite = new JTextField();
campoSite.setColumns(10);
campoSite.setBounds(10, 387, 470, 20);
contentPanel.add(campoSite);
btnCadastrar = new JButton("Cadastrar");
btnCadastrar.setBounds(10, 446, 110, 23);
contentPanel.add(btnCadastrar);
JComboBox comboBoxStatus = new JComboBox();
comboBoxStatus.setBounds(596, 11, 113, 20);
contentPanel.add(comboBoxStatus);
JLabel lblStatus = new JLabel("Status");
lblStatus.setForeground(Color.WHITE);
lblStatus.setFont(new Font("Arial", Font.BOLD, 15));
lblStatus.setBounds(541, 11, 45, 18);
contentPanel.add(lblStatus);
lblEmpresaMatriz = new JLabel("Empresa Matriz");
lblEmpresaMatriz.setForeground(Color.WHITE);
lblEmpresaMatriz.setFont(new Font("Arial", Font.BOLD, 15));
lblEmpresaMatriz.setBounds(106, 56, 110, 18);
contentPanel.add(lblEmpresaMatriz);
comboBoxEmprasaMae = new JComboBox();
comboBoxEmprasaMae.setBounds(106, 74, 374, 20);
contentPanel.add(comboBoxEmprasaMae);
}
}
| Java |
package br.com.teckstoq.views.interfacesListener;
import br.com.teckstoq.models.Fornecedor;
public interface IFornecedorListener {
public void fornecedor(Fornecedor fornecedor);
}
| Java |
package br.com.teckstoq.views.interfacesListener;
import br.com.teckstoq.models.Setor;
public interface ISetorListener {
public void setor(Setor setor);
}
| Java |
package br.com.teckstoq.views.interfacesListener;
import br.com.teckstoq.models.Peca;
public interface IPecaListener {
public void peca(Peca peca);
}
| Java |
package br.com.teckstoq.views.interfacesListener;
import br.com.teckstoq.models.Equipamento;
public interface IEquipamentoListener {
public void equipamento(Equipamento equipamento);
}
| Java |
package br.com.teckstoq.views.interfacesListener;
import br.com.teckstoq.models.Comodatario;
public interface IComodatarioListener {
public void comodatario(Comodatario comodatario);
}
| Java |
package br.com.teckstoq.views.interfacesListener;
import br.com.teckstoq.models.Funcionario;
public interface IFuncionarioListener {
public void funcionario(Funcionario funcionario);
}
| Java |
package br.com.teckstoq.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* @author Paulo Lima
* @category Projeto TeckEstoq Java SE
* @since 05/09/2014
* @version 1.0
*
*/
@SuppressWarnings("deprecation")
public class HibernateUtil {
private static final SessionFactory sessionFactory;
private static ThreadLocal<Session> sessions = new ThreadLocal<Session>();
static {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
public static Session getSession() {
if (sessions.get() != null) {
}
sessions.set(sessionFactory.openSession());
return sessions.get();
}
public static void closeCurrentSession() {
sessions.get().close();
sessions.set(null);
}
public static Session currentSession() {
return sessions.get();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
} | Java |
package br.com.teckstoq.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import br.com.teckstoq.models.Comodatario;
public class HibernateUtilP {
private static SessionFactory factory;
public static Configuration getInitializedConfiguration() {
AnnotationConfiguration config = new AnnotationConfiguration();
/* add all of your JPA annotated classes here!!! */
config.addAnnotatedClass(Comodatario.class);
config.configure();
return config;
}
public static Session getSession() {
if (factory == null) {
Configuration config = HibernateUtilP.getInitializedConfiguration();
factory = config.buildSessionFactory();
}
Session hibernateSession = factory.getCurrentSession();
return hibernateSession;
}
public static void closeSession() {
HibernateUtilP.getSession().close();
}
public static void recreateDatabase() {
Configuration config;
config = HibernateUtilP.getInitializedConfiguration();
new SchemaExport(config).create(true, true);
}
public static Session beginTransaction() {
Session hibernateSession;
hibernateSession = HibernateUtil.getSession();
hibernateSession.beginTransaction();
return hibernateSession;
}
public static void commitTransaction() {
HibernateUtilP.getSession().getTransaction().commit();
}
public static void rollbackTransaction() {
HibernateUtilP.getSession().getTransaction().rollback();
}
public static void main(String args[]) {
HibernateUtilP.recreateDatabase();
}
}
| Java |
package br.com.teckstoq.repositorio;
import java.sql.SQLException;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import br.com.teckstoq.dao.Dao;
import br.com.teckstoq.hibernate.HibernateUtil;
import br.com.teckstoq.irepositorio.IRepositorioLogHistorico;
import br.com.teckstoq.models.LogHistorico;
public class RepositorioLogHistorico implements IRepositorioLogHistorico {
private Dao dao = Dao.getInstance();
private Session sessao;
private Transaction tx;
//-------------------------------------------------------------------
public void inserirLogHistorico(LogHistorico logHistorico)
throws SQLException {
dao.save(logHistorico);
}
//--------------------------------------------------------------------
public void atualizarLogHistorico(LogHistorico logHistorico)
throws SQLException {
dao.update(logHistorico);
}
//--------------------------------------------------------------------
public void removerLogHistorico(LogHistorico logHistorico)
throws SQLException {
dao.delete(logHistorico);
}
//--------------------------------------------------------------------
@SuppressWarnings("unchecked")
public ArrayList<LogHistorico> listarLogHistorico() throws SQLException {
return (ArrayList<LogHistorico>) dao.list(LogHistorico.class);
}
//---------------------------------------------------------------------
public LogHistorico retornaLogHistorico(long chave) throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
Query selecao = sessao.createQuery("FROM LogHistorico WHERE idLogHistorico =:chave");
selecao.setLong("chave", chave);
LogHistorico logHistorico = (LogHistorico) selecao.uniqueResult();
sessao.close();
return logHistorico;
}
//----------------------------------------------------------------------
}
| Java |
package br.com.teckstoq.repositorio;
import java.sql.SQLException;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import br.com.teckstoq.dao.Dao;
import br.com.teckstoq.hibernate.HibernateUtil;
import br.com.teckstoq.irepositorio.IRepositorioEquipamento;
import br.com.teckstoq.models.Equipamento;
import br.com.teckstoq.models.Fornecedor;
public class RepositorioEquipamento implements IRepositorioEquipamento {
private Dao dao = Dao.getInstance();
private Session sessao;
private Transaction tx;
//-------------------------------------------------------------------
public void inserirEquipamento(Equipamento equipamento) throws SQLException {
dao.save(equipamento);
}
//-------------------------------------------------------------------
public void atualizarEquipamento(Equipamento equipamento) throws SQLException {
dao.update(equipamento);
}
//-------------------------------------------------------------------
public void removerEquipamento(Equipamento equipamento) throws SQLException {
dao.delete(equipamento);
}
//-------------------------------------------------------------------
@SuppressWarnings("unchecked")
public ArrayList<Equipamento> listarEquipamento() throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
ArrayList<Equipamento> equipamentos = new ArrayList<Equipamento>();
Query selecao = sessao.createQuery("FROM Equipamento WHERE status='ATIVO'");
equipamentos = (ArrayList<Equipamento>) selecao.list();
sessao.close();
return equipamentos;
}
//-------------------------------------------------------------------
public Equipamento retornaEquipamento(long chave) throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
Query selecao = sessao.createQuery("FROM Equipamento WHERE idMaquina =:chave AND status='ATIVO'");
selecao.setLong("chave", chave);
Equipamento equipamento = (Equipamento) selecao.uniqueResult();
sessao.close();
return equipamento;
}
//-------------------------------------------------------------------
@SuppressWarnings("unchecked")
public ArrayList<Equipamento> buscarEquipamento(String chave, String tipo)
throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
ArrayList<Equipamento> equipamentos = new ArrayList<Equipamento>();
if (tipo.equals("CODIGO")){
Query selecao = sessao.createQuery("FROM Equipamento WHERE codigoFabrica like :chave AND status='ATIVO'");
selecao.setString("chave", chave+"%");
equipamentos = (ArrayList<Equipamento>) selecao.list();
sessao.close();
}
else if(tipo.equals("NOME")){
Query selecao = sessao.createQuery("FROM Equipamento WHERE nomeMaquina like :chave AND status='ATIVO'");
selecao.setString("chave", chave+"%");
equipamentos = (ArrayList<Equipamento>) selecao.list();
sessao.close();
}
else{
//-------------------------------------------------------------------------------
Fornecedor fornecedor = new Fornecedor();
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
Query selecao = sessao.createQuery("FROM Fornecedor WHERE nome like :chave AND status='ATIVO'");
selecao.setString("chave", chave+"%");
fornecedor = (Fornecedor) selecao.uniqueResult();
if (!(fornecedor == null)){
long idFornecedor = fornecedor.getIdFornecedor();
Query selecao2 = sessao.createQuery("FROM Equipamento WHERE fornecedor =:chave2 AND status='ATIVO'");
selecao2.setLong("chave2", idFornecedor);
equipamentos = (ArrayList<Equipamento>) selecao2.list();
sessao.close();
}
//-------------------------------------------------------------------------------
}
return equipamentos;
}
//-------------------------------------------------------------------
}
| Java |
package br.com.teckstoq.repositorio;
import java.sql.SQLException;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import br.com.teckstoq.dao.Dao;
import br.com.teckstoq.hibernate.HibernateUtil;
import br.com.teckstoq.irepositorio.IRepositorioEntradaEstoque;
import br.com.teckstoq.models.EntradaEstoque;
public class RepositorioEntradaEstoque implements IRepositorioEntradaEstoque {
private Dao dao = Dao.getInstance();
private Session sessao;
private Transaction tx;
//-------------------------------------------------------------------
public void inserirEntradaEstoque(EntradaEstoque entradaEstoque)
throws SQLException {
dao.save(entradaEstoque);
}
//-------------------------------------------------------------------
public void atualizarEntradaEstoque(EntradaEstoque entradaEstoque)
throws SQLException {
dao.update(entradaEstoque);
}
//-------------------------------------------------------------------
public void removerEntradaEstoque(EntradaEstoque entradaEstoque)
throws SQLException {
dao.delete(entradaEstoque);
}
//-------------------------------------------------------------------
@SuppressWarnings("unchecked")
public ArrayList<EntradaEstoque> listarEntradaEstoque() throws SQLException {
return (ArrayList<EntradaEstoque>) dao.list(EntradaEstoque.class);
}
//-------------------------------------------------------------------
public EntradaEstoque retornaEntradaEstoque(long chave)
throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
Query selecao = sessao.createQuery("FROM EntradaEstoque WHERE idEntradaEstoque =:chave");
selecao.setLong("chave", chave);
EntradaEstoque entradaEstoque = (EntradaEstoque) selecao.uniqueResult();
sessao.close();
return entradaEstoque;
}
//-------------------------------------------------------------------
}
| Java |
package br.com.teckstoq.repositorio;
import java.sql.SQLException;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import br.com.teckstoq.dao.Dao;
import br.com.teckstoq.hibernate.HibernateUtil;
import br.com.teckstoq.irepositorio.IRepositorioFornecedor;
import br.com.teckstoq.models.Fornecedor;
import br.com.teckstoq.models.Funcionario;
@SuppressWarnings("unused")
public class RepositorioFornecedor implements IRepositorioFornecedor {
private Dao dao = Dao.getInstance();
private Session sessao;
private Transaction tx;
//-------------------------------------------------------------------------
public void inserirFornecedor(Fornecedor fornecedor) throws SQLException {
dao.save(fornecedor);
}
//-------------------------------------------------------------------------
public void atualizarFornecedor(Fornecedor fornecedor) throws SQLException {
dao.update(fornecedor);
}
//-------------------------------------------------------------------------
public void removerFornecedor(Fornecedor fornecedor) throws SQLException {
dao.delete(fornecedor);
}
//-------------------------------------------------------------------------
@SuppressWarnings("unchecked")
public ArrayList<Fornecedor> listarFornecedor() throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
ArrayList<Fornecedor> fornecedores = new ArrayList<Fornecedor>();
Query selecao = sessao.createQuery("FROM Fornecedor WHERE status='ATIVO'");
fornecedores = (ArrayList<Fornecedor>) selecao.list();
sessao.close();
return fornecedores;
}
//-------------------------------------------------------------------------
public Fornecedor retornaFornecedor(long chave) {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
Query selecao = sessao.createQuery("FROM Fornecedor WHERE idFornecedor =:chave");
selecao.setLong("chave", chave);
Fornecedor fornecedor = (Fornecedor) selecao.uniqueResult();
sessao.close();
return fornecedor;
}
//-------------------------------------------------------------------------
@SuppressWarnings("unchecked")
public ArrayList<Fornecedor> buscarFornecedor(String chave, String tipo)
throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
ArrayList<Fornecedor> fornecedores = new ArrayList<Fornecedor>();
if (tipo.equals("CODIGO")){
Query selecao = sessao.createQuery("FROM Fornecedor WHERE idFornecedor like :chave AND status='ATIVO'");
selecao.setString("chave", chave+"%");
fornecedores = (ArrayList<Fornecedor>) selecao.list();
sessao.close();
}
else if(tipo.equals("NOME")){
Query selecao = sessao.createQuery("FROM Fornecedor WHERE nome like :chave AND status='ATIVO'");
selecao.setString("chave", chave+"%");
fornecedores = (ArrayList<Fornecedor>) selecao.list();
sessao.close();
}
else if(tipo.equals("CNPJ")){
Query selecao = sessao.createQuery("FROM Fornecedor WHERE cnpj like :chave AND status='ATIVO'");
selecao.setString("chave", chave+"%");
fornecedores = (ArrayList<Fornecedor>) selecao.list();
sessao.close();
}
else{
Query selecao = sessao.createQuery("FROM Fornecedor WHERE inscricaoEstadual like :chave AND status='ATIVO'");
selecao.setString("chave", chave+"%");
fornecedores = (ArrayList<Fornecedor>) selecao.list();
sessao.close();
}
return fornecedores;
}
//-------------------------------------------------------------------------
}
| Java |
package br.com.teckstoq.repositorio;
import java.sql.SQLException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import br.com.teckstoq.dao.Dao;
import br.com.teckstoq.hibernate.HibernateUtil;
import br.com.teckstoq.irepositorio.IRepositorioAcesso;
import br.com.teckstoq.models.ValidarAcesso;
public class RepositorioAcesso implements IRepositorioAcesso {
private Dao dao = Dao.getInstance();
private Session sessao;
private Transaction tx;
// ----------------------------------------------------------
public void inserirAcesso(ValidarAcesso acesso) throws SQLException {
dao.save(acesso);
}
// ----------------------------------------------------------
public void atualizarAcesso(ValidarAcesso acesso) throws SQLException {
dao.update(acesso);
}
// ----------------------------------------------------------
public ValidarAcesso retornaAcesso(long chave) throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
Query selecao = sessao.createQuery("FROM ValidarAcesso WHERE idAcesso =:chave");
selecao.setLong("chave", chave);
ValidarAcesso acesso = (ValidarAcesso) selecao.uniqueResult();
sessao.close();
return acesso;
}
}
| Java |
package br.com.teckstoq.repositorio;
import java.sql.SQLException;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import br.com.teckstoq.dao.Dao;
import br.com.teckstoq.hibernate.HibernateUtil;
import br.com.teckstoq.irepositorio.IRepositorioEstoque;
import br.com.teckstoq.models.Estoque;
import br.com.teckstoq.models.Peca;
public class RepositorioEstoque implements IRepositorioEstoque {
private Dao dao = Dao.getInstance();
private Session sessao;
private Transaction tx;
//----------------------------------------------------------------
public void inserirEstoque(Estoque estoque) throws SQLException {
dao.save(estoque);
}
//----------------------------------------------------------------
public void atualizarEstoque(Estoque estoque) throws SQLException {
dao.update(estoque);
}
//----------------------------------------------------------------
public void removerEstoque(Estoque estoque) throws SQLException {
dao.delete(estoque);
}
//----------------------------------------------------------------
@SuppressWarnings("unchecked")
public ArrayList<Estoque> listarEstoque() throws SQLException {
return (ArrayList<Estoque>) dao.list(Estoque.class);
}
//----------------------------------------------------------------
public Estoque retornaEstoquePorProduto(long chave) throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
Query selecao = sessao.createQuery("FROM Estoque WHERE idEstoque =:chave");
selecao.setLong("chave", chave);
Estoque estoque = (Estoque) selecao.uniqueResult();
sessao.close();
return estoque;
}
//---------------------------------------------------------------
@SuppressWarnings("unchecked")
public ArrayList<Estoque> buscarQuantidadeMinima() throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
ArrayList<Estoque> estoque = new ArrayList<Estoque>();
Query selecao = sessao
.createQuery("FROM Estoque WHERE quantidade <= quantidadeMinima");
estoque = (ArrayList<Estoque>) selecao.list();
sessao.close();
return estoque;
}
//---------------------------------------------------------------
}
| Java |
package br.com.teckstoq.repositorio;
import java.sql.SQLException;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import br.com.teckstoq.dao.Dao;
import br.com.teckstoq.hibernate.HibernateUtil;
import br.com.teckstoq.irepositorio.IRepositorioSaidaEmprestimo;
import br.com.teckstoq.models.Fornecedor;
import br.com.teckstoq.models.Peca;
import br.com.teckstoq.models.SaidaEmprestimo;
public class RepositorioSaidaEmprestimo implements IRepositorioSaidaEmprestimo {
private Dao dao = Dao.getInstance();
private Session sessao;
private Transaction tx;
//---------------------------------------------------------------------
public void inserirSaidaEmprestimo(SaidaEmprestimo saidaEmprestimo)
throws SQLException {
dao.save(saidaEmprestimo);
}
//----------------------------------------------------------------------
public void atualizarSaidaEmprestimo(SaidaEmprestimo saidaEmprestimo)
throws SQLException {
dao.update(saidaEmprestimo);
}
//----------------------------------------------------------------------
public void removerSaidaEmprestimo(SaidaEmprestimo saidaEmprestimo)
throws SQLException {
dao.delete(saidaEmprestimo);
}
//----------------------------------------------------------------------
@SuppressWarnings("unchecked")
public ArrayList<SaidaEmprestimo> listarSaidaEmprestimo()
throws SQLException {
return (ArrayList<SaidaEmprestimo>) dao.list(SaidaEmprestimo.class);
}
//----------------------------------------------------------------------
public SaidaEmprestimo retornaSaidaEmprestimo(long chave)
throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
Query selecao = sessao.createQuery("FROM SaidaEmprestimo WHERE idSaidaEmprestimo =:chave");
selecao.setLong("chave", chave);
SaidaEmprestimo saidaEmprestimo = (SaidaEmprestimo) selecao.uniqueResult();
sessao.close();
return saidaEmprestimo;
}
//----------------------------------------------------------------------
public ArrayList<SaidaEmprestimo> buscarSaidaEmprestimos(String chave, String tipo)
throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
ArrayList<SaidaEmprestimo> saidaEmprestimos = new ArrayList<SaidaEmprestimo>();
Query selecao = sessao.createQuery("FROM SaidaEmprestimo WHERE idSaidaEmprestimo like :chave AND WHERE Status='ATIVO'");
selecao.setString("chave", chave+"%");
saidaEmprestimos = (ArrayList<SaidaEmprestimo>) selecao.list();
sessao.close();
return saidaEmprestimos;
}
//----------------------------------------------------------------------
@SuppressWarnings("unchecked")
public ArrayList<SaidaEmprestimo> buscarSaidaEmprestimosData()
throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
ArrayList<SaidaEmprestimo> saidaEmprestimos = new ArrayList<SaidaEmprestimo>();
Query selecao = sessao.createQuery("FROM SaidaEmprestimo WHERE status='ativo'");
saidaEmprestimos = (ArrayList<SaidaEmprestimo>) selecao.list();
sessao.close();
return saidaEmprestimos;
}
//----------------------------------------------------------------------
}
| Java |
package br.com.teckstoq.repositorio;
import java.sql.SQLException;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import br.com.teckstoq.dao.Dao;
import br.com.teckstoq.hibernate.HibernateUtil;
import br.com.teckstoq.irepositorio.IRepositorioEntradaEmprestimo;
import br.com.teckstoq.models.EntradaEmprestimo;
public class RepositorioEntradaEmprestimo implements IRepositorioEntradaEmprestimo {
private Dao dao = Dao.getInstance();
private Session sessao;
private Transaction tx;
//--------------------------------------------------------------------------
public void inserirEntradaEmprestimo(EntradaEmprestimo entradaEmprestimo)
throws SQLException {
dao.save(entradaEmprestimo);
}
//--------------------------------------------------------------------------
public void atualizarEntradaEmprestimo(EntradaEmprestimo entradaEmprestimo)
throws SQLException {
dao.update(entradaEmprestimo);
}
//--------------------------------------------------------------------------
public void removerEntradaEmprestimo(EntradaEmprestimo entradaEmprestimo)
throws SQLException {
dao.delete(entradaEmprestimo);
}
//--------------------------------------------------------------------------
@SuppressWarnings("unchecked")
public ArrayList<EntradaEmprestimo> listarEntradaEmprestimo()
throws SQLException {
return (ArrayList<EntradaEmprestimo>) dao.list(EntradaEmprestimo.class);
}
//--------------------------------------------------------------------------
public EntradaEmprestimo retornaEntradaEmprestimo(long chave)
throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
Query selecao = sessao.createQuery("FROM EntradaEmprestimo WHERE idEntradaEmprestim =:chave");
selecao.setLong("chave", chave);
EntradaEmprestimo entradaEmprestimo = (EntradaEmprestimo) selecao.uniqueResult();
sessao.close();
return entradaEmprestimo;
}
//---------------------------------------------------------------------------
}
| Java |
package br.com.teckstoq.repositorio;
import java.sql.SQLException;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import br.com.teckstoq.dao.Dao;
import br.com.teckstoq.hibernate.HibernateUtil;
import br.com.teckstoq.irepositorio.IRepositorioComodatario;
import br.com.teckstoq.models.Comodatario;
import br.com.teckstoq.models.Setor;
public class RepositorioComodatario implements IRepositorioComodatario {
private Dao dao = Dao.getInstance();
private Session sessao;
private Transaction tx;
//---------------------------------------------------------------------------
public void inserirComodatario(Comodatario comodatario) throws SQLException {
dao.save(comodatario);
}
//---------------------------------------------------------------------------
public void atualizarComodatario(Comodatario comodatario)
throws SQLException {
dao.update(comodatario);
}
//---------------------------------------------------------------------------
public void removerComodatario(Comodatario comodatario) throws SQLException {
dao.delete(comodatario);
}
//---------------------------------------------------------------------------
@SuppressWarnings("unchecked")
public ArrayList<Comodatario> listarComodatario() throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
ArrayList<Comodatario> comodatarios = new ArrayList<Comodatario>();
Query selecao = sessao.createQuery("FROM Comodatario WHERE status='ATIVO'");
comodatarios = (ArrayList<Comodatario>) selecao.list();
sessao.close();
return comodatarios;
}
//---------------------------------------------------------------------------
public Comodatario retornaComodatario(long chave) throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
Query selecao = sessao.createQuery("FROM Comodatario WHERE idComodatario =:chave");
selecao.setLong("chave", chave);
Comodatario comodatario = (Comodatario) selecao.uniqueResult();
sessao.close();
return comodatario;
}
//--------------------------------------------------------------------------------------------------
@SuppressWarnings("unchecked")
public ArrayList<Comodatario> buscarComodatarios(String chave, String tipo)
throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
ArrayList<Comodatario> comodatarios = new ArrayList<Comodatario>();
if (tipo.equals("CODIGO")){
Query selecao = sessao.createQuery("FROM Comodatario WHERE idComodatario like :chave AND status='ATIVO'");
selecao.setString("chave", chave+"%");
comodatarios = (ArrayList<Comodatario>) selecao.list();
sessao.close();
}
else{
Query selecao = sessao.createQuery("FROM Comodatario WHERE nomeComodatario like :chave AND status='ATIVO'");
selecao.setString("chave", chave+"%");
comodatarios = (ArrayList<Comodatario>) selecao.list();
sessao.close();
}
return comodatarios;
}
//-------------------------------------------------------------------------------
}
| Java |
package br.com.teckstoq.repositorio;
import java.sql.SQLException;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import br.com.teckstoq.dao.Dao;
import br.com.teckstoq.hibernate.HibernateUtil;
import br.com.teckstoq.irepositorio.IRepositorioSaidaEstoque;
import br.com.teckstoq.models.SaidaEstoque;
public class RepositorioSaidaEstoque implements IRepositorioSaidaEstoque {
private Dao dao = Dao.getInstance();
private Session sessao;
private Transaction tx;
//---------------------------------------------------------
public void inserirSaidaEstoque(SaidaEstoque saidaEstoque)
throws SQLException {
dao.save(saidaEstoque);
}
//---------------------------------------------------------
public void atualizarSaidaEstoque(SaidaEstoque saidaEstoque)
throws SQLException {
dao.update(saidaEstoque);
}
//---------------------------------------------------------
public void removerSaidaEstoque(SaidaEstoque saidaEstoque)
throws SQLException {
dao.delete(saidaEstoque);
}
//---------------------------------------------------------
@SuppressWarnings("unchecked")
public ArrayList<SaidaEstoque> listarSaidaEstoque() throws SQLException {
return (ArrayList<SaidaEstoque>) dao.list(SaidaEstoque.class);
}
//---------------------------------------------------------
public SaidaEstoque retornaSaidaEstoque(long chave) throws SQLException {
sessao = HibernateUtil.getSession();
tx = sessao.beginTransaction();
Query selecao = sessao.createQuery("FROM SaidaEstoque WHERE idSaidaEstoque =:chave");
selecao.setLong("chave", chave);
SaidaEstoque saidaEstoque = (SaidaEstoque) selecao.uniqueResult();
sessao.close();
return saidaEstoque;
}
//---------------------------------------------------------
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.