Improve code / xml formatting, closes #54

This commit is contained in:
Emux
2016-07-09 19:45:22 +03:00
parent 7919d0ab9c
commit e793e8851b
458 changed files with 58405 additions and 63062 deletions

View File

@@ -1,33 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.5.1//EN" "http://google-web-toolkit.googlecode.com/svn/tags/2.5.1/distro-source/core/src/gwt-module.dtd">
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE module PUBLIC
"-//Google Inc.//DTD Google Web Toolkit 2.5.1//EN"
"http://google-web-toolkit.googlecode.com/svn/tags/2.5.1/distro-source/core/src/gwt-module.dtd">
<module rename-to='com.badlogic.gdx.backends.gwt'>
<inherits name='com.google.gwt.user.User' />
<!-- Inherit edited chrome theme ("gwt"-prefixed classes only) for a little bit of default styling in the text input dialogs -->
<inherits name='com.badlogic.gdx.backends.gwt.theme.chrome.Chrome'/>
<inherits name="com.google.gwt.http.HTTP"/>
<inherits name="com.badlogic.gdx" />
<inherits name="com.google.gwt.webgl.WebGL" />
<inherits name="com.badlogic.gwtref.GwtReflect"/>
<inherits name='com.google.gwt.user.User' />
<!-- Inherit edited chrome theme ("gwt"-prefixed classes only) for a little bit of default styling in the text input dialogs -->
<inherits name='com.badlogic.gdx.backends.gwt.theme.chrome.Chrome' />
<inherits name="com.google.gwt.http.HTTP" />
<!-- <script src="soundmanager2-setup.js"/>
<script src="soundmanager2-jsmin.js"/> -->
<!-- <public path="gwt/resources"/> -->
<super-source path="gwt/emu" />
<source path="gwt">
<inherits name="com.badlogic.gdx" />
<inherits name="com.google.gwt.webgl.WebGL" />
<inherits name="com.badlogic.gwtref.GwtReflect" />
<!-- <script src="soundmanager2-setup.js"/>
<script src="soundmanager2-jsmin.js"/> -->
<!-- <public path="gwt/resources"/> -->
<super-source path="gwt/emu" />
<source path="gwt">
<exclude name="**/emu/**" />
<exclude name="**/theme/**" />
<exclude name="**/PreloaderBundleGenerator.java"/>
<exclude name="**/FileWrapper.java"/>
<exclude name="**/theme/**" />
<exclude name="**/PreloaderBundleGenerator.java" />
<exclude name="**/FileWrapper.java" />
<exclude name="**/emu/**" />
</source>
<define-configuration-property name="gdx.assetpath" is-multi-valued="false"/>
<define-configuration-property name="gdx.assetfilterclass" is-multi-valued="false"/>
<define-configuration-property name="gdx.assetoutputpath" is-multi-valued="false"/>
<generate-with class="com.badlogic.gdx.backends.gwt.preloader.PreloaderBundleGenerator">
<when-type-assignable class="com.badlogic.gdx.backends.gwt.preloader.PreloaderBundle"/>
</generate-with>
</source>
<define-configuration-property name="gdx.assetpath" is-multi-valued="false" />
<define-configuration-property name="gdx.assetfilterclass" is-multi-valued="false" />
<define-configuration-property name="gdx.assetoutputpath" is-multi-valued="false" />
<generate-with class="com.badlogic.gdx.backends.gwt.preloader.PreloaderBundleGenerator">
<when-type-assignable class="com.badlogic.gdx.backends.gwt.preloader.PreloaderBundle" />
</generate-with>
</module>

View File

@@ -1,75 +1,75 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<module>
<!-- <entry-point class="org.oscim.gdx.client.GwtLauncher" /> -->
<!-- <entry-point class="org.oscim.gdx.client.GwtLauncher" /> -->
<inherits name="com.google.gwt.xml.XML" />
<inherits name="ru.finam.slf4jgwt.logging.gwt.Logging" />
<inherits name="com.google.gwt.xml.XML" />
<inherits name="ru.finam.slf4jgwt.logging.gwt.Logging" />
<!-- <set-property name='gwt.logging.enabled' value='TRUE' />
<set-property name='gwt.logging.consoleHandler' value='ENABLED' />
<set-property name='gwt.logging.firebugHandler' value='DISABLED' />
<set-property name='gwt.logging.popupHandler' value='DISABLED' />
<set-property name="gwt.logging.logLevel" value="FINE"/>
-->
<inherits name="VtmGdx" />
<!-- <inherits name="com.badlogic.gdx.backends.gdx_backends_gwt" /> -->
<inherits name="com.badlogic.gdx.backends.Gdx" />
<inherits name="com.google.gwt.user.theme.chrome.Chrome" />
<!-- <set-property name='gwt.logging.enabled' value='TRUE' />
<set-property name='gwt.logging.consoleHandler' value='ENABLED' />
<set-property name='gwt.logging.firebugHandler' value='DISABLED' />
<set-property name='gwt.logging.popupHandler' value='DISABLED' />
<set-property name="gwt.logging.logLevel" value="FINE"/>
-->
<inherits name="VtmGdx" />
<!-- <inherits name="com.badlogic.gdx.backends.gdx_backends_gwt" /> -->
<inherits name="com.badlogic.gdx.backends.Gdx" />
<inherits name="com.google.gwt.user.theme.chrome.Chrome" />
<!-- <extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.scenes.scene2d" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.math" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.graphics.g2d.TextureRegion" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.graphics.g2d.BitmapFont" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.graphics.g2d.NinePatch" />
<extend-configuration-property name="gdx.reflect.include"
value="com.badlogic.gdx.graphics.g3d.materials.MaterialAttribute" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.graphics.Color" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.graphics.Texture" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.utils.Array" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.utils.ObjectMap" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.utils.OrderedMap" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.utils.Disposable" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.graphics.VertexAttribute" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.graphics.g3d.model" />
-->
<clear-configuration-property name="gdx.reflect.include" />
<extend-configuration-property name="gdx.reflect.include" value="java.util.List" />
<extend-configuration-property name="gdx.reflect.include" value="java.util.ArrayList" />
<extend-configuration-property name="gdx.reflect.include" value="java.util.Map" />
<extend-configuration-property name="gdx.reflect.include" value="java.util.HashMap" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.String" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Boolean" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Byte" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Short" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Character" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Integer" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Float" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Double" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.CharSequence" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Enum" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Object" />
<!-- super dev mode -->
<!--
<add-linker name="xsiframe"/>
<set-configuration-property name='xsiframe.failIfScriptTag' value='FALSE'/>
<set-configuration-property name="devModeRedirectEnabled" value="true"/>
-->
<!-- <extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.scenes.scene2d" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.math" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.graphics.g2d.TextureRegion" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.graphics.g2d.BitmapFont" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.graphics.g2d.NinePatch" />
<extend-configuration-property name="gdx.reflect.include"
value="com.badlogic.gdx.graphics.g3d.materials.MaterialAttribute" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.graphics.Color" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.graphics.Texture" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.utils.Array" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.utils.ObjectMap" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.utils.OrderedMap" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.utils.Disposable" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.graphics.VertexAttribute" />
<extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.graphics.g3d.model" />
-->
<clear-configuration-property name="gdx.reflect.include" />
<extend-configuration-property name="gdx.reflect.include" value="java.util.List" />
<extend-configuration-property name="gdx.reflect.include" value="java.util.ArrayList" />
<extend-configuration-property name="gdx.reflect.include" value="java.util.Map" />
<extend-configuration-property name="gdx.reflect.include" value="java.util.HashMap" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.String" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Boolean" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Byte" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Short" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Character" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Integer" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Float" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Double" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.CharSequence" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Enum" />
<extend-configuration-property name="gdx.reflect.include" value="java.lang.Object" />
<!-- does not work with super dev mode, include directly in page -->
<!--
<script src="_tessellate.js"/>
<script src="tessellate.js"/>
-->
<!-- super dev mode -->
<!--
<add-linker name="xsiframe"/>
<set-configuration-property name='xsiframe.failIfScriptTag' value='FALSE'/>
<set-configuration-property name="devModeRedirectEnabled" value="true"/>
-->
<public path="resources" />
<!-- does not work with super dev mode, include directly in page -->
<!--
<script src="_tessellate.js"/>
<script src="tessellate.js"/>
-->
<super-source path="emu" />
<public path="resources" />
<!-- <set-configuration-property name="gdx.assetpath" value="./assets" /> -->
<!-- for gradle build, commend out for eclipse build/devmode -->
<!-- <set-configuration-property name="gdx.assetoutputpath" value="build/gwt/draftOut" /> -->
<!-- <set-property name="user.agent" value="safari"/> -->
<super-source path="emu" />
<!-- <set-configuration-property name="gdx.assetpath" value="./assets" /> -->
<!-- for gradle build, commend out for eclipse build/devmode -->
<!-- <set-configuration-property name="gdx.assetoutputpath" value="build/gwt/draftOut" /> -->
<!-- <set-property name="user.agent" value="safari"/> -->
</module>

File diff suppressed because it is too large Load Diff

View File

@@ -16,9 +16,6 @@
*/
package org.oscim.gdx.client;
import org.oscim.backend.GL;
import org.oscim.backend.canvas.Bitmap;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap;
@@ -26,75 +23,80 @@ import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.RootPanel;
import org.oscim.backend.GL;
import org.oscim.backend.canvas.Bitmap;
public class GwtBitmap implements Bitmap {
Pixmap pixmap;
Image image;
boolean disposable;
Pixmap pixmap;
Image image;
boolean disposable;
public GwtBitmap(Image data) {
ImageElement imageElement = ImageElement.as(data.getElement());
pixmap = new Pixmap(imageElement);
image = data;
}
public GwtBitmap(Image data) {
ImageElement imageElement = ImageElement.as(data.getElement());
pixmap = new Pixmap(imageElement);
image = data;
}
/** always argb8888 */
public GwtBitmap(int width, int height, int format) {
pixmap = new Pixmap(width, height, null);
}
/**
* always argb8888
*/
public GwtBitmap(int width, int height, int format) {
pixmap = new Pixmap(width, height, null);
}
public GwtBitmap(String fileName) {
FileHandle handle = Gdx.files.internal(fileName);
pixmap = new Pixmap(handle);
disposable = true;
}
public GwtBitmap(String fileName) {
FileHandle handle = Gdx.files.internal(fileName);
pixmap = new Pixmap(handle);
disposable = true;
}
@Override
public int getWidth() {
return pixmap.getWidth();
}
@Override
public int getWidth() {
return pixmap.getWidth();
}
@Override
public int getHeight() {
return pixmap.getHeight();
}
@Override
public int getHeight() {
return pixmap.getHeight();
}
@Override
public void recycle() {
// FIXME this should be called at some point in time
pixmap.dispose();
@Override
public void recycle() {
// FIXME this should be called at some point in time
pixmap.dispose();
if (image != null)
RootPanel.get().remove(image);
}
if (image != null)
RootPanel.get().remove(image);
}
@Override
public int[] getPixels() {
return null;
}
@Override
public int[] getPixels() {
return null;
}
@Override
public void eraseColor(int color) {
}
@Override
public void eraseColor(int color) {
}
@Override
public void uploadToTexture(boolean replace) {
@Override
public void uploadToTexture(boolean replace) {
Gdx.gl.glTexImage2D(GL.TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(),
pixmap.getHeight(), 0,
pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels());
Gdx.gl.glTexImage2D(GL.TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(),
pixmap.getHeight(), 0,
pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels());
if (disposable || image != null) {
//log.debug("dispose pixmap " + getWidth() + "/" + getHeight());
pixmap.dispose();
if (disposable || image != null) {
//log.debug("dispose pixmap " + getWidth() + "/" + getHeight());
pixmap.dispose();
if (image != null)
RootPanel.get().remove(image);
}
}
if (image != null)
RootPanel.get().remove(image);
}
}
@Override
public boolean isValid() {
return true;
}
@Override
public boolean isValid() {
return true;
}
}

View File

@@ -16,54 +16,54 @@
*/
package org.oscim.gdx.client;
import org.oscim.backend.canvas.Bitmap;
import org.oscim.backend.canvas.Paint;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.canvas.dom.client.Context2d.LineJoin;
import org.oscim.backend.canvas.Bitmap;
import org.oscim.backend.canvas.Paint;
public class GwtCanvas implements org.oscim.backend.canvas.Canvas {
GwtBitmap bitmap;
GwtBitmap bitmap;
public GwtCanvas() {
// canvas comes with gdx pixmap
}
public GwtCanvas() {
// canvas comes with gdx pixmap
}
@Override
public void setBitmap(Bitmap bitmap) {
this.bitmap = (GwtBitmap) bitmap;
Context2d ctx = this.bitmap.pixmap.getContext();
@Override
public void setBitmap(Bitmap bitmap) {
this.bitmap = (GwtBitmap) bitmap;
Context2d ctx = this.bitmap.pixmap.getContext();
ctx.clearRect(0, 0, this.bitmap.getWidth(), this.bitmap.getHeight());
ctx.setLineJoin(LineJoin.BEVEL);
}
ctx.clearRect(0, 0, this.bitmap.getWidth(), this.bitmap.getHeight());
ctx.setLineJoin(LineJoin.BEVEL);
}
@Override
public void drawText(String string, float x, float y, Paint fill, Paint stroke) {
if (bitmap == null) {
//log.debug("no bitmap set");
return;
}
@Override
public void drawText(String string, float x, float y, Paint fill, Paint stroke) {
if (bitmap == null) {
//log.debug("no bitmap set");
return;
}
GwtPaint p = (GwtPaint) fill;
GwtPaint p = (GwtPaint) fill;
if (p.stroke && GwtGdxGraphics.NO_STROKE_TEXT)
return;
if (p.stroke && GwtGdxGraphics.NO_STROKE_TEXT)
return;
Context2d ctx = bitmap.pixmap.getContext();
ctx.setFont(p.font);
Context2d ctx = bitmap.pixmap.getContext();
ctx.setFont(p.font);
if (p.stroke) {
ctx.setLineWidth(p.strokeWidth);
ctx.setStrokeStyle(p.color);
ctx.strokeText(string, (int) (x + 1), (int) (y + 1));
} else {
ctx.setFillStyle(p.color);
ctx.fillText(string, (int) (x + 1), (int) (y + 1));
}
}
if (p.stroke) {
ctx.setLineWidth(p.strokeWidth);
ctx.setStrokeStyle(p.color);
ctx.strokeText(string, (int) (x + 1), (int) (y + 1));
} else {
ctx.setFillStyle(p.color);
ctx.fillText(string, (int) (x + 1), (int) (y + 1));
}
}
@Override
public void drawBitmap(Bitmap bitmap, float x, float y) {
}
@Override
public void drawBitmap(Bitmap bitmap, float x, float y) {
}
}

View File

@@ -16,62 +16,62 @@
*/
package org.oscim.gdx.client;
import java.io.InputStream;
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.canvas.dom.client.TextMetrics;
import org.oscim.backend.CanvasAdapter;
import org.oscim.backend.canvas.Bitmap;
import org.oscim.backend.canvas.Paint;
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.canvas.dom.client.TextMetrics;
import java.io.InputStream;
public class GwtGdxGraphics extends CanvasAdapter {
public static boolean NO_STROKE_TEXT = false;
public static boolean NO_STROKE_TEXT = false;
static final Context2d ctx;
static final Context2d ctx;
static {
Canvas canvas = Canvas.createIfSupported();
canvas.setCoordinateSpaceWidth(1);
canvas.setCoordinateSpaceHeight(1);
ctx = canvas.getContext2d();
}
static {
Canvas canvas = Canvas.createIfSupported();
canvas.setCoordinateSpaceWidth(1);
canvas.setCoordinateSpaceHeight(1);
ctx = canvas.getContext2d();
}
public static synchronized float getTextWidth(String text, String font) {
ctx.setFont(font);
TextMetrics tm = ctx.measureText(text);
return (float) tm.getWidth();
}
public static synchronized float getTextWidth(String text, String font) {
ctx.setFont(font);
TextMetrics tm = ctx.measureText(text);
return (float) tm.getWidth();
}
@Override
public Bitmap decodeBitmapImpl(InputStream in) {
//ImageData data = new ImageData();
return null;
}
@Override
public Bitmap decodeBitmapImpl(InputStream in) {
//ImageData data = new ImageData();
return null;
}
@Override
public Bitmap loadBitmapAssetImpl(String fileName) {
return new GwtBitmap(fileName);
}
@Override
public Bitmap loadBitmapAssetImpl(String fileName) {
return new GwtBitmap(fileName);
}
@Override
public Paint newPaintImpl() {
return new GwtPaint();
}
@Override
public Paint newPaintImpl() {
return new GwtPaint();
}
@Override
public Bitmap newBitmapImpl(int width, int height, int format) {
return new GwtBitmap(width, height, format);
}
@Override
public Bitmap newBitmapImpl(int width, int height, int format) {
return new GwtBitmap(width, height, format);
}
@Override
public org.oscim.backend.canvas.Canvas newCanvasImpl() {
return new GwtCanvas();
}
@Override
public org.oscim.backend.canvas.Canvas newCanvasImpl() {
return new GwtCanvas();
}
public static void init() {
CanvasAdapter.init(new GwtGdxGraphics());
}
public static void init() {
CanvasAdapter.init(new GwtGdxGraphics());
}
}

View File

@@ -16,106 +16,106 @@
*/
package org.oscim.gdx.client;
import org.oscim.backend.canvas.Paint;
import com.badlogic.gdx.graphics.Pixmap;
import org.oscim.backend.canvas.Paint;
public class GwtPaint implements Paint {
String color;
boolean stroke;
String color;
boolean stroke;
float strokeWidth;
Align mAlign;
float strokeWidth;
Align mAlign;
float fontSize = 12;
float fontSize = 12;
private FontStyle fontStyle = FontStyle.NORMAL;
//private FontFamily fontFamily = FontFamily.DEFAULT;
private FontStyle fontStyle = FontStyle.NORMAL;
//private FontFamily fontFamily = FontFamily.DEFAULT;
//String font = "12px sans-serif";
String font = "13px Helvetica";
//String font = "12px sans-serif";
String font = "13px Helvetica";
//private int cap;
//private int cap;
@Override
public int getColor() {
return 0;
}
@Override
public int getColor() {
return 0;
}
@Override
public void setColor(int color) {
float a = ((color >>> 24) & 0xff) / 255f;
int r = (color >>> 16) & 0xff;
int g = (color >>> 8) & 0xff;
int b = (color & 0xff);
@Override
public void setColor(int color) {
float a = ((color >>> 24) & 0xff) / 255f;
int r = (color >>> 16) & 0xff;
int g = (color >>> 8) & 0xff;
int b = (color & 0xff);
this.color = Pixmap.make(r, g, b, a);
}
this.color = Pixmap.make(r, g, b, a);
}
@Override
public void setStrokeCap(Cap cap) {
stroke = true;
}
@Override
public void setStrokeCap(Cap cap) {
stroke = true;
}
@Override
public void setStrokeWidth(float width) {
stroke = true;
strokeWidth = width;
}
@Override
public void setStrokeWidth(float width) {
stroke = true;
strokeWidth = width;
}
@Override
public void setStyle(Style style) {
}
@Override
public void setStyle(Style style) {
}
@Override
public void setTextAlign(Align align) {
mAlign = align;
}
@Override
public void setTextAlign(Align align) {
mAlign = align;
}
@Override
public void setTextSize(float size) {
fontSize = size;
buildFont();
}
@Override
public void setTextSize(float size) {
fontSize = size;
buildFont();
}
@Override
public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) {
this.fontStyle = fontStyle;
//this.fontFamily = fontFamily;
buildFont();
}
@Override
public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) {
this.fontStyle = fontStyle;
//this.fontFamily = fontFamily;
buildFont();
}
@Override
public float measureText(String text) {
return GwtGdxGraphics.getTextWidth(text, font);
}
@Override
public float measureText(String text) {
return GwtGdxGraphics.getTextWidth(text, font);
}
// FIXME all estimates. no idea how to properly measure canvas text..
@Override
public float getFontHeight() {
return 2 + fontSize + strokeWidth * 2;
}
// FIXME all estimates. no idea how to properly measure canvas text..
@Override
public float getFontHeight() {
return 2 + fontSize + strokeWidth * 2;
}
@Override
public float getFontDescent() {
return 4 + strokeWidth;
}
@Override
public float getFontDescent() {
return 4 + strokeWidth;
}
void buildFont() {
StringBuilder sb = new StringBuilder();
void buildFont() {
StringBuilder sb = new StringBuilder();
if (this.fontStyle == FontStyle.BOLD)
sb.append("bold ");
else if (this.fontStyle == FontStyle.ITALIC)
sb.append("italic ");
if (this.fontStyle == FontStyle.BOLD)
sb.append("bold ");
else if (this.fontStyle == FontStyle.ITALIC)
sb.append("italic ");
sb.append(Math.round(this.fontSize));
sb.append("px ");
sb.append(Math.round(this.fontSize));
sb.append("px ");
sb.append("Helvetica");
sb.append("Helvetica");
this.font = sb.toString();
this.font = sb.toString();
}
}
}

View File

@@ -19,30 +19,30 @@ package org.oscim.gdx.client;
import com.google.gwt.core.client.JavaScriptObject;
public class MapConfig extends JavaScriptObject {
protected MapConfig() {
}
protected MapConfig() {
}
public static native MapConfig get()/*-{
return $wnd.mapconfig;
public static native MapConfig get()/*-{
return $wnd.mapconfig;
}-*/;
public final native double getLatitude() /*-{
return this.latitude || 0;
public final native double getLatitude() /*-{
return this.latitude || 0;
}-*/;
public final native double getLongitude() /*-{
public final native double getLongitude() /*-{
return this.longitude || 0;
}-*/;
public final native int getZoom() /*-{
public final native int getZoom() /*-{
return this.zoom || 2;
}-*/;
public final native String getTileSource() /*-{
public final native String getTileSource() /*-{
return this.tilesource;
}-*/;
public final native int getTileSize() /*-{
public final native int getTileSize() /*-{
return this.tileSize || 256;
}-*/;

View File

@@ -1,120 +1,120 @@
package org.oscim.gdx.client;
import java.util.HashMap;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import org.oscim.core.MapPosition;
import org.oscim.core.MercatorProjection;
import org.oscim.map.Map;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import java.util.HashMap;
public class MapUrl extends Timer {
private int curLon, curLat, curZoom, curTilt, curRot;
private MapPosition pos = new MapPosition();
private final Map mMap;
private String mParams = "";
private int curLon, curLat, curZoom, curTilt, curRot;
private MapPosition pos = new MapPosition();
private final Map mMap;
private String mParams = "";
public MapUrl(Map map) {
mMap = map;
}
public MapUrl(Map map) {
mMap = map;
}
public String getParam(String name) {
return params.get(name);
}
public String getParam(String name) {
return params.get(name);
}
public final HashMap<String, String> params = new HashMap<String, String>();
public final HashMap<String, String> params = new HashMap<String, String>();
public void parseUrl(MapPosition pos) {
public void parseUrl(MapPosition pos) {
//String addOpts = "";
if (Window.Location.getHash() == null)
return;
//String addOpts = "";
if (Window.Location.getHash() == null)
return;
String hash = Window.Location.getHash();
hash = hash.substring(1);
String[] urlParams = null;
urlParams = hash.split("&");
if (urlParams.length == 1)
urlParams = hash.split(",");
double lat = pos.getLatitude(), lon = pos.getLongitude();
float rotation = pos.bearing;
float tilt = pos.tilt;
String hash = Window.Location.getHash();
hash = hash.substring(1);
String[] urlParams = null;
urlParams = hash.split("&");
if (urlParams.length == 1)
urlParams = hash.split(",");
double lat = pos.getLatitude(), lon = pos.getLongitude();
float rotation = pos.bearing;
float tilt = pos.tilt;
//String themeName = "";
//String mapName = "";
//String themeName = "";
//String mapName = "";
int zoom = pos.zoomLevel;
int zoom = pos.zoomLevel;
for (String p : urlParams) {
try {
if (p.startsWith("lat="))
lat = Double.parseDouble(p.substring(4));
for (String p : urlParams) {
try {
if (p.startsWith("lat="))
lat = Double.parseDouble(p.substring(4));
else if (p.startsWith("lon="))
lon = Double.parseDouble(p.substring(4));
else if (p.startsWith("scale="))
zoom = Integer.parseInt(p.substring(6));
else if (p.startsWith("rot="))
rotation = Float.parseFloat(p.substring(4));
else if (p.startsWith("tilt="))
tilt = Float.parseFloat(p.substring(5));
// else if (p.startsWith("theme="))
// themeName = p.substring(6);
// else if (p.startsWith("map="))
// mapName = p.substring(4);
else {
String[] opt = p.split("=");
if (opt.length > 1)
params.put(opt[0], opt[1]);
else
params.put(opt[0], null);
else if (p.startsWith("lon="))
lon = Double.parseDouble(p.substring(4));
else if (p.startsWith("scale="))
zoom = Integer.parseInt(p.substring(6));
else if (p.startsWith("rot="))
rotation = Float.parseFloat(p.substring(4));
else if (p.startsWith("tilt="))
tilt = Float.parseFloat(p.substring(5));
// else if (p.startsWith("theme="))
// themeName = p.substring(6);
// else if (p.startsWith("map="))
// mapName = p.substring(4);
else {
String[] opt = p.split("=");
if (opt.length > 1)
params.put(opt[0], opt[1]);
else
params.put(opt[0], null);
mParams += p + "&";
mParams += p + "&";
}
} catch (NumberFormatException e) {
}
} catch (NumberFormatException e) {
}
}
pos.setPosition(lat, lon);
pos.setZoomLevel(zoom);
pos.set(MercatorProjection.longitudeToX(lon),
MercatorProjection.latitudeToY(lat),
1 << zoom,
rotation,
tilt);
}
}
pos.setPosition(lat, lon);
pos.setZoomLevel(zoom);
pos.set(MercatorProjection.longitudeToX(lon),
MercatorProjection.latitudeToY(lat),
1 << zoom,
rotation,
tilt);
}
}
@Override
public void run() {
mMap.viewport().getMapPosition(pos);
int lat = (int) (MercatorProjection.toLatitude(pos.y) * 1000);
int lon = (int) (MercatorProjection.toLongitude(pos.x) * 1000);
int rot = (int) (pos.bearing);
rot = (int) (pos.bearing) % 360;
//rot = rot < 0 ? -rot : rot;
@Override
public void run() {
mMap.viewport().getMapPosition(pos);
int lat = (int) (MercatorProjection.toLatitude(pos.y) * 1000);
int lon = (int) (MercatorProjection.toLongitude(pos.x) * 1000);
int rot = (int) (pos.bearing);
rot = (int) (pos.bearing) % 360;
//rot = rot < 0 ? -rot : rot;
if (curZoom != pos.zoomLevel || curLat != lat || curLon != lon
|| curTilt != rot || curRot != (int) (pos.bearing)) {
if (curZoom != pos.zoomLevel || curLat != lat || curLon != lon
|| curTilt != rot || curRot != (int) (pos.bearing)) {
curLat = lat;
curLon = lon;
curZoom = pos.zoomLevel;
curTilt = (int) pos.tilt;
curRot = rot;
curLat = lat;
curLon = lon;
curZoom = pos.zoomLevel;
curTilt = (int) pos.tilt;
curRot = rot;
String newURL = Window.Location
.createUrlBuilder()
.setHash(mParams
+ "scale=" + pos.zoomLevel
+ "&rot=" + curRot
+ "&tilt=" + curTilt
+ "&lat=" + (curLat / 1000f)
+ "&lon=" + (curLon / 1000f))
.buildString();
Window.Location.replace(newURL);
}
}
String newURL = Window.Location
.createUrlBuilder()
.setHash(mParams
+ "scale=" + pos.zoomLevel
+ "&rot=" + curRot
+ "&tilt=" + curTilt
+ "&lat=" + (curLat / 1000f)
+ "&lon=" + (curLon / 1000f))
.buildString();
Window.Location.replace(newURL);
}
}
}

View File

@@ -1,12 +1,12 @@
/*******************************************************************************
* Copyright 2011 See libgdx AUTHORS file.
*
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -16,9 +16,6 @@
package com.badlogic.gdx.backends.gwt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Audio;
@@ -44,290 +41,297 @@ import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Panel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of an {@link Application} based on GWT. Clients have to
* override {@link #getConfig()} and {@link #getApplicationListener()}. Clients
* can override the default loading screen via {@link #getPreloaderCallback()}
* and implement any loading screen drawing via GWT widgets.
*
*
* @author mzechner
*/
public abstract class GwtApplication implements EntryPoint, Application {
private final static Logger log = LoggerFactory.getLogger(GwtApplication.class);
private final static Logger log = LoggerFactory.getLogger(GwtApplication.class);
private ApplicationListener listener;
private GwtApplicationConfiguration config;
private GwtGraphics graphics;
private GwtInput input;
private GwtNet net;
private int logLevel = LOG_ERROR;
private Array<Runnable> runnables = new Array<Runnable>();
private Array<Runnable> runnablesHelper = new Array<Runnable>();
private Array<LifecycleListener> lifecycleListeners = new Array<LifecycleListener>();
private int lastWidth;
private int lastHeight;
Preloader preloader;
private static AgentInfo agentInfo;
private ObjectMap<String, Preferences> prefs = new ObjectMap<String, Preferences>();
private ApplicationListener listener;
private GwtApplicationConfiguration config;
private GwtGraphics graphics;
private GwtInput input;
private GwtNet net;
private int logLevel = LOG_ERROR;
private Array<Runnable> runnables = new Array<Runnable>();
private Array<Runnable> runnablesHelper = new Array<Runnable>();
private Array<LifecycleListener> lifecycleListeners = new Array<LifecycleListener>();
private int lastWidth;
private int lastHeight;
Preloader preloader;
private static AgentInfo agentInfo;
private ObjectMap<String, Preferences> prefs = new ObjectMap<String, Preferences>();
/** @return the configuration for the {@link GwtApplication}. */
public abstract GwtApplicationConfiguration getConfig();
/**
* @return the configuration for the {@link GwtApplication}.
*/
public abstract GwtApplicationConfiguration getConfig();
public String getPreloaderBaseURL() {
return GWT.getHostPageBaseURL() + "assets/";
}
public String getPreloaderBaseURL() {
return GWT.getHostPageBaseURL() + "assets/";
}
@Override
public void onModuleLoad() {
GwtApplication.agentInfo = computeAgentInfo();
this.listener = getApplicationListener();
this.config = getConfig();
@Override
public void onModuleLoad() {
GwtApplication.agentInfo = computeAgentInfo();
this.listener = getApplicationListener();
this.config = getConfig();
final PreloaderCallback callback = getPreloaderCallback();
preloader = createPreloader();
preloader.preload("assets.txt", new PreloaderCallback() {
@Override
public void error(String file) {
callback.error(file);
}
final PreloaderCallback callback = getPreloaderCallback();
preloader = createPreloader();
preloader.preload("assets.txt", new PreloaderCallback() {
@Override
public void error(String file) {
callback.error(file);
}
@Override
public void update(PreloaderState state) {
callback.update(state);
if (state.hasEnded()) {
//getRootPanel().clear();
setupLoop();
}
}
});
}
@Override
public void update(PreloaderState state) {
callback.update(state);
if (state.hasEnded()) {
//getRootPanel().clear();
setupLoop();
}
}
});
}
void setupLoop() {
Gdx.app = this;
// setup modules
try {
graphics = new GwtGraphics(null, config);
} catch (Throwable e) {
error("GwtApplication", "exception: " + e.getMessage(), e);
//root.clear();
//root.add(new Label("Sorry, your browser doesn't seem to support WebGL"));
return;
}
lastWidth = graphics.getWidth();
lastHeight = graphics.getHeight();
Gdx.app = this;
Gdx.graphics = graphics;
Gdx.gl20 = graphics.getGL20();
Gdx.gl = Gdx.gl20;
Gdx.files = new GwtFiles(preloader);
this.input = new GwtInput(graphics.canvas);
Gdx.input = this.input;
this.net = new GwtNet();
Gdx.net = this.net;
void setupLoop() {
Gdx.app = this;
// setup modules
try {
graphics = new GwtGraphics(null, config);
} catch (Throwable e) {
error("GwtApplication", "exception: " + e.getMessage(), e);
//root.clear();
//root.add(new Label("Sorry, your browser doesn't seem to support WebGL"));
return;
}
lastWidth = graphics.getWidth();
lastHeight = graphics.getHeight();
Gdx.app = this;
Gdx.graphics = graphics;
Gdx.gl20 = graphics.getGL20();
Gdx.gl = Gdx.gl20;
Gdx.files = new GwtFiles(preloader);
this.input = new GwtInput(graphics.canvas);
Gdx.input = this.input;
this.net = new GwtNet();
Gdx.net = this.net;
// tell listener about app creation
try {
listener.create();
listener.resize(graphics.getWidth(), graphics.getHeight());
} catch (Throwable t) {
error("GwtApplication", "exception: " + t.getMessage(), t);
t.printStackTrace();
throw new RuntimeException(t);
}
// tell listener about app creation
try {
listener.create();
listener.resize(graphics.getWidth(), graphics.getHeight());
} catch (Throwable t) {
error("GwtApplication", "exception: " + t.getMessage(), t);
t.printStackTrace();
throw new RuntimeException(t);
}
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
final int frameTime = (int) ((1f / config.fps) * 1000);
final int frameTime = (int) ((1f / config.fps) * 1000);
// setup rendering timer
new Timer() {
@Override
public void run() {
try {
mainLoop(this, frameTime);
} catch (Throwable t) {
error("GwtApplication", "exception: " + t.getMessage(), t);
throw new RuntimeException(t);
}
}
}.schedule(1);
}
// setup rendering timer
new Timer() {
@Override
public void run() {
try {
mainLoop(this, frameTime);
} catch (Throwable t) {
error("GwtApplication", "exception: " + t.getMessage(), t);
throw new RuntimeException(t);
}
}
}.schedule(1);
}
void mainLoop(Timer timer, int frameTime) {
graphics.update();
if (Gdx.graphics.getWidth() != lastWidth || Gdx.graphics.getHeight() != lastHeight) {
GwtApplication.this.listener.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
lastWidth = graphics.getWidth();
lastHeight = graphics.getHeight();
Gdx.gl.glViewport(0, 0, lastWidth, lastHeight);
}
runnablesHelper.addAll(runnables);
runnables.clear();
for (int i = 0; i < runnablesHelper.size; i++) {
runnablesHelper.get(i).run();
}
runnablesHelper.clear();
listener.render();
input.justTouched = false;
void mainLoop(Timer timer, int frameTime) {
graphics.update();
if (Gdx.graphics.getWidth() != lastWidth || Gdx.graphics.getHeight() != lastHeight) {
GwtApplication.this.listener.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
lastWidth = graphics.getWidth();
lastHeight = graphics.getHeight();
Gdx.gl.glViewport(0, 0, lastWidth, lastHeight);
}
runnablesHelper.addAll(runnables);
runnables.clear();
for (int i = 0; i < runnablesHelper.size; i++) {
runnablesHelper.get(i).run();
}
runnablesHelper.clear();
listener.render();
input.justTouched = false;
long now = System.currentTimeMillis();
int diff = (int) (now - graphics.lastTimeStamp);
diff = frameTime - diff;
timer.schedule(diff > 5 ? diff : 5);
}
long now = System.currentTimeMillis();
int diff = (int) (now - graphics.lastTimeStamp);
diff = frameTime - diff;
timer.schedule(diff > 5 ? diff : 5);
}
public Panel getRootPanel() {
throw new GdxRuntimeException("no panel!");
}
public Panel getRootPanel() {
throw new GdxRuntimeException("no panel!");
}
long loadStart = TimeUtils.nanoTime();
long loadStart = TimeUtils.nanoTime();
public Preloader createPreloader() {
return new Preloader(getPreloaderBaseURL());
}
public Preloader createPreloader() {
return new Preloader(getPreloaderBaseURL());
}
public PreloaderCallback getPreloaderCallback() {
return null;
}
public PreloaderCallback getPreloaderCallback() {
return null;
}
@Override
public Graphics getGraphics() {
return graphics;
}
@Override
public Graphics getGraphics() {
return graphics;
}
@Override
public Audio getAudio() {
return Gdx.audio;
}
@Override
public Audio getAudio() {
return Gdx.audio;
}
@Override
public Input getInput() {
return Gdx.input;
}
@Override
public Input getInput() {
return Gdx.input;
}
@Override
public Files getFiles() {
return Gdx.files;
}
@Override
public Files getFiles() {
return Gdx.files;
}
@Override
public Net getNet() {
return Gdx.net;
}
@Override
public Net getNet() {
return Gdx.net;
}
@Override
public void log(String tag, String message) {
log.info("{} : {}", tag, message);
}
@Override
public void log(String tag, String message) {
log.info("{} : {}", tag, message);
}
@Override
public void log(String tag, String message, Throwable exception) {
log.info("{} : {}\n{}", tag, exception, getStackTrace(exception));
}
@Override
public void log(String tag, String message, Throwable exception) {
log.info("{} : {}\n{}", tag, exception, getStackTrace(exception));
}
@Override
public void error(String tag, String message) {
log.error("{} : {}", tag, message);
}
@Override
public void error(String tag, String message) {
log.error("{} : {}", tag, message);
}
@Override
public void error(String tag, String message, Throwable exception) {
log.error("{} : {}\n{}", tag, message, getStackTrace(exception));
}
@Override
public void error(String tag, String message, Throwable exception) {
log.error("{} : {}\n{}", tag, message, getStackTrace(exception));
}
@Override
public void debug(String tag, String message) {
log.debug("{} : {}", tag, message);
}
@Override
public void debug(String tag, String message) {
log.debug("{} : {}", tag, message);
}
@Override
public void debug(String tag, String message, Throwable exception) {
log.debug("{} : {}\n{}", tag, message, getStackTrace(exception));
}
@Override
public void debug(String tag, String message, Throwable exception) {
log.debug("{} : {}\n{}", tag, message, getStackTrace(exception));
}
private String getStackTrace(Throwable e) {
StringBuffer buffer = new StringBuffer();
for (StackTraceElement trace : e.getStackTrace()) {
buffer.append(trace.toString() + "\n");
}
return buffer.toString();
}
private String getStackTrace(Throwable e) {
StringBuffer buffer = new StringBuffer();
for (StackTraceElement trace : e.getStackTrace()) {
buffer.append(trace.toString() + "\n");
}
return buffer.toString();
}
@Override
public void setLogLevel(int logLevel) {
}
@Override
public void setLogLevel(int logLevel) {
}
@Override
public int getLogLevel() {
return LOG_DEBUG;
}
@Override
public int getLogLevel() {
return LOG_DEBUG;
}
@Override
public ApplicationType getType() {
return ApplicationType.WebGL;
}
@Override
public ApplicationType getType() {
return ApplicationType.WebGL;
}
@Override
public int getVersion() {
return 0;
}
@Override
public int getVersion() {
return 0;
}
@Override
public long getJavaHeap() {
return 0;
}
@Override
public long getJavaHeap() {
return 0;
}
@Override
public long getNativeHeap() {
return 0;
}
@Override
public long getNativeHeap() {
return 0;
}
@Override
public Preferences getPreferences(String name) {
Preferences pref = prefs.get(name);
if (pref == null) {
pref = new GwtPreferences(name);
prefs.put(name, pref);
}
return pref;
}
@Override
public Preferences getPreferences(String name) {
Preferences pref = prefs.get(name);
if (pref == null) {
pref = new GwtPreferences(name);
prefs.put(name, pref);
}
return pref;
}
@Override
public Clipboard getClipboard() {
return new Clipboard() {
@Override
public String getContents() {
return null;
}
@Override
public Clipboard getClipboard() {
return new Clipboard() {
@Override
public String getContents() {
return null;
}
@Override
public void setContents(String content) {
}
};
}
@Override
public void setContents(String content) {
}
};
}
@Override
public void postRunnable(Runnable runnable) {
runnables.add(runnable);
}
@Override
public void postRunnable(Runnable runnable) {
runnables.add(runnable);
}
@Override
public void exit() {
}
@Override
public void exit() {
}
/**
* Contains precomputed information on the user-agent. Useful for dealing
* with browser and OS behavioral differences. Kindly
* borrowed from PlayN
*/
public static AgentInfo agentInfo() {
return agentInfo;
}
/**
* Contains precomputed information on the user-agent. Useful for dealing
* with browser and OS behavioral differences. Kindly
* borrowed from PlayN
*/
public static AgentInfo agentInfo() {
return agentInfo;
}
/** kindly borrowed from PlayN **/
private static native AgentInfo computeAgentInfo() /*-{
var userAgent = navigator.userAgent.toLowerCase();
/**
* kindly borrowed from PlayN
**/
private static native AgentInfo computeAgentInfo() /*-{
var userAgent = navigator.userAgent.toLowerCase();
return {
// browser type flags
isFirefox : userAgent.indexOf("firefox") != -1,
@@ -342,63 +346,65 @@ public abstract class GwtApplication implements EntryPoint, Application {
};
}-*/;
/** Returned by {@link #agentInfo}. Kindly borrowed from PlayN. */
public static class AgentInfo extends JavaScriptObject {
public final native boolean isFirefox() /*-{
return this.isFirefox;
/**
* Returned by {@link #agentInfo}. Kindly borrowed from PlayN.
*/
public static class AgentInfo extends JavaScriptObject {
public final native boolean isFirefox() /*-{
return this.isFirefox;
}-*/;
public final native boolean isChrome() /*-{
public final native boolean isChrome() /*-{
return this.isChrome;
}-*/;
public final native boolean isSafari() /*-{
public final native boolean isSafari() /*-{
return this.isSafari;
}-*/;
public final native boolean isOpera() /*-{
public final native boolean isOpera() /*-{
return this.isOpera;
}-*/;
public final native boolean isIE() /*-{
public final native boolean isIE() /*-{
return this.isIE;
}-*/;
public final native boolean isMacOS() /*-{
public final native boolean isMacOS() /*-{
return this.isMacOS;
}-*/;
public final native boolean isLinux() /*-{
public final native boolean isLinux() /*-{
return this.isLinux;
}-*/;
public final native boolean isWindows() /*-{
public final native boolean isWindows() /*-{
return this.isWindows;
}-*/;
protected AgentInfo() {
}
}
protected AgentInfo() {
}
}
public String getBaseUrl() {
return preloader.baseUrl;
}
public String getBaseUrl() {
return preloader.baseUrl;
}
public Preloader getPreloader() {
return preloader;
}
public Preloader getPreloader() {
return preloader;
}
@Override
public void addLifecycleListener(LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void addLifecycleListener(LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener(LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
@Override
public void removeLifecycleListener(LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
}

View File

@@ -1,12 +1,12 @@
/*******************************************************************************
* Copyright 2011 See libgdx AUTHORS file.
*
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -16,10 +16,6 @@
package com.badlogic.gdx.backends.gwt;
import org.oscim.gdx.client.GdxGL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.graphics.GL20;
@@ -33,154 +29,158 @@ import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.webgl.client.WebGLContextAttributes;
import com.google.gwt.webgl.client.WebGLRenderingContext;
import org.oscim.gdx.client.GdxGL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GwtGraphics implements Graphics {
static final Logger log = LoggerFactory.getLogger(GwtGraphics.class);
static final Logger log = LoggerFactory.getLogger(GwtGraphics.class);
CanvasElement canvas;
WebGLRenderingContext context;
GL20 gl;
String extensions;
float fps = 0;
long lastTimeStamp = System.currentTimeMillis();
float deltaTime = 0;
float time = 0;
int frames;
GwtApplicationConfiguration config;
boolean inFullscreenMode = false;
double pixelRatio;
CanvasElement canvas;
WebGLRenderingContext context;
GL20 gl;
String extensions;
float fps = 0;
long lastTimeStamp = System.currentTimeMillis();
float deltaTime = 0;
float time = 0;
int frames;
GwtApplicationConfiguration config;
boolean inFullscreenMode = false;
double pixelRatio;
public GwtGraphics(Panel root, final GwtApplicationConfiguration config) {
this.pixelRatio = getDevicePixelRatioJSNI();
public GwtGraphics(Panel root, final GwtApplicationConfiguration config) {
this.pixelRatio = getDevicePixelRatioJSNI();
if (config.canvasId == null) {
Canvas canvasWidget = Canvas.createIfSupported();
if (canvasWidget == null)
throw new GdxRuntimeException("Canvas not supported");
canvas = canvasWidget.getCanvasElement();
root.add(canvasWidget);
} else {
canvas = (CanvasElement) Document.get().getElementById(config.canvasId);
if (config.canvasId == null) {
Canvas canvasWidget = Canvas.createIfSupported();
if (canvasWidget == null)
throw new GdxRuntimeException("Canvas not supported");
canvas = canvasWidget.getCanvasElement();
root.add(canvasWidget);
} else {
canvas = (CanvasElement) Document.get().getElementById(config.canvasId);
canvas.setWidth((int) (config.width * pixelRatio));
canvas.setHeight((int) (config.height * pixelRatio));
canvas.setWidth((int) (config.width * pixelRatio));
canvas.setHeight((int) (config.height * pixelRatio));
canvas.getStyle().setWidth(config.width, Unit.PX);
canvas.getStyle().setHeight(config.height, Unit.PX);
}
canvas.getStyle().setWidth(config.width, Unit.PX);
canvas.getStyle().setHeight(config.height, Unit.PX);
}
this.config = config;
this.config = config;
WebGLContextAttributes attributes = WebGLContextAttributes.create();
attributes.setAntialias(config.antialiasing);
attributes.setStencil(config.stencil);
attributes.setAlpha(false);
attributes.setPremultipliedAlpha(false);
WebGLContextAttributes attributes = WebGLContextAttributes.create();
attributes.setAntialias(config.antialiasing);
attributes.setStencil(config.stencil);
attributes.setAlpha(false);
attributes.setPremultipliedAlpha(false);
context = WebGLRenderingContext.getContext(canvas, attributes);
if (context == null)
throw new GdxRuntimeException("Could not create Canvas for " + attributes);
context = WebGLRenderingContext.getContext(canvas, attributes);
if (context == null)
throw new GdxRuntimeException("Could not create Canvas for " + attributes);
context.viewport(0, 0, config.width, config.height);
context.viewport(0, 0, config.width, config.height);
// this actually *enables* the option to use std derivatives in shader..
if (context.getExtension("OES_standard_derivatives") == null) {
log.error("Missing gl extension for OES_standard_derivatives");
}
// this actually *enables* the option to use std derivatives in shader..
if (context.getExtension("OES_standard_derivatives") == null) {
log.error("Missing gl extension for OES_standard_derivatives");
}
if (context.getExtension("WEBKIT_WEBGL_depth_texture") == null) {
log.error("Missing gl extension for WEBKIT_WEBGL_depth_texture");
}
if (context.getExtension("WEBKIT_WEBGL_depth_texture") == null) {
log.error("Missing gl extension for WEBKIT_WEBGL_depth_texture");
}
this.gl = config.useDebugGL ? new GwtGL20Debug(context) : new GdxGL(context);
}
this.gl = config.useDebugGL ? new GwtGL20Debug(context) : new GdxGL(context);
}
public static native double getDevicePixelRatioJSNI() /*-{
return $wnd.devicePixelRatio || 1.0;
public static native double getDevicePixelRatioJSNI() /*-{
return $wnd.devicePixelRatio || 1.0;
}-*/;
public static native int getWindowWidthJSNI() /*-{
return $wnd.innerWidth;
public static native int getWindowWidthJSNI() /*-{
return $wnd.innerWidth;
}-*/;
public static native int getWindowHeightJSNI() /*-{
public static native int getWindowHeightJSNI() /*-{
return $wnd.innerHeight;
}-*/;
public WebGLRenderingContext getContext() {
return context;
}
public WebGLRenderingContext getContext() {
return context;
}
@Override
public GL20 getGL20() {
return gl;
}
@Override
public GL20 getGL20() {
return gl;
}
@Override
public int getWidth() {
return canvas.getWidth();
}
@Override
public int getWidth() {
return canvas.getWidth();
}
@Override
public int getHeight() {
return canvas.getHeight();
}
@Override
public int getHeight() {
return canvas.getHeight();
}
@Override
public float getDeltaTime() {
return deltaTime;
}
@Override
public float getDeltaTime() {
return deltaTime;
}
@Override
public int getFramesPerSecond() {
return (int) fps;
}
@Override
public int getFramesPerSecond() {
return (int) fps;
}
@Override
public GraphicsType getType() {
return GraphicsType.WebGL;
}
@Override
public GraphicsType getType() {
return GraphicsType.WebGL;
}
@Override
public float getPpiX() {
return 96;
}
@Override
public float getPpiX() {
return 96;
}
@Override
public float getPpiY() {
return 96;
}
@Override
public float getPpiY() {
return 96;
}
@Override
public float getPpcX() {
return 96 / 2.54f;
}
@Override
public float getPpcX() {
return 96 / 2.54f;
}
@Override
public float getPpcY() {
return 96 / 2.54f;
}
@Override
public float getPpcY() {
return 96 / 2.54f;
}
@Override
public boolean supportsDisplayModeChange() {
return true;
}
@Override
public boolean supportsDisplayModeChange() {
return true;
}
@Override
public DisplayMode[] getDisplayModes() {
return new DisplayMode[] { new DisplayMode(getScreenWidthJSNI(), getScreenHeightJSNI(), 60,
8) {
} };
}
@Override
public DisplayMode[] getDisplayModes() {
return new DisplayMode[]{new DisplayMode(getScreenWidthJSNI(), getScreenHeightJSNI(), 60,
8) {
}};
}
private native int getScreenWidthJSNI() /*-{
private native int getScreenWidthJSNI() /*-{
return $wnd.screen.width;
}-*/;
private native int getScreenHeightJSNI() /*-{
private native int getScreenHeightJSNI() /*-{
return $wnd.screen.height;
}-*/;
private native boolean isFullscreenJSNI() /*-{
private native boolean isFullscreenJSNI() /*-{
if ("webkitIsFullScreen" in $doc) {
return $doc.webkitIsFullScreen;
}
@@ -190,14 +190,14 @@ public class GwtGraphics implements Graphics {
return false
}-*/;
private void fullscreenChanged() {
if (!isFullscreen()) {
canvas.setWidth(config.width);
canvas.setHeight(config.height);
}
}
private void fullscreenChanged() {
if (!isFullscreen()) {
canvas.setWidth(config.width);
canvas.setHeight(config.height);
}
}
private native boolean setFullscreenJSNI(GwtGraphics graphics, CanvasElement element) /*-{
private native boolean setFullscreenJSNI(GwtGraphics graphics, CanvasElement element) /*-{
if (element.webkitRequestFullScreen) {
element.width = $wnd.screen.width;
element.height = $wnd.screen.height;
@@ -225,118 +225,118 @@ public class GwtGraphics implements Graphics {
return false;
}-*/;
private native void exitFullscreen() /*-{
private native void exitFullscreen() /*-{
if ($doc.webkitExitFullscreen)
$doc.webkitExitFullscreen();
if ($doc.mozExitFullscreen)
$doc.mozExitFullscreen();
}-*/;
@Override
public DisplayMode getDesktopDisplayMode() {
return new DisplayMode(getScreenWidthJSNI(), getScreenHeightJSNI(), 60, 8) {
};
}
@Override
public DisplayMode getDesktopDisplayMode() {
return new DisplayMode(getScreenWidthJSNI(), getScreenHeightJSNI(), 60, 8) {
};
}
@Override
public boolean setDisplayMode(DisplayMode displayMode) {
if (displayMode.width != getScreenWidthJSNI()
&& displayMode.height != getScreenHeightJSNI())
return false;
return setFullscreenJSNI(this, canvas);
}
@Override
public boolean setDisplayMode(DisplayMode displayMode) {
if (displayMode.width != getScreenWidthJSNI()
&& displayMode.height != getScreenHeightJSNI())
return false;
return setFullscreenJSNI(this, canvas);
}
@Override
public boolean setDisplayMode(int width, int height, boolean fullscreen) {
if (fullscreen) {
if (width != getScreenWidthJSNI() && height != getScreenHeightJSNI())
return false;
return setFullscreenJSNI(this, canvas);
} else {
if (isFullscreenJSNI())
exitFullscreen();
canvas.setWidth(width);
canvas.setHeight(height);
canvas.getStyle().setWidth(width, Unit.PX);
canvas.getStyle().setHeight(height, Unit.PX);
return true;
}
}
@Override
public boolean setDisplayMode(int width, int height, boolean fullscreen) {
if (fullscreen) {
if (width != getScreenWidthJSNI() && height != getScreenHeightJSNI())
return false;
return setFullscreenJSNI(this, canvas);
} else {
if (isFullscreenJSNI())
exitFullscreen();
canvas.setWidth(width);
canvas.setHeight(height);
canvas.getStyle().setWidth(width, Unit.PX);
canvas.getStyle().setHeight(height, Unit.PX);
return true;
}
}
@Override
public BufferFormat getBufferFormat() {
return new BufferFormat(8, 8, 8, 0, 16, config.stencil ? 8 : 0, 0, false);
}
@Override
public BufferFormat getBufferFormat() {
return new BufferFormat(8, 8, 8, 0, 16, config.stencil ? 8 : 0, 0, false);
}
@Override
public boolean supportsExtension(String extension) {
if (extensions == null)
extensions = Gdx.gl.glGetString(GL20.GL_EXTENSIONS);
return extensions.contains(extension);
}
@Override
public boolean supportsExtension(String extension) {
if (extensions == null)
extensions = Gdx.gl.glGetString(GL20.GL_EXTENSIONS);
return extensions.contains(extension);
}
public void update() {
long currTimeStamp = System.currentTimeMillis();
deltaTime = (currTimeStamp - lastTimeStamp) / 1000.0f;
lastTimeStamp = currTimeStamp;
time += deltaTime;
frames++;
if (time > 1) {
this.fps = frames;
time = 0;
frames = 0;
}
}
public void update() {
long currTimeStamp = System.currentTimeMillis();
deltaTime = (currTimeStamp - lastTimeStamp) / 1000.0f;
lastTimeStamp = currTimeStamp;
time += deltaTime;
frames++;
if (time > 1) {
this.fps = frames;
time = 0;
frames = 0;
}
}
@Override
public void setTitle(String title) {
}
@Override
public void setTitle(String title) {
}
@Override
public void setVSync(boolean vsync) {
}
@Override
public void setVSync(boolean vsync) {
}
@Override
public float getDensity() {
return 96.0f / 160;
}
@Override
public float getDensity() {
return 96.0f / 160;
}
@Override
public void setContinuousRendering(boolean isContinuous) {
}
@Override
public void setContinuousRendering(boolean isContinuous) {
}
@Override
public boolean isContinuousRendering() {
return false;
}
@Override
public boolean isContinuousRendering() {
return false;
}
@Override
public void requestRendering() {
}
@Override
public void requestRendering() {
}
@Override
public float getRawDeltaTime() {
return getDeltaTime();
}
@Override
public float getRawDeltaTime() {
return getDeltaTime();
}
@Override
public boolean isFullscreen() {
return isFullscreenJSNI();
}
@Override
public boolean isFullscreen() {
return isFullscreenJSNI();
}
@Override
public boolean isGL30Available() {
return false;
}
@Override
public boolean isGL30Available() {
return false;
}
@Override
public GL30 getGL30() {
return null;
}
@Override
public GL30 getGL30() {
return null;
}
@Override
public long getFrameId() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getFrameId() {
// TODO Auto-generated method stub
return 0;
}
}

View File

@@ -1,12 +1,12 @@
/*******************************************************************************
* Copyright 2011 See libgdx AUTHORS file.
*
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -16,11 +16,6 @@
package com.badlogic.gdx.graphics;
import java.nio.Buffer;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.backends.gwt.GwtFileHandle;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.BufferUtils;
@@ -33,185 +28,216 @@ import com.google.gwt.canvas.dom.client.Context2d.Composite;
import com.google.gwt.dom.client.CanvasElement;
import com.google.gwt.dom.client.ImageElement;
import java.nio.Buffer;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.Map;
public class Pixmap implements Disposable {
public static Map<Integer, Pixmap> pixmaps = new HashMap<Integer, Pixmap>();
static int nextId = 0;
public static Map<Integer, Pixmap> pixmaps = new HashMap<Integer, Pixmap>();
static int nextId = 0;
/** Different pixel formats.
*
* @author mzechner */
public enum Format {
Alpha, Intensity, LuminanceAlpha, RGB565, RGBA4444, RGB888, RGBA8888;
}
/**
* Different pixel formats.
*
* @author mzechner
*/
public enum Format {
Alpha, Intensity, LuminanceAlpha, RGB565, RGBA4444, RGB888, RGBA8888;
}
/** Blending functions to be set with {@link Pixmap#setBlending}.
* @author mzechner */
public enum Blending {
None, SourceOver
}
/**
* Blending functions to be set with {@link Pixmap#setBlending}.
*
* @author mzechner
*/
public enum Blending {
None, SourceOver
}
/** Filters to be used with {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}.
*
* @author mzechner */
public enum Filter {
NearestNeighbour, BiLinear
}
/**
* Filters to be used with {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}.
*
* @author mzechner
*/
public enum Filter {
NearestNeighbour, BiLinear
}
int width;
int height;
Format format;
Canvas canvas;
Context2d context;
int id;
IntBuffer buffer;
int r = 255, g = 255, b = 255;
float a;
String color = make(r, g, b, a);
static Blending blending;
CanvasPixelArray pixels;
int width;
int height;
Format format;
Canvas canvas;
Context2d context;
int id;
IntBuffer buffer;
int r = 255, g = 255, b = 255;
float a;
String color = make(r, g, b, a);
static Blending blending;
CanvasPixelArray pixels;
public Context2d getContext(){
return context;
}
public Context2d getContext() {
return context;
}
public Pixmap (FileHandle file) {
GwtFileHandle gwtFile = (GwtFileHandle)file;
ImageElement img = gwtFile.preloader.images.get(file.path());
if (img == null) throw new GdxRuntimeException("Couldn't load image '" + file.path() + "', file does not exist");
create(img.getWidth(), img.getHeight(), Format.RGBA8888);
context.setGlobalCompositeOperation(Composite.COPY);
context.drawImage(img, 0, 0);
context.setGlobalCompositeOperation(getComposite());
}
public Pixmap(FileHandle file) {
GwtFileHandle gwtFile = (GwtFileHandle) file;
ImageElement img = gwtFile.preloader.images.get(file.path());
if (img == null)
throw new GdxRuntimeException("Couldn't load image '" + file.path() + "', file does not exist");
create(img.getWidth(), img.getHeight(), Format.RGBA8888);
context.setGlobalCompositeOperation(Composite.COPY);
context.drawImage(img, 0, 0);
context.setGlobalCompositeOperation(getComposite());
}
private static Composite getComposite () {
return blending == Blending.None ? Composite.COPY : Composite.SOURCE_OVER;
}
private static Composite getComposite() {
return blending == Blending.None ? Composite.COPY : Composite.SOURCE_OVER;
}
public Pixmap (ImageElement img) {
create(img.getWidth(), img.getHeight(), Format.RGBA8888);
context.drawImage(img, 0, 0);
}
public Pixmap(ImageElement img) {
create(img.getWidth(), img.getHeight(), Format.RGBA8888);
context.drawImage(img, 0, 0);
}
public Pixmap (int width, int height, Format format) {
create(width, height, format);
}
public Pixmap(int width, int height, Format format) {
create(width, height, format);
}
private void create (int width, int height, Format format2) {
this.width = width;
this.height = height;
this.format = Format.RGBA8888;
canvas = Canvas.createIfSupported();
canvas.getCanvasElement().setWidth(width);
canvas.getCanvasElement().setHeight(height);
context = canvas.getContext2d();
context.setGlobalCompositeOperation(getComposite());
buffer = BufferUtils.newIntBuffer(1);
id = nextId++;
buffer.put(0, id);
pixmaps.put(id, this);
}
private void create(int width, int height, Format format2) {
this.width = width;
this.height = height;
this.format = Format.RGBA8888;
canvas = Canvas.createIfSupported();
canvas.getCanvasElement().setWidth(width);
canvas.getCanvasElement().setHeight(height);
context = canvas.getContext2d();
context.setGlobalCompositeOperation(getComposite());
buffer = BufferUtils.newIntBuffer(1);
id = nextId++;
buffer.put(0, id);
pixmaps.put(id, this);
}
public static String make (int r2, int g2, int b2, float a2) {
return "rgba(" + r2 + "," + g2 + "," + b2 + "," + a2 + ")";
}
public static String make(int r2, int g2, int b2, float a2) {
return "rgba(" + r2 + "," + g2 + "," + b2 + "," + a2 + ")";
}
/** Sets the type of {@link Blending} to be used for all operations. Default is {@link Blending#SourceOver}.
* @param blending the blending type */
public static void setBlending (Blending blending) {
Pixmap.blending = blending;
Composite composite = getComposite();
for (Pixmap pixmap : pixmaps.values()) {
pixmap.context.setGlobalCompositeOperation(composite);
}
}
/**
* Sets the type of {@link Blending} to be used for all operations. Default is {@link Blending#SourceOver}.
*
* @param blending the blending type
*/
public static void setBlending(Blending blending) {
Pixmap.blending = blending;
Composite composite = getComposite();
for (Pixmap pixmap : pixmaps.values()) {
pixmap.context.setGlobalCompositeOperation(composite);
}
}
/** @return the currently set {@link Blending} */
public static Blending getBlending () {
return blending;
}
/**
* @return the currently set {@link Blending}
*/
public static Blending getBlending() {
return blending;
}
/** Sets the type of interpolation {@link Filter} to be used in conjunction with
* {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}.
* @param filter the filter. */
public static void setFilter (Filter filter) {
}
/**
* Sets the type of interpolation {@link Filter} to be used in conjunction with
* {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}.
*
* @param filter the filter.
*/
public static void setFilter(Filter filter) {
}
public Format getFormat () {
return format;
}
public Format getFormat() {
return format;
}
public int getGLInternalFormat () {
return GL20.GL_RGBA;
}
public int getGLInternalFormat() {
return GL20.GL_RGBA;
}
public int getGLFormat () {
return GL20.GL_RGBA;
}
public int getGLFormat() {
return GL20.GL_RGBA;
}
public int getGLType () {
return GL20.GL_UNSIGNED_BYTE;
}
public int getGLType() {
return GL20.GL_UNSIGNED_BYTE;
}
public int getWidth () {
return width;
}
public int getWidth() {
return width;
}
public int getHeight () {
return height;
}
public int getHeight() {
return height;
}
public Buffer getPixels () {
return buffer;
}
public Buffer getPixels() {
return buffer;
}
@Override
public void dispose () {
pixmaps.remove(id);
}
@Override
public void dispose() {
pixmaps.remove(id);
}
public CanvasElement getCanvasElement () {
return canvas.getCanvasElement();
}
public CanvasElement getCanvasElement() {
return canvas.getCanvasElement();
}
/** Sets the color for the following drawing operations
* @param color the color, encoded as RGBA8888 */
public void setColor (int color) {
r = (color >>> 24) & 0xff;
g = (color >>> 16) & 0xff;
b = (color >>> 8) & 0xff;
a = (color & 0xff) / 255f;
this.color = make(r, g, b, a);
context.setFillStyle(this.color);
context.setStrokeStyle(this.color);
}
/**
* Sets the color for the following drawing operations
*
* @param color the color, encoded as RGBA8888
*/
public void setColor(int color) {
r = (color >>> 24) & 0xff;
g = (color >>> 16) & 0xff;
b = (color >>> 8) & 0xff;
a = (color & 0xff) / 255f;
this.color = make(r, g, b, a);
context.setFillStyle(this.color);
context.setStrokeStyle(this.color);
}
/** Sets the color for the following drawing operations.
*
* @param r The red component.
* @param g The green component.
* @param b The blue component.
* @param a The alpha component. */
public void setColor (float r, float g, float b, float a) {
this.r = (int)(r * 255);
this.g = (int)(g * 255);
this.b = (int)(b * 255);
this.a = a;
color = make(this.r, this.g, this.b, this.a);
context.setFillStyle(color);
context.setStrokeStyle(this.color);
}
/**
* Sets the color for the following drawing operations.
*
* @param r The red component.
* @param g The green component.
* @param b The blue component.
* @param a The alpha component.
*/
public void setColor(float r, float g, float b, float a) {
this.r = (int) (r * 255);
this.g = (int) (g * 255);
this.b = (int) (b * 255);
this.a = a;
color = make(this.r, this.g, this.b, this.a);
context.setFillStyle(color);
context.setStrokeStyle(this.color);
}
/** Sets the color for the following drawing operations.
* @param color The color. */
public void setColor (Color color) {
setColor(color.r, color.g, color.b, color.a);
}
/**
* Sets the color for the following drawing operations.
*
* @param color The color.
*/
public void setColor(Color color) {
setColor(color.r, color.g, color.b, color.a);
}
/** Fills the complete bitmap with the currently set color. */
public void fill () {
context.fillRect(0, 0, getWidth(), getHeight());
}
/**
* Fills the complete bitmap with the currently set color.
*/
public void fill() {
context.fillRect(0, 0, getWidth(), getHeight());
}
// /**
// * Sets the width in pixels of strokes.
@@ -220,158 +246,182 @@ public class Pixmap implements Disposable {
// */
// public void setStrokeWidth (int width);
/** Draws a line between the given coordinates using the currently set color.
*
* @param x The x-coodinate of the first point
* @param y The y-coordinate of the first point
* @param x2 The x-coordinate of the first point
* @param y2 The y-coordinate of the first point */
public void drawLine (int x, int y, int x2, int y2) {
context.beginPath();
context.moveTo(x, y);
context.lineTo(x2, y2);
context.stroke();
context.closePath();
}
/**
* Draws a line between the given coordinates using the currently set color.
*
* @param x The x-coodinate of the first point
* @param y The y-coordinate of the first point
* @param x2 The x-coordinate of the first point
* @param y2 The y-coordinate of the first point
*/
public void drawLine(int x, int y, int x2, int y2) {
context.beginPath();
context.moveTo(x, y);
context.lineTo(x2, y2);
context.stroke();
context.closePath();
}
/** Draws a rectangle outline starting at x, y extending by width to the right and by height downwards (y-axis points downwards)
* using the current color.
*
* @param x The x coordinate
* @param y The y coordinate
* @param width The width in pixels
* @param height The height in pixels */
public void drawRectangle (int x, int y, int width, int height) {
context.beginPath();
context.rect(x, y, width, height);
context.stroke();
context.closePath();
}
/**
* Draws a rectangle outline starting at x, y extending by width to the right and by height downwards (y-axis points downwards)
* using the current color.
*
* @param x The x coordinate
* @param y The y coordinate
* @param width The width in pixels
* @param height The height in pixels
*/
public void drawRectangle(int x, int y, int width, int height) {
context.beginPath();
context.rect(x, y, width, height);
context.stroke();
context.closePath();
}
/** Draws an area form another Pixmap to this Pixmap.
*
* @param pixmap The other Pixmap
* @param x The target x-coordinate (top left corner)
* @param y The target y-coordinate (top left corner) */
public void drawPixmap (Pixmap pixmap, int x, int y) {
context.drawImage(pixmap.getCanvasElement(), x, y);
}
/**
* Draws an area form another Pixmap to this Pixmap.
*
* @param pixmap The other Pixmap
* @param x The target x-coordinate (top left corner)
* @param y The target y-coordinate (top left corner)
*/
public void drawPixmap(Pixmap pixmap, int x, int y) {
context.drawImage(pixmap.getCanvasElement(), x, y);
}
/** Draws an area form another Pixmap to this Pixmap.
*
* @param pixmap The other Pixmap
* @param x The target x-coordinate (top left corner)
* @param y The target y-coordinate (top left corner)
* @param srcx The source x-coordinate (top left corner)
* @param srcy The source y-coordinate (top left corner);
* @param srcWidth The width of the area form the other Pixmap in pixels
* @param srcHeight The height of the area form the other Pixmap in pixles */
public void drawPixmap (Pixmap pixmap, int x, int y, int srcx, int srcy, int srcWidth, int srcHeight) {
context.drawImage(pixmap.getCanvasElement(), srcx, srcy, srcWidth, srcHeight, x, y, srcWidth, srcHeight);
}
/**
* Draws an area form another Pixmap to this Pixmap.
*
* @param pixmap The other Pixmap
* @param x The target x-coordinate (top left corner)
* @param y The target y-coordinate (top left corner)
* @param srcx The source x-coordinate (top left corner)
* @param srcy The source y-coordinate (top left corner);
* @param srcWidth The width of the area form the other Pixmap in pixels
* @param srcHeight The height of the area form the other Pixmap in pixles
*/
public void drawPixmap(Pixmap pixmap, int x, int y, int srcx, int srcy, int srcWidth, int srcHeight) {
context.drawImage(pixmap.getCanvasElement(), srcx, srcy, srcWidth, srcHeight, x, y, srcWidth, srcHeight);
}
/** Draws an area form another Pixmap to this Pixmap. This will automatically scale and stretch the source image to the
* specified target rectangle. Use {@link Pixmap#setFilter(Filter)} to specify the type of filtering to be used (nearest
* neighbour or bilinear).
*
* @param pixmap The other Pixmap
* @param srcx The source x-coordinate (top left corner)
* @param srcy The source y-coordinate (top left corner);
* @param srcWidth The width of the area form the other Pixmap in pixels
* @param srcHeight The height of the area form the other Pixmap in pixles
* @param dstx The target x-coordinate (top left corner)
* @param dsty The target y-coordinate (top left corner)
* @param dstWidth The target width
* @param dstHeight the target height */
public void drawPixmap (Pixmap pixmap, int srcx, int srcy, int srcWidth, int srcHeight, int dstx, int dsty, int dstWidth,
int dstHeight) {
context.drawImage(pixmap.getCanvasElement(), srcx, srcy, srcWidth, srcHeight, dstx, dsty, dstWidth, dstHeight);
}
/**
* Draws an area form another Pixmap to this Pixmap. This will automatically scale and stretch the source image to the
* specified target rectangle. Use {@link Pixmap#setFilter(Filter)} to specify the type of filtering to be used (nearest
* neighbour or bilinear).
*
* @param pixmap The other Pixmap
* @param srcx The source x-coordinate (top left corner)
* @param srcy The source y-coordinate (top left corner);
* @param srcWidth The width of the area form the other Pixmap in pixels
* @param srcHeight The height of the area form the other Pixmap in pixles
* @param dstx The target x-coordinate (top left corner)
* @param dsty The target y-coordinate (top left corner)
* @param dstWidth The target width
* @param dstHeight the target height
*/
public void drawPixmap(Pixmap pixmap, int srcx, int srcy, int srcWidth, int srcHeight, int dstx, int dsty, int dstWidth,
int dstHeight) {
context.drawImage(pixmap.getCanvasElement(), srcx, srcy, srcWidth, srcHeight, dstx, dsty, dstWidth, dstHeight);
}
/** Fills a rectangle starting at x, y extending by width to the right and by height downwards (y-axis points downwards) using
* the current color.
*
* @param x The x coordinate
* @param y The y coordinate
* @param width The width in pixels
* @param height The height in pixels */
public void fillRectangle (int x, int y, int width, int height) {
context.fillRect(x, y, width, height);
}
/**
* Fills a rectangle starting at x, y extending by width to the right and by height downwards (y-axis points downwards) using
* the current color.
*
* @param x The x coordinate
* @param y The y coordinate
* @param width The width in pixels
* @param height The height in pixels
*/
public void fillRectangle(int x, int y, int width, int height) {
context.fillRect(x, y, width, height);
}
/** Draws a circle outline with the center at x,y and a radius using the current color and stroke width.
*
* @param x The x-coordinate of the center
* @param y The y-coordinate of the center
* @param radius The radius in pixels */
public void drawCircle (int x, int y, int radius) {
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI, false);
context.stroke();
context.closePath();
}
/**
* Draws a circle outline with the center at x,y and a radius using the current color and stroke width.
*
* @param x The x-coordinate of the center
* @param y The y-coordinate of the center
* @param radius The radius in pixels
*/
public void drawCircle(int x, int y, int radius) {
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI, false);
context.stroke();
context.closePath();
}
/** Fills a circle with the center at x,y and a radius using the current color.
*
* @param x The x-coordinate of the center
* @param y The y-coordinate of the center
* @param radius The radius in pixels */
public void fillCircle (int x, int y, int radius) {
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI, false);
context.fill();
context.closePath();
}
/**
* Fills a circle with the center at x,y and a radius using the current color.
*
* @param x The x-coordinate of the center
* @param y The y-coordinate of the center
* @param radius The radius in pixels
*/
public void fillCircle(int x, int y, int radius) {
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI, false);
context.fill();
context.closePath();
}
/** Fills a triangle with vertices at x1,y1 and x2,y2 and x3,y3 using the current color.
*
* @param x1 The x-coordinate of vertex 1
* @param y1 The y-coordinate of vertex 1
* @param x2 The x-coordinate of vertex 2
* @param y2 The y-coordinate of vertex 2
* @param x3 The x-coordinate of vertex 3
* @param y3 The y-coordinate of vertex 3 */
public void fillTriangle (int x1, int y1, int x2, int y2, int x3, int y3) {
context.beginPath();
context.moveTo(x1,y1);
context.lineTo(x2,y2);
context.lineTo(x3,y3);
context.lineTo(x1,y1);
context.fill();
context.closePath();
}
/**
* Fills a triangle with vertices at x1,y1 and x2,y2 and x3,y3 using the current color.
*
* @param x1 The x-coordinate of vertex 1
* @param y1 The y-coordinate of vertex 1
* @param x2 The x-coordinate of vertex 2
* @param y2 The y-coordinate of vertex 2
* @param x3 The x-coordinate of vertex 3
* @param y3 The y-coordinate of vertex 3
*/
public void fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.lineTo(x3, y3);
context.lineTo(x1, y1);
context.fill();
context.closePath();
}
/** Returns the 32-bit RGBA8888 value of the pixel at x, y. For Alpha formats the RGB components will be one.
*
* @param x The x-coordinate
* @param y The y-coordinate
* @return The pixel color in RGBA8888 format. */
public int getPixel (int x, int y) {
if (pixels == null) pixels = context.getImageData(0, 0, width, height).getData();
int i = x * 4 + y * width * 4;
int r = pixels.get(i + 0) & 0xff;
int g = pixels.get(i + 1) & 0xff;
int b = pixels.get(i + 2) & 0xff;
int a = pixels.get(i + 3) & 0xff;
return (r << 24) | (g << 16) | (b << 8) | (a);
}
/**
* Returns the 32-bit RGBA8888 value of the pixel at x, y. For Alpha formats the RGB components will be one.
*
* @param x The x-coordinate
* @param y The y-coordinate
* @return The pixel color in RGBA8888 format.
*/
public int getPixel(int x, int y) {
if (pixels == null) pixels = context.getImageData(0, 0, width, height).getData();
int i = x * 4 + y * width * 4;
int r = pixels.get(i + 0) & 0xff;
int g = pixels.get(i + 1) & 0xff;
int b = pixels.get(i + 2) & 0xff;
int a = pixels.get(i + 3) & 0xff;
return (r << 24) | (g << 16) | (b << 8) | (a);
}
/** Draws a pixel at the given location with the current color.
*
* @param x the x-coordinate
* @param y the y-coordinate */
public void drawPixel (int x, int y) {
context.fillRect(x, y, 1, 1);
}
/**
* Draws a pixel at the given location with the current color.
*
* @param x the x-coordinate
* @param y the y-coordinate
*/
public void drawPixel(int x, int y) {
context.fillRect(x, y, 1, 1);
}
/** Draws a pixel at the given location with the given color.
*
* @param x the x-coordinate
* @param y the y-coordinate
* @param color the color in RGBA8888 format. */
public void drawPixel (int x, int y, int color) {
setColor(color);
drawPixel(x, y);
}
/**
* Draws a pixel at the given location with the given color.
*
* @param x the x-coordinate
* @param y the y-coordinate
* @param color the color in RGBA8888 format.
*/
public void drawPixel(int x, int y, int color) {
setColor(color);
drawPixel(x, y);
}
}

View File

@@ -2,9 +2,9 @@ package java.net;
public class MalformedURLException extends Exception {
/**
/**
*
*/
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
}

View File

@@ -1,22 +1,22 @@
package java.net;
public class URL {
@Override
public String toString() {
return mPath;
}
@Override
public String toString() {
return mPath;
}
String mProtocol;
String mHostname;
int mPort;
String mPath;
String mProtocol;
String mHostname;
int mPort;
String mPath;
public URL(String protocol, String hostName, int port, String path) {
//mPath = "http://" +hostName +"/" + path;
mPath = path;
}
public URL(String protocol, String hostName, int port, String path) {
//mPath = "http://" +hostName +"/" + path;
mPath = path;
}
public URL(String path) throws MalformedURLException {
mPath = path;
}
public URL(String path) throws MalformedURLException {
mPath = path;
}
}

View File

@@ -2,9 +2,9 @@ package java.util.concurrent;
public class CancellationException extends IllegalStateException {
/**
*
*/
/**
*
*/
private static final long serialVersionUID = 1L;
}

View File

@@ -4,9 +4,9 @@ import java.util.ArrayList;
public class CopyOnWriteArrayList<E> extends ArrayList<E> {
/**
/**
*
*/
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
}

View File

@@ -1,75 +1,75 @@
package org.oscim.backend;
import org.xml.sax.Attributes;
import com.google.gwt.xml.client.NamedNodeMap;
import com.google.gwt.xml.client.Node;
import org.xml.sax.Attributes;
public class MyAttributes implements Attributes {
private NamedNodeMap map;
private NamedNodeMap map;
public MyAttributes(Node n) {
map = n.getAttributes();
}
public MyAttributes(Node n) {
map = n.getAttributes();
}
public String getValue(int i) {
return map.item(i).getNodeValue();
}
public String getValue(int i) {
return map.item(i).getNodeValue();
}
public int getLength() {
return map.getLength();
}
public int getLength() {
return map.getLength();
}
public String getLocalName(int i) {
return map.item(i).getNodeName();
}
public String getLocalName(int i) {
return map.item(i).getNodeName();
}
public String getValue(String string) {
Node n = map.getNamedItem(string);
if (n == null)
return null;
public String getValue(String string) {
Node n = map.getNamedItem(string);
if (n == null)
return null;
return n.getNodeValue();
}
return n.getNodeValue();
}
@Override
public String getURI(int paramInt) {
return null;
}
@Override
public String getURI(int paramInt) {
return null;
}
@Override
public String getQName(int paramInt) {
return null;
}
@Override
public String getQName(int paramInt) {
return null;
}
@Override
public String getType(int paramInt) {
return null;
}
@Override
public String getType(int paramInt) {
return null;
}
@Override
public int getIndex(String paramString1, String paramString2) {
return 0;
}
@Override
public int getIndex(String paramString1, String paramString2) {
return 0;
}
@Override
public int getIndex(String paramString) {
return 0;
}
@Override
public int getIndex(String paramString) {
return 0;
}
@Override
public String getType(String paramString1, String paramString2) {
return null;
}
@Override
public String getType(String paramString1, String paramString2) {
return null;
}
@Override
public String getType(String paramString) {
return null;
}
@Override
public String getType(String paramString) {
return null;
}
@Override
public String getValue(String paramString1, String paramString2) {
return null;
}
@Override
public String getValue(String paramString1, String paramString2) {
return null;
}
}

View File

@@ -1,61 +1,61 @@
package org.oscim.backend;
import java.io.IOException;
import java.io.InputStream;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.IOException;
import java.io.InputStream;
public class MyXMLReader {
public void parse(InputStream is) throws SAXException {
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
int read;
try {
while ((read = is.read(buf)) >= 0) {
if (read > 0)
sb.append(new String(buf, 0, read));
}
} catch (IOException e) {
e.printStackTrace();
}
public void parse(InputStream is) throws SAXException {
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
int read;
try {
while ((read = is.read(buf)) >= 0) {
if (read > 0)
sb.append(new String(buf, 0, read));
}
} catch (IOException e) {
e.printStackTrace();
}
Document d = XMLParser.parse(sb.toString());
handleElement(d.getFirstChild());
mHandler.endDocument();
}
Document d = XMLParser.parse(sb.toString());
handleElement(d.getFirstChild());
mHandler.endDocument();
}
int level = 0;
int level = 0;
void handleElement(Node n) throws SAXException {
if (n == null) {
return;
}
if (n.getNodeType() == Node.ELEMENT_NODE) {
void handleElement(Node n) throws SAXException {
if (n == null) {
return;
}
if (n.getNodeType() == Node.ELEMENT_NODE) {
String localName = n.getNodeName();
mHandler.startElement(null, localName, null, new MyAttributes(n));
String localName = n.getNodeName();
mHandler.startElement(null, localName, null, new MyAttributes(n));
if (n.hasChildNodes()) {
NodeList l = n.getChildNodes();
for (int i = 0, len = l.getLength(); i < len; i++) {
handleElement(l.item(i));
}
}
mHandler.endElement(null, localName, null);
}
if (n.hasChildNodes()) {
NodeList l = n.getChildNodes();
for (int i = 0, len = l.getLength(); i < len; i++) {
handleElement(l.item(i));
}
}
mHandler.endElement(null, localName, null);
}
}
}
private DefaultHandler mHandler;
private DefaultHandler mHandler;
public void setContentHandler(DefaultHandler handler) {
mHandler = handler;
}
public void setContentHandler(DefaultHandler handler) {
mHandler = handler;
}
}

View File

@@ -1,16 +1,16 @@
package org.oscim.backend;
import java.io.IOException;
import java.io.InputStream;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XMLReaderAdapter {
public void parse(DefaultHandler handler, InputStream is) throws IOException, SAXException {
import java.io.IOException;
import java.io.InputStream;
MyXMLReader xmlReader = new MyXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.parse(is);
}
public class XMLReaderAdapter {
public void parse(DefaultHandler handler, InputStream is) throws IOException, SAXException {
MyXMLReader xmlReader = new MyXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.parse(is);
}
}

View File

@@ -1,29 +1,29 @@
package org.oscim.layers.tile;
import com.badlogic.gdx.Gdx;
import org.oscim.renderer.MapRenderer;
import org.oscim.tiling.ITileDataSink;
import com.badlogic.gdx.Gdx;
public abstract class LoadDelayTask<T> implements Runnable {
protected final MapTile tile;
protected final ITileDataSink sink;
protected final T data;
protected final MapTile tile;
protected final ITileDataSink sink;
protected final T data;
public LoadDelayTask(MapTile tile, ITileDataSink sink, T data) {
this.tile = tile;
this.sink = sink;
this.data = data;
}
public LoadDelayTask(MapTile tile, ITileDataSink sink, T data) {
this.tile = tile;
this.sink = sink;
this.data = data;
}
@Override
public void run() {
if (MapRenderer.frametime == TileLoader.lastLoadTime) {
Gdx.app.postRunnable(this);
return;
}
continueLoading();
}
@Override
public void run() {
if (MapRenderer.frametime == TileLoader.lastLoadTime) {
Gdx.app.postRunnable(this);
return;
}
continueLoading();
}
public abstract void continueLoading();
public abstract void continueLoading();
}

View File

@@ -14,7 +14,8 @@
*/
package org.oscim.layers.tile;
import static org.oscim.tiling.QueryResult.FAILED;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.Timer;
import org.oscim.backend.canvas.Bitmap;
import org.oscim.core.MapElement;
@@ -24,136 +25,135 @@ import org.oscim.tiling.QueryResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.Timer;
import static org.oscim.tiling.QueryResult.FAILED;
public abstract class TileLoader implements ITileDataSink {
final static Logger log = LoggerFactory.getLogger(TileLoader.class);
final static Logger log = LoggerFactory.getLogger(TileLoader.class);
private final TileManager mTileManager;
private Timer mTimer;
private final TileManager mTileManager;
private Timer mTimer;
public TileLoader(TileManager tileManager) {
if (mTimer == null)
mTimer = new Timer();
public TileLoader(TileManager tileManager) {
if (mTimer == null)
mTimer = new Timer();
mTileManager = tileManager;
}
mTileManager = tileManager;
}
public abstract void dispose();
public abstract void dispose();
protected abstract boolean loadTile(MapTile tile);
protected abstract boolean loadTile(MapTile tile);
boolean isInterrupted;
boolean isInterrupted;
public void finish() {
isInterrupted = true;
// cancel loading
}
public void finish() {
isInterrupted = true;
// cancel loading
}
public void cancel() {
isInterrupted = true;
// cancel loading... ?
}
public void cancel() {
isInterrupted = true;
// cancel loading... ?
}
boolean mPausing;
boolean mPausing;
public boolean isCanceled() {
return mPausing;
}
public boolean isCanceled() {
return mPausing;
}
public boolean isPausing() {
return mPausing;
}
public boolean isPausing() {
return mPausing;
}
public void pause() {
mPausing = true;
}
public void pause() {
mPausing = true;
}
public void proceed() {
mPausing = false;
// FIXME
mWorking = false;
if (mTileManager.hasTileJobs())
go();
}
public void proceed() {
mPausing = false;
// FIXME
mWorking = false;
if (mTileManager.hasTileJobs())
go();
}
public void awaitPausing() {
public void awaitPausing() {
}
}
public void start() {
mPausing = false;
}
public void start() {
mPausing = false;
}
protected boolean mWorking;
protected MapTile mTile;
protected boolean mWorking;
protected MapTile mTile;
public void go() {
if (mWorking)
return;
public void go() {
if (mWorking)
return;
mTile = mTileManager.getTileJob();
mTile = mTileManager.getTileJob();
if (mTile == null)
return;
if (mTile == null)
return;
try {
loadTile(mTile);
mWorking = true;
} catch (Exception e) {
e.printStackTrace();
completed(FAILED);
}
}
try {
loadTile(mTile);
mWorking = true;
} catch (Exception e) {
e.printStackTrace();
completed(FAILED);
}
}
public static long lastLoadTime;
public static long lastLoadTime;
/**
* Callback to be called by TileDataSource when finished
* loading or on failure. MUST BE CALLED IN ANY CASE!
*/
@Override
public void completed(QueryResult result) {
long now = MapRenderer.frametime;
/**
* Callback to be called by TileDataSource when finished
* loading or on failure. MUST BE CALLED IN ANY CASE!
*/
@Override
public void completed(QueryResult result) {
long now = MapRenderer.frametime;
//log.debug("completed {} diff time:{}", mTile, (now - lastLoadTime));
lastLoadTime = now;
//log.debug("completed {} diff time:{}", mTile, (now - lastLoadTime));
lastLoadTime = now;
mTileManager.jobCompleted(mTile, result);
mTile = null;
mTileManager.jobCompleted(mTile, result);
mTile = null;
mWorking = false;
mWorking = false;
if (mPausing || !mTileManager.hasTileJobs())
return;
if (mPausing || !mTileManager.hasTileJobs())
return;
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
go();
}
});
}
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
go();
}
});
}
/**
* Called by TileDataSource
*/
@Override
public void process(MapElement element) {
/**
* Called by TileDataSource
*/
@Override
public void process(MapElement element) {
}
}
/**
* Called by TileDataSource
*/
@Override
public void setTileImage(Bitmap bitmap) {
/**
* Called by TileDataSource
*/
@Override
public void setTileImage(Bitmap bitmap) {
}
}
public static void postLoadDelay(LoadDelayTask<?> task) {
Gdx.app.postRunnable(task);
}
public static void postLoadDelay(LoadDelayTask<?> task) {
Gdx.app.postRunnable(task);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -14,116 +14,116 @@
*/
package org.oscim.tiling.source;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.oscim.core.Tile;
import org.oscim.layers.tile.MapTile;
import com.google.gwt.typedarrays.client.Uint8ArrayNative;
import com.google.gwt.typedarrays.shared.Uint8Array;
import com.google.gwt.xhr.client.ReadyStateChangeHandler;
import com.google.gwt.xhr.client.XMLHttpRequest;
import com.google.gwt.xhr.client.XMLHttpRequest.ResponseType;
import org.oscim.core.Tile;
import org.oscim.layers.tile.MapTile;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class LwHttp implements HttpEngine {
//static final Logger log = LoggerFactory.getLogger(LwHttp.class);
//static final Logger log = LoggerFactory.getLogger(LwHttp.class);
private XMLHttpRequest mHttpRequest;
private XMLHttpRequest mHttpRequest;
private ReadyStateChangeHandler mResponseHandler;
private ReadyStateChangeHandler mResponseHandler;
public LwHttp(UrlTileSource tileSource) {
mTileSource = tileSource;
}
public LwHttp(UrlTileSource tileSource) {
mTileSource = tileSource;
}
static class Buffer extends InputStream {
Uint8Array mBuffer;
int mPos;
int mEnd;
static class Buffer extends InputStream {
Uint8Array mBuffer;
int mPos;
int mEnd;
public Buffer(Uint8Array buf) {
mBuffer = buf;
mPos = 0;
mEnd = buf.byteLength();
}
public Buffer(Uint8Array buf) {
mBuffer = buf;
mPos = 0;
mEnd = buf.byteLength();
}
@Override
public synchronized int read() throws IOException {
if (mPos < mEnd)
return mBuffer.get(mPos++);
@Override
public synchronized int read() throws IOException {
if (mPos < mEnd)
return mBuffer.get(mPos++);
return -1;
}
}
return -1;
}
}
public void close() {
if (mHttpRequest == null)
return;
public void close() {
if (mHttpRequest == null)
return;
mHttpRequest.abort();
mHttpRequest = null;
}
mHttpRequest.abort();
mHttpRequest = null;
}
private UrlTileSource mTileSource;
private UrlTileSource mTileSource;
public void sendRequest(MapTile tile, final UrlTileDataSource dataSource) {
public void sendRequest(MapTile tile, final UrlTileDataSource dataSource) {
String url = mTileSource.getTileUrl(tile);
String url = mTileSource.getTileUrl(tile);
mHttpRequest = XMLHttpRequest.create();
mHttpRequest.open("GET", url);
mHttpRequest.setResponseType(ResponseType.ArrayBuffer);
mHttpRequest = XMLHttpRequest.create();
mHttpRequest.open("GET", url);
mHttpRequest.setResponseType(ResponseType.ArrayBuffer);
mResponseHandler = new ReadyStateChangeHandler() {
mResponseHandler = new ReadyStateChangeHandler() {
@Override
public void onReadyStateChange(XMLHttpRequest xhr) {
int state = xhr.getReadyState();
//log.debug(mCurrentUrl + "response " + status + "/" + state);
@Override
public void onReadyStateChange(XMLHttpRequest xhr) {
int state = xhr.getReadyState();
//log.debug(mCurrentUrl + "response " + status + "/" + state);
if (state == XMLHttpRequest.DONE) {
if (xhr.getStatus() == 200) {
Uint8Array buf = Uint8ArrayNative.create(xhr.getResponseArrayBuffer());
dataSource.process(new Buffer(buf));
} else {
dataSource.process(null);
}
mHttpRequest = null;
}
}
};
if (state == XMLHttpRequest.DONE) {
if (xhr.getStatus() == 200) {
Uint8Array buf = Uint8ArrayNative.create(xhr.getResponseArrayBuffer());
dataSource.process(new Buffer(buf));
} else {
dataSource.process(null);
}
mHttpRequest = null;
}
}
};
mHttpRequest.setOnReadyStateChange(mResponseHandler);
mHttpRequest.send();
}
mHttpRequest.setOnReadyStateChange(mResponseHandler);
mHttpRequest.send();
}
public static class LwHttpFactory implements HttpEngine.Factory {
public static class LwHttpFactory implements HttpEngine.Factory {
@Override
public HttpEngine create(UrlTileSource tileSource) {
return new LwHttp(tileSource);
}
}
@Override
public HttpEngine create(UrlTileSource tileSource) {
return new LwHttp(tileSource);
}
}
@Override
public InputStream read() throws IOException {
return null;
}
@Override
public InputStream read() throws IOException {
return null;
}
@Override
public void setCache(OutputStream os) {
}
@Override
public void setCache(OutputStream os) {
}
@Override
public boolean requestCompleted(boolean success) {
// mHttpRequest.clearOnReadyStateChange();
// mHttpRequest = null;
return true;
}
@Override
public boolean requestCompleted(boolean success) {
// mHttpRequest.clearOnReadyStateChange();
// mHttpRequest = null;
return true;
}
@Override
public void sendRequest(Tile tile) throws IOException {
}
@Override
public void sendRequest(Tile tile) throws IOException {
}
}

View File

@@ -14,12 +14,6 @@
*/
package org.oscim.tiling.source;
import static org.oscim.tiling.QueryResult.FAILED;
import static org.oscim.tiling.QueryResult.SUCCESS;
import java.io.IOException;
import java.io.InputStream;
import org.oscim.layers.tile.LoadDelayTask;
import org.oscim.layers.tile.MapTile;
import org.oscim.layers.tile.TileLoader;
@@ -28,69 +22,75 @@ import org.oscim.tiling.ITileDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import static org.oscim.tiling.QueryResult.FAILED;
import static org.oscim.tiling.QueryResult.SUCCESS;
public class UrlTileDataSource implements ITileDataSource {
static final Logger log = LoggerFactory.getLogger(UrlTileDataSource.class);
static final Logger log = LoggerFactory.getLogger(UrlTileDataSource.class);
protected final LwHttp mConn;
protected final ITileDecoder mTileDecoder;
protected final UrlTileSource mTileSource;
protected final LwHttp mConn;
protected final ITileDecoder mTileDecoder;
protected final UrlTileSource mTileSource;
private ITileDataSink mSink;
private MapTile mTile;
private ITileDataSink mSink;
private MapTile mTile;
public UrlTileDataSource(UrlTileSource tileSource, ITileDecoder tileDecoder, HttpEngine conn) {
mTileSource = tileSource;
mTileDecoder = tileDecoder;
mConn = (LwHttp) conn;
}
public UrlTileDataSource(UrlTileSource tileSource, ITileDecoder tileDecoder, HttpEngine conn) {
mTileSource = tileSource;
mTileDecoder = tileDecoder;
mConn = (LwHttp) conn;
}
@Override
public void query(MapTile tile, ITileDataSink sink) {
mTile = tile;
mSink = sink;
mConn.sendRequest(tile, this);
}
@Override
public void query(MapTile tile, ITileDataSink sink) {
mTile = tile;
mSink = sink;
mConn.sendRequest(tile, this);
}
public void process(final InputStream is) {
if (is == null) {
log.debug("{} no inputstream", mTile);
mSink.completed(FAILED);
mTile = null;
mSink = null;
return;
}
public void process(final InputStream is) {
if (is == null) {
log.debug("{} no inputstream", mTile);
mSink.completed(FAILED);
mTile = null;
mSink = null;
return;
}
TileLoader.postLoadDelay(new LoadDelayTask<InputStream>(mTile, mSink, is) {
@Override
public void continueLoading() {
boolean win = false;
if (tile.state(MapTile.State.LOADING)) {
try {
win = mTileDecoder.decode(tile, sink, data);
} catch (IOException e) {
e.printStackTrace();
}
}
if (win) {
sink.completed(SUCCESS);
} else {
sink.completed(FAILED);
log.debug("{} decode failed", tile);
}
}
});
mTile = null;
mSink = null;
}
TileLoader.postLoadDelay(new LoadDelayTask<InputStream>(mTile, mSink, is) {
@Override
public void continueLoading() {
boolean win = false;
if (tile.state(MapTile.State.LOADING)) {
try {
win = mTileDecoder.decode(tile, sink, data);
} catch (IOException e) {
e.printStackTrace();
}
}
if (win) {
sink.completed(SUCCESS);
} else {
sink.completed(FAILED);
log.debug("{} decode failed", tile);
}
}
});
mTile = null;
mSink = null;
}
@Override
public void dispose() {
mConn.close();
}
@Override
public void dispose() {
mConn.close();
}
@Override
public void cancel() {
mConn.close();
}
@Override
public void cancel() {
mConn.close();
}
}

View File

@@ -1,5 +1,14 @@
package org.oscim.tiling.source.bitmap;
import com.google.gwt.event.dom.client.ErrorEvent;
import com.google.gwt.event.dom.client.ErrorHandler;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.safehtml.shared.SafeUri;
import com.google.gwt.safehtml.shared.UriUtils;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.RootPanel;
import org.oscim.gdx.client.GwtBitmap;
import org.oscim.layers.tile.LoadDelayTask;
import org.oscim.layers.tile.MapTile;
@@ -12,126 +21,117 @@ import org.oscim.tiling.source.UrlTileSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gwt.event.dom.client.ErrorEvent;
import com.google.gwt.event.dom.client.ErrorHandler;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.safehtml.shared.SafeUri;
import com.google.gwt.safehtml.shared.UriUtils;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.RootPanel;
public class BitmapTileSource extends UrlTileSource {
static final Logger log = LoggerFactory.getLogger(LwHttp.class);
static final Logger log = LoggerFactory.getLogger(LwHttp.class);
public static class Builder<T extends Builder<T>> extends UrlTileSource.Builder<T> {
public static class Builder<T extends Builder<T>> extends UrlTileSource.Builder<T> {
public Builder() {
super(null, "/{Z}/{X}/{Y}.png", 0, 17);
}
public Builder() {
super(null, "/{Z}/{X}/{Y}.png", 0, 17);
}
public BitmapTileSource build() {
return new BitmapTileSource(this);
}
}
public BitmapTileSource build() {
return new BitmapTileSource(this);
}
}
protected BitmapTileSource(Builder<?> builder) {
super(builder);
}
protected BitmapTileSource(Builder<?> builder) {
super(builder);
}
@SuppressWarnings("rawtypes")
public static Builder<?> builder() {
return new Builder();
}
@SuppressWarnings("rawtypes")
public static Builder<?> builder() {
return new Builder();
}
/**
* Create BitmapTileSource for 'url'
*
* By default path will be formatted as: url/z/x/y.png
* Use e.g. setExtension(".jpg") to overide ending or
* implement getUrlString() for custom formatting.
*/
/**
* Create BitmapTileSource for 'url'
* <p/>
* By default path will be formatted as: url/z/x/y.png
* Use e.g. setExtension(".jpg") to overide ending or
* implement getUrlString() for custom formatting.
*/
public BitmapTileSource(String url, int zoomMin, int zoomMax) {
super(url, "/{Z}/{X}/{Y}.png", zoomMin, zoomMax);
}
public BitmapTileSource(String url, int zoomMin, int zoomMax) {
super(url, "/{Z}/{X}/{Y}.png", zoomMin, zoomMax);
}
public BitmapTileSource(String url, int zoomMin, int zoomMax, String extension) {
super(url, "/{Z}/{X}/{Y}" + extension, zoomMin, zoomMax);
}
public BitmapTileSource(String url, int zoomMin, int zoomMax, String extension) {
super(url, "/{Z}/{X}/{Y}" + extension, zoomMin, zoomMax);
}
public BitmapTileSource(String url, String tilePath, int zoomMin, int zoomMax) {
super(url, tilePath, zoomMin, zoomMax);
}
public BitmapTileSource(String url, String tilePath, int zoomMin, int zoomMax) {
super(url, tilePath, zoomMin, zoomMax);
}
@Override
public ITileDataSource getDataSource() {
return new BitmapTileDataSource(this);
}
@Override
public ITileDataSource getDataSource() {
return new BitmapTileDataSource(this);
}
public class BitmapTileDataSource implements ITileDataSource {
public class BitmapTileDataSource implements ITileDataSource {
protected final UrlTileSource mTileSource;
protected final UrlTileSource mTileSource;
public BitmapTileDataSource(BitmapTileSource bitmapTileSource) {
mTileSource = bitmapTileSource;
}
public BitmapTileDataSource(BitmapTileSource bitmapTileSource) {
mTileSource = bitmapTileSource;
}
@Override
public void query(final MapTile tile, final ITileDataSink sink) {
@Override
public void query(final MapTile tile, final ITileDataSink sink) {
String url = mTileSource.getTileUrl(tile);
String url = mTileSource.getTileUrl(tile);
SafeUri uri = UriUtils.fromTrustedString(url);
SafeUri uri = UriUtils.fromTrustedString(url);
final Image img = new Image();
img.setVisible(false);
final Image img = new Image();
img.setVisible(false);
/* As if researching CORS issues doesnt result in
* enough headache...
* enough headache...
*
* Here are some more special Chrome/Webkit quirks:
* MUST SET CORS BEFORE URL! */
img.getElement().setAttribute("crossorigin", "anonymous");
img.setUrl(uri);
img.getElement().setAttribute("crossorigin", "anonymous");
img.setUrl(uri);
RootPanel.get().add(img);
RootPanel.get().add(img);
img.addLoadHandler(new LoadHandler() {
public void onLoad(LoadEvent event) {
TileLoader.postLoadDelay(new LoadDelayTask<Image>(tile, sink, img) {
img.addLoadHandler(new LoadHandler() {
public void onLoad(LoadEvent event) {
TileLoader.postLoadDelay(new LoadDelayTask<Image>(tile, sink, img) {
@Override
public void continueLoading() {
if (!tile.state(MapTile.State.LOADING)) {
sink.completed(QueryResult.FAILED);
RootPanel.get().remove(data);
} else {
sink.setTileImage(new GwtBitmap(data));
sink.completed(QueryResult.SUCCESS);
}
}
});
}
});
@Override
public void continueLoading() {
if (!tile.state(MapTile.State.LOADING)) {
sink.completed(QueryResult.FAILED);
RootPanel.get().remove(data);
} else {
sink.setTileImage(new GwtBitmap(data));
sink.completed(QueryResult.SUCCESS);
}
}
});
}
});
img.addErrorHandler(new ErrorHandler() {
img.addErrorHandler(new ErrorHandler() {
@Override
public void onError(ErrorEvent event) {
sink.completed(QueryResult.FAILED);
RootPanel.get().remove(img);
}
});
}
@Override
public void onError(ErrorEvent event) {
sink.completed(QueryResult.FAILED);
RootPanel.get().remove(img);
}
});
}
@Override
public void dispose() {
}
@Override
public void dispose() {
}
@Override
public void cancel() {
}
@Override
public void cancel() {
}
}
}
}

View File

@@ -16,8 +16,6 @@
*/
package org.oscim.tiling.source.geojson;
import java.util.Map;
import org.oscim.core.MapElement;
import org.oscim.core.Tag;
import org.oscim.tiling.ITileDataSource;
@@ -26,37 +24,43 @@ import org.oscim.tiling.source.UrlTileSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public abstract class GeoJsonTileSource extends UrlTileSource {
static final Logger log = LoggerFactory.getLogger(GeoJsonTileSource.class);
static final Logger log = LoggerFactory.getLogger(GeoJsonTileSource.class);
public GeoJsonTileSource(String url) {
super(url, "/{Z}/{X}/{Y}.json");
}
public GeoJsonTileSource(String url) {
super(url, "/{Z}/{X}/{Y}.json");
}
@Override
public ITileDataSource getDataSource() {
return new JsonTileDataSource(this);
}
@Override
public ITileDataSource getDataSource() {
return new JsonTileDataSource(this);
}
public Tag getFeatureTag() {
return null;
}
public Tag getFeatureTag() {
return null;
}
/** allow overriding tag handling */
public abstract void decodeTags(MapElement mapElement, Map<String, Object> properties);
/**
* allow overriding tag handling
*/
public abstract void decodeTags(MapElement mapElement, Map<String, Object> properties);
public Tag rewriteTag(String key, Object value) {
public Tag rewriteTag(String key, Object value) {
if (value == null)
return null;
if (value == null)
return null;
String val = (value instanceof String) ? (String) value : String.valueOf(value);
String val = (value instanceof String) ? (String) value : String.valueOf(value);
return new Tag(key, val);
}
return new Tag(key, val);
}
/** modify mapElement before process() */
public void postGeomHook(MapElement mapElement) {
/**
* modify mapElement before process()
*/
public void postGeomHook(MapElement mapElement) {
}
}
}

View File

@@ -25,34 +25,33 @@ import java.util.logging.Level;
*/
public final class IOUtils {
/**
* Invokes the {@link Closeable#close()} method on the given object. If an
* {@link IOException} occurs during the
* method call, it will be caught and logged on level {@link Level#WARNING}.
*
* @param closeable
* the data source which should be closed (may be null).
*/
public static void closeQuietly(OutputStream closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException e) {
//log.debug(e.getMessage() + " " + e);
}
}
/**
* Invokes the {@link Closeable#close()} method on the given object. If an
* {@link IOException} occurs during the
* method call, it will be caught and logged on level {@link Level#WARNING}.
*
* @param closeable the data source which should be closed (may be null).
*/
public static void closeQuietly(OutputStream closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException e) {
//log.debug(e.getMessage() + " " + e);
}
}
public static void closeQuietly(InputStream closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException e) {
//log.debug(e.getMessage() + " " + e);
}
}
public static void closeQuietly(InputStream closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException e) {
//log.debug(e.getMessage() + " " + e);
}
}
private IOUtils() {
}
private IOUtils() {
}
}

View File

@@ -2,72 +2,72 @@ package org.oscim.utils;
public class TessJNI {
public TessJNI() {
public TessJNI() {
}
}
public TessJNI(int size) {
throw new RuntimeException("unimplemented");
}
public TessJNI(int size) {
throw new RuntimeException("unimplemented");
}
public void dispose() {
throw new RuntimeException("unimplemented");
}
public void dispose() {
throw new RuntimeException("unimplemented");
}
public void addContour2D(float[] points) {
throw new RuntimeException("unimplemented");
}
public void addContour2D(float[] points) {
throw new RuntimeException("unimplemented");
}
public void addContour2D(float[] points, int offset, int length) {
throw new RuntimeException("unimplemented");
}
public void addContour2D(float[] points, int offset, int length) {
throw new RuntimeException("unimplemented");
}
public void addContour2D(int[] index, float[] contour) {
throw new RuntimeException("unimplemented");
}
public void addContour2D(int[] index, float[] contour) {
throw new RuntimeException("unimplemented");
}
public void addContour2D(int[] index, float[] contour, int idxStart, int idxEnd) {
throw new RuntimeException("unimplemented");
}
public void addContour2D(int[] index, float[] contour, int idxStart, int idxEnd) {
throw new RuntimeException("unimplemented");
}
public boolean tesselate() {
throw new RuntimeException("unimplemented");
}
public boolean tesselate() {
throw new RuntimeException("unimplemented");
}
public boolean tesselate(int windingRule, int elementType) {
throw new RuntimeException("unimplemented");
}
public boolean tesselate(int windingRule, int elementType) {
throw new RuntimeException("unimplemented");
}
public int getVertexCount() {
throw new RuntimeException("unimplemented");
}
public int getVertexCount() {
throw new RuntimeException("unimplemented");
}
public int getElementCount() {
throw new RuntimeException("unimplemented");
}
public int getElementCount() {
throw new RuntimeException("unimplemented");
}
public void getVertices(float[] out, int offset, int length) {
throw new RuntimeException("unimplemented");
}
public void getVertices(float[] out, int offset, int length) {
throw new RuntimeException("unimplemented");
}
public void getVertices(short[] out, int offset, int length, float scale) {
throw new RuntimeException("unimplemented");
}
public void getVertices(short[] out, int offset, int length, float scale) {
throw new RuntimeException("unimplemented");
}
public void getElements(int[] out, int offset, int length) {
throw new RuntimeException("unimplemented");
}
public void getElements(int[] out, int offset, int length) {
throw new RuntimeException("unimplemented");
}
public void getElements(short[] out, int offset, int length) {
throw new RuntimeException("unimplemented");
}
public void getElements(short[] out, int offset, int length) {
throw new RuntimeException("unimplemented");
}
public void getVertexIndices(int[] out, int offset, int length) {
throw new RuntimeException("unimplemented");
}
public void getVertexIndices(int[] out, int offset, int length) {
throw new RuntimeException("unimplemented");
}
public void getElementsWithInputVertexIds(short[] dst, int dstOffset, int offset, int length) {
throw new RuntimeException("unimplemented");
}
public void getElementsWithInputVertexIds(short[] dst, int dstOffset, int offset, int length) {
throw new RuntimeException("unimplemented");
}
}

View File

@@ -1,10 +1,5 @@
package org.oscim.utils;
import org.oscim.core.GeometryBuffer;
import org.oscim.renderer.bucket.VertexData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gwt.core.client.JavaScriptException;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArrayInteger;
@@ -13,179 +8,184 @@ import com.google.gwt.core.client.JsArrayUtils;
import com.google.gwt.typedarrays.shared.Float32Array;
import com.google.gwt.typedarrays.shared.Int32Array;
import org.oscim.core.GeometryBuffer;
import org.oscim.renderer.bucket.VertexData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Tessellator {
static final Logger log = LoggerFactory.getLogger(Tessellator.class);
static final Logger log = LoggerFactory.getLogger(Tessellator.class);
public static int tessellate(GeometryBuffer geom, float scale,
VertexData outPoints, VertexData outTris, int vertexOffset) {
public static int tessellate(GeometryBuffer geom, float scale,
VertexData outPoints, VertexData outTris, int vertexOffset) {
int numIndices = 0;
int indexPos = 0;
int pointPos = 0;
int indexEnd = geom.index.length;
int numIndices = 0;
int indexPos = 0;
int pointPos = 0;
int indexEnd = geom.index.length;
JsArrayNumber jspoints = JsArrayUtils.readOnlyJsArray(geom.points);
JsArrayInteger jsindex = JsArrayUtils.readOnlyJsArray(geom.index);
JsArrayNumber jspoints = JsArrayUtils.readOnlyJsArray(geom.points);
JsArrayInteger jsindex = JsArrayUtils.readOnlyJsArray(geom.index);
for (int idx = 0; idx < indexEnd && geom.index[idx] > 0; idx++) {
indexPos = idx;
for (int idx = 0; idx < indexEnd && geom.index[idx] > 0; idx++) {
indexPos = idx;
int numRings = 1;
int numPoints = geom.index[idx++];
int numRings = 1;
int numPoints = geom.index[idx++];
for (; idx < indexEnd && geom.index[idx] > 0; idx++) {
numRings++;
numPoints += geom.index[idx];
}
for (; idx < indexEnd && geom.index[idx] > 0; idx++) {
numRings++;
numPoints += geom.index[idx];
}
if (numPoints <= 0 && numRings == 1) {
log.debug("tessellation skip empty");
pointPos += numPoints;
continue;
}
if (numPoints <= 0 && numRings == 1) {
log.debug("tessellation skip empty");
pointPos += numPoints;
continue;
}
TessResult res;
try {
res = tessellate2(jspoints, pointPos, numPoints,
jsindex, indexPos, numRings);
} catch (JavaScriptException e) {
e.printStackTrace();
return 0;
}
pointPos += numPoints;
TessResult res;
try {
res = tessellate2(jspoints, pointPos, numPoints,
jsindex, indexPos, numRings);
} catch (JavaScriptException e) {
e.printStackTrace();
return 0;
}
pointPos += numPoints;
if (res == null) {
log.debug("tessellation failed");
continue;
}
if (res == null) {
log.debug("tessellation failed");
continue;
}
Int32Array io = res.getIndices(res);
int resIndices = io.length();
numIndices += resIndices;
Int32Array io = res.getIndices(res);
int resIndices = io.length();
numIndices += resIndices;
for (int k = 0, cnt = 0; k < resIndices; k += cnt) {
VertexData.Chunk chunk = outTris.obtainChunk();
for (int k = 0, cnt = 0; k < resIndices; k += cnt) {
VertexData.Chunk chunk = outTris.obtainChunk();
cnt = VertexData.SIZE - chunk.used;
cnt = VertexData.SIZE - chunk.used;
if (k + cnt > resIndices)
cnt = resIndices - k;
if (k + cnt > resIndices)
cnt = resIndices - k;
for (int i = 0; i < cnt; i++)
chunk.vertices[chunk.used + i] =
(short) (vertexOffset + io.get(k + i));
for (int i = 0; i < cnt; i++)
chunk.vertices[chunk.used + i] =
(short) (vertexOffset + io.get(k + i));
chunk.used += cnt;
outTris.releaseChunk();
}
chunk.used += cnt;
outTris.releaseChunk();
}
Float32Array po = res.getPoints(res);
int resPoints = po.length();
Float32Array po = res.getPoints(res);
int resPoints = po.length();
vertexOffset += (resPoints >> 1);
vertexOffset += (resPoints >> 1);
for (int k = 0, cnt = 0; k < resPoints; k += cnt) {
VertexData.Chunk chunk = outPoints.obtainChunk();
for (int k = 0, cnt = 0; k < resPoints; k += cnt) {
VertexData.Chunk chunk = outPoints.obtainChunk();
cnt = VertexData.SIZE - chunk.used;
cnt = VertexData.SIZE - chunk.used;
if (k + cnt > resPoints)
cnt = resPoints - k;
if (k + cnt > resPoints)
cnt = resPoints - k;
for (int i = 0; i < cnt; i++)
chunk.vertices[chunk.used + i] =
(short) (po.get(k + i) * scale);
for (int i = 0; i < cnt; i++)
chunk.vertices[chunk.used + i] =
(short) (po.get(k + i) * scale);
chunk.used += cnt;
outPoints.releaseChunk();
}
chunk.used += cnt;
outPoints.releaseChunk();
}
if (idx >= indexEnd || geom.index[idx] < 0)
break;
}
if (idx >= indexEnd || geom.index[idx] < 0)
break;
}
return numIndices;
}
return numIndices;
}
public static int tessellate(float[] points, int ppos, int plen, int[] index,
int ipos, int rings, int vertexOffset, VertexData outTris) {
public static int tessellate(float[] points, int ppos, int plen, int[] index,
int ipos, int rings, int vertexOffset, VertexData outTris) {
Int32Array io;
try {
io = tessellate(JsArrayUtils.readOnlyJsArray(points), ppos, plen,
JsArrayUtils.readOnlyJsArray(index), ipos, rings);
} catch (JavaScriptException e) {
e.printStackTrace();
return 0;
}
Int32Array io;
try {
io = tessellate(JsArrayUtils.readOnlyJsArray(points), ppos, plen,
JsArrayUtils.readOnlyJsArray(index), ipos, rings);
} catch (JavaScriptException e) {
e.printStackTrace();
return 0;
}
if (io == null) {
//log.debug("building tessellation failed");
return 0;
}
if (io == null) {
//log.debug("building tessellation failed");
return 0;
}
// if (vo.length() != plen) {
// // TODO handle different output points
// log.debug(" + io.length());
//
// //for (int i = 0; i < vo.length(); i += 2)
// // log.debug(vo.get(i) + " " + vo.get(i + 1));
// //for (int i = ppos; i < ppos + plen; i += 2)
// // log.debug( points[i]+ " " + points[i + 1]);
//
// return 0;
// }
// if (vo.length() != plen) {
// // TODO handle different output points
// log.debug(" + io.length());
//
// //for (int i = 0; i < vo.length(); i += 2)
// // log.debug(vo.get(i) + " " + vo.get(i + 1));
// //for (int i = ppos; i < ppos + plen; i += 2)
// // log.debug( points[i]+ " " + points[i + 1]);
//
// return 0;
// }
int numIndices = io.length();
int numIndices = io.length();
for (int k = 0, cnt = 0; k < numIndices; k += cnt) {
VertexData.Chunk chunk = outTris.obtainChunk();
for (int k = 0, cnt = 0; k < numIndices; k += cnt) {
VertexData.Chunk chunk = outTris.obtainChunk();
cnt = VertexData.SIZE - chunk.used;
cnt = VertexData.SIZE - chunk.used;
if (k + cnt > numIndices)
cnt = numIndices - k;
if (k + cnt > numIndices)
cnt = numIndices - k;
for (int i = 0; i < cnt; i++) {
int idx = (vertexOffset + io.get(k + i));
chunk.vertices[chunk.used + i] = (short) idx;
}
chunk.used += cnt;
outTris.releaseChunk();
}
for (int i = 0; i < cnt; i++) {
int idx = (vertexOffset + io.get(k + i));
chunk.vertices[chunk.used + i] = (short) idx;
}
chunk.used += cnt;
outTris.releaseChunk();
}
return numIndices;
}
return numIndices;
}
public static int tessellate(GeometryBuffer geom, GeometryBuffer out) {
return 0;
}
public static int tessellate(GeometryBuffer geom, GeometryBuffer out) {
return 0;
}
static native Int32Array tessellate(JsArrayNumber points, int pOffset, int pLength,
JsArrayInteger bounds, int bOffset, int bLength)/*-{
static native Int32Array tessellate(JsArrayNumber points, int pOffset, int pLength,
JsArrayInteger bounds, int bOffset, int bLength)/*-{
return $wnd.tessellate(points, pOffset, pOffset + pLength, bounds,
bOffset, bOffset + bLength, false);
}-*/;
static native TessResult tessellate2(JsArrayNumber points, int pOffset, int pLength,
JsArrayInteger bounds, int bOffset, int bLength)
/*-{
static native TessResult tessellate2(JsArrayNumber points, int pOffset, int pLength,
JsArrayInteger bounds, int bOffset, int bLength)
/*-{
return $wnd.tessellate(points, pOffset, pOffset + pLength, bounds,
bOffset, bOffset + bLength, true);
}-*/;
static final class TessResult extends JavaScriptObject {
protected TessResult() {
}
static final class TessResult extends JavaScriptObject {
protected TessResult() {
}
native Float32Array getPoints(JavaScriptObject result)/*-{
return result.vertices;
native Float32Array getPoints(JavaScriptObject result)/*-{
return result.vertices;
}-*/;
native Int32Array getIndices(JavaScriptObject result)/*-{
native Int32Array getIndices(JavaScriptObject result)/*-{
return result.triangles;
}-*/;
}
}
}

View File

@@ -2,15 +2,15 @@ package org.oscim.utils;
public class ThreadUtils {
public static void assertMainThread() {
}
public static void assertMainThread() {
}
public static boolean isMainThread() {
return true;
}
public static boolean isMainThread() {
return true;
}
public static void init() {
public static void init() {
}
}
}

View File

@@ -5,46 +5,45 @@ import com.badlogic.gdx.utils.Disposable;
/**
* GWT emulation of AsynchExecutor, will call tasks immediately :D
*
*
* @author badlogic
*
*/
public class AsyncExecutor implements Disposable {
private final TaskQueue mainloop;
private final TaskQueue mainloop;
/**
* Creates a new AsynchExecutor that allows maxConcurrent {@link Runnable}
* instances to run in parallel.
*
* @param maxConcurrent
*/
public AsyncExecutor(int maxConcurrent, TaskQueue mainloop) {
this.mainloop = mainloop;
}
/**
* Creates a new AsynchExecutor that allows maxConcurrent {@link Runnable}
* instances to run in parallel.
*
* @param maxConcurrent
*/
public AsyncExecutor(int maxConcurrent, TaskQueue mainloop) {
this.mainloop = mainloop;
}
/**
* Submits a {@link Runnable} to be executed asynchronously. If
* maxConcurrent runnables are already running, the runnable
* will be queued.
*
* @param task the task to execute asynchronously
*/
public boolean post(Runnable task) {
if (task instanceof AsyncTask) {
((AsyncTask) task).setTaskQueue(mainloop);
}
/**
* Submits a {@link Runnable} to be executed asynchronously. If
* maxConcurrent runnables are already running, the runnable
* will be queued.
*
* @param task the task to execute asynchronously
*/
public boolean post(Runnable task) {
if (task instanceof AsyncTask) {
((AsyncTask) task).setTaskQueue(mainloop);
}
Gdx.app.postRunnable(task);
Gdx.app.postRunnable(task);
return true;
}
return true;
}
/**
* Waits for running {@link AsyncTask} instances to finish,
* then destroys any resources like threads. Can not be used
* after this method is called.
*/
@Override
public void dispose() {
}
/**
* Waits for running {@link AsyncTask} instances to finish,
* then destroys any resources like threads. Can not be used
* after this method is called.
*/
@Override
public void dispose() {
}
}

View File

@@ -1,27 +1,27 @@
package org.xml.sax;
public abstract interface Attributes {
public abstract int getLength();
public abstract int getLength();
public abstract String getURI(int paramInt);
public abstract String getURI(int paramInt);
public abstract String getLocalName(int paramInt);
public abstract String getLocalName(int paramInt);
public abstract String getQName(int paramInt);
public abstract String getQName(int paramInt);
public abstract String getType(int paramInt);
public abstract String getType(int paramInt);
public abstract String getValue(int paramInt);
public abstract String getValue(int paramInt);
public abstract int getIndex(String paramString1, String paramString2);
public abstract int getIndex(String paramString1, String paramString2);
public abstract int getIndex(String paramString);
public abstract int getIndex(String paramString);
public abstract String getType(String paramString1, String paramString2);
public abstract String getType(String paramString1, String paramString2);
public abstract String getType(String paramString);
public abstract String getType(String paramString);
public abstract String getValue(String paramString1, String paramString2);
public abstract String getValue(String paramString1, String paramString2);
public abstract String getValue(String paramString);
public abstract String getValue(String paramString);
}

View File

@@ -4,17 +4,16 @@ import java.io.IOException;
public class SAXException extends IOException {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
private static final long serialVersionUID = 1L;
public SAXException(String str) {
super(str);
}
public SAXException(String str) {
super(str);
}
public SAXException(String str, Throwable throwable)
{
super(str);
}
public SAXException(String str, Throwable throwable) {
super(str);
}
}

View File

@@ -2,18 +2,17 @@ package org.xml.sax;
public class SAXParseException extends SAXException {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
private static final long serialVersionUID = 1L;
public SAXParseException(String str) {
super(str);
}
public SAXParseException(String str) {
super(str);
}
public SAXParseException(String str, Throwable throwable)
{
super(str);
}
public SAXParseException(String str, Throwable throwable) {
super(str);
}
}

View File

@@ -5,25 +5,25 @@ import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DefaultHandler {
public void endDocument() {
public void endDocument() {
}
}
public void error(SAXParseException exception) {
public void error(SAXParseException exception) {
}
}
public void warning(SAXParseException exception) {
public void warning(SAXParseException exception) {
}
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
}
}
public void endElement(String uri, String localName, String qName) {
public void endElement(String uri, String localName, String qName) {
}
}
}

View File

@@ -16,10 +16,10 @@
*/
package org.oscim.tiling.source;
import static org.oscim.tiling.QueryResult.FAILED;
import static org.oscim.tiling.QueryResult.SUCCESS;
import java.io.InputStream;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.jsonp.client.JsonpRequest;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import org.oscim.layers.tile.MapTile;
import org.oscim.layers.tile.MapTile.State;
@@ -30,95 +30,95 @@ import org.oscim.tiling.source.geojson.GeoJsonTileSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.jsonp.client.JsonpRequest;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import java.io.InputStream;
import static org.oscim.tiling.QueryResult.FAILED;
import static org.oscim.tiling.QueryResult.SUCCESS;
public class JsonTileDataSource implements ITileDataSource {
static final Logger log = LoggerFactory.getLogger(JsonTileDataSource.class);
static final Logger log = LoggerFactory.getLogger(JsonTileDataSource.class);
protected final GeoJsonTileDecoder mTileDecoder;
protected final UrlTileSource mTileSource;
protected final GeoJsonTileDecoder mTileDecoder;
protected final UrlTileSource mTileSource;
public JsonTileDataSource(GeoJsonTileSource tileSource) {
mTileSource = tileSource;
mTileDecoder = new GeoJsonTileDecoder(tileSource);
}
public JsonTileDataSource(GeoJsonTileSource tileSource) {
mTileSource = tileSource;
mTileDecoder = new GeoJsonTileDecoder(tileSource);
}
UrlTileSource getTileSource() {
return mTileSource;
}
UrlTileSource getTileSource() {
return mTileSource;
}
private ITileDataSink mSink;
private MapTile mTile;
private ITileDataSink mSink;
private MapTile mTile;
@Override
public void query(MapTile tile, ITileDataSink sink) {
mTile = tile;
mSink = sink;
@Override
public void query(MapTile tile, ITileDataSink sink) {
mTile = tile;
mSink = sink;
try {
doGet(mTileSource.getTileUrl(tile));
} catch (Exception e) {
e.printStackTrace();
sink.completed(FAILED);
}
}
try {
doGet(mTileSource.getTileUrl(tile));
} catch (Exception e) {
e.printStackTrace();
sink.completed(FAILED);
}
}
public void process(InputStream is) {
}
public void process(InputStream is) {
}
boolean mFinished;
boolean mFinished;
@Override
public void dispose() {
mFinished = true;
}
@Override
public void dispose() {
mFinished = true;
}
@Override
public void cancel() {
mFinished = true;
}
@Override
public void cancel() {
mFinished = true;
}
JsonpRequest<JavaScriptObject> mRequestHandle;
JsonpRequest<JavaScriptObject> mRequestHandle;
void doGet(final String url) {
JsonpRequestBuilder builder = new JsonpRequestBuilder();
//builder.setCallbackParam("json_callback");
void doGet(final String url) {
JsonpRequestBuilder builder = new JsonpRequestBuilder();
//builder.setCallbackParam("json_callback");
mRequestHandle = builder.requestObject(url, new AsyncCallback<JavaScriptObject>() {
public void onFailure(Throwable caught) {
mRequestHandle = builder.requestObject(url, new AsyncCallback<JavaScriptObject>() {
public void onFailure(Throwable caught) {
mSink.completed(FAILED);
log.debug("fail! {} {}", mRequestHandle, caught.getMessage());
//mRequestHandle.cancel();
}
mSink.completed(FAILED);
log.debug("fail! {} {}", mRequestHandle, caught.getMessage());
//mRequestHandle.cancel();
}
public void onSuccess(JavaScriptObject jso) {
if (mTile.state(State.NONE)) {
log.debug("tile cleared {}", url);
mSink.completed(FAILED);
return;
}
public void onSuccess(JavaScriptObject jso) {
if (mTile.state(State.NONE)) {
log.debug("tile cleared {}", url);
mSink.completed(FAILED);
return;
}
if (jso == null) {
log.debug("Couldn't retrieve JSON for {}", url);
mSink.completed(FAILED);
return;
}
if (jso == null) {
log.debug("Couldn't retrieve JSON for {}", url);
mSink.completed(FAILED);
return;
}
try {
if (mTileDecoder.decode(mTile, mSink, jso)) {
mSink.completed(SUCCESS);
return;
}
} catch (Exception e) {
log.debug("Couldn't retrieve JSON for {} {}" + url, e);
// FIXME need to check where it might be thrown
mSink.completed(FAILED);
}
}
});
}
try {
if (mTileDecoder.decode(mTile, mSink, jso)) {
mSink.completed(SUCCESS);
return;
}
} catch (Exception e) {
log.debug("Couldn't retrieve JSON for {} {}" + url, e);
// FIXME need to check where it might be thrown
mSink.completed(FAILED);
}
}
});
}
}

View File

@@ -21,30 +21,30 @@ import java.util.Map;
public class Feature extends GeoJsonObject {
protected Feature() {
protected Feature() {
}
}
public final native Geometry<?> getGeometry() /*-{
return this.geometry;
public final native Geometry<?> getGeometry() /*-{
return this.geometry;
}-*/;
public final native String getId() /*-{
return this.id;
public final native String getId() /*-{
return this.id;
}-*/;
public final native void setId(String id) /*-{
public final native void setId(String id) /*-{
this.id = id;
}-*/;
public final Map<String, Object> getProperties(HashMap<String, Object> map) {
map.clear();
fromJavascriptObject(map);
public final Map<String, Object> getProperties(HashMap<String, Object> map) {
map.clear();
fromJavascriptObject(map);
return map;
}
return map;
}
public final native void fromJavascriptObject(HashMap<String, Object> s) /*-{
public final native void fromJavascriptObject(HashMap<String, Object> s) /*-{
for(var key in this.properties) {
s.@java.util.HashMap::put(Ljava/lang/Object;Ljava/lang/Object;)(key, Object(this.properties[key]));
}

View File

@@ -16,23 +16,23 @@
*/
package org.oscim.tiling.source.geojson;
import java.util.Collection;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import java.util.Collection;
public class FeatureCollection extends JavaScriptObject {
protected FeatureCollection() {
protected FeatureCollection() {
}
}
public final Collection<Feature> getFeatures() {
return new JsArrayCollection<Feature>(getFeaturesInternal());
}
public final Collection<Feature> getFeatures() {
return new JsArrayCollection<Feature>(getFeaturesInternal());
}
public final native JsArray<Feature> getFeaturesInternal()/*-{
return this.features;
public final native JsArray<Feature> getFeaturesInternal()/*-{
return this.features;
}-*/;
}

View File

@@ -20,15 +20,15 @@ import com.google.gwt.core.client.JavaScriptObject;
public abstract class GeoJsonObject extends JavaScriptObject {
protected GeoJsonObject() {
protected GeoJsonObject() {
}
}
public final native double[] getBbox()/*-{
return bbox;
public final native double[] getBbox()/*-{
return bbox;
}-*/;
public final native void setBbox(double[] bbox) /*-{
this.bbox = bbox;
public final native void setBbox(double[] bbox) /*-{
this.bbox = bbox;
}-*/;
}

View File

@@ -16,12 +16,7 @@
*/
package org.oscim.tiling.source.geojson;
import static org.oscim.core.MercatorProjection.latitudeToY;
import static org.oscim.core.MercatorProjection.longitudeToX;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import com.google.gwt.core.client.JavaScriptObject;
import org.oscim.core.GeometryBuffer.GeometryType;
import org.oscim.core.MapElement;
@@ -31,109 +26,114 @@ import org.oscim.tiling.source.ITileDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gwt.core.client.JavaScriptObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import static org.oscim.core.MercatorProjection.latitudeToY;
import static org.oscim.core.MercatorProjection.longitudeToX;
public class GeoJsonTileDecoder implements ITileDecoder {
static final Logger log = LoggerFactory.getLogger(GeoJsonTileDecoder.class);
static final Logger log = LoggerFactory.getLogger(GeoJsonTileDecoder.class);
private final MapElement mapElement;
private final GeoJsonTileSource mTileSource;
private final MapElement mapElement;
private final GeoJsonTileSource mTileSource;
private ITileDataSink mTileDataSink;
private ITileDataSink mTileDataSink;
public GeoJsonTileDecoder(GeoJsonTileSource tileSource) {
mTileSource = tileSource;
mapElement = new MapElement();
mapElement.layer = 5;
}
public GeoJsonTileDecoder(GeoJsonTileSource tileSource) {
mTileSource = tileSource;
mapElement = new MapElement();
mapElement.layer = 5;
}
final static LinkedHashMap<String, Object> mProperties = new LinkedHashMap<String, Object>(10);
final static LinkedHashMap<String, Object> mProperties = new LinkedHashMap<String, Object>(10);
double mTileY, mTileX, mTileScale;
double mTileY, mTileX, mTileScale;
public boolean decode(Tile tile, ITileDataSink sink, JavaScriptObject jso) {
mTileDataSink = sink;
public boolean decode(Tile tile, ITileDataSink sink, JavaScriptObject jso) {
mTileDataSink = sink;
mTileScale = 1 << tile.zoomLevel;
mTileX = tile.tileX / mTileScale;
mTileY = tile.tileY / mTileScale;
mTileScale *= Tile.SIZE;
mTileScale = 1 << tile.zoomLevel;
mTileX = tile.tileX / mTileScale;
mTileY = tile.tileY / mTileScale;
mTileScale *= Tile.SIZE;
FeatureCollection c = (FeatureCollection) jso;
FeatureCollection c = (FeatureCollection) jso;
for (Feature f : c.getFeatures()) {
mapElement.clear();
mapElement.tags.clear();
for (Feature f : c.getFeatures()) {
mapElement.clear();
mapElement.tags.clear();
/* add tag information */
mTileSource.decodeTags(mapElement, f.getProperties(mProperties));
if (mapElement.tags.numTags == 0)
continue;
mTileSource.decodeTags(mapElement, f.getProperties(mProperties));
if (mapElement.tags.numTags == 0)
continue;
/* add geometry information */
decodeGeometry(f.getGeometry());
decodeGeometry(f.getGeometry());
if (mapElement.type == GeometryType.NONE)
continue;
if (mapElement.type == GeometryType.NONE)
continue;
mTileDataSink.process(mapElement);
}
mTileDataSink.process(mapElement);
}
return true;
}
return true;
}
private void decodeGeometry(Geometry<?> geometry) {
String type = geometry.type();
private void decodeGeometry(Geometry<?> geometry) {
String type = geometry.type();
if ("Polygon".equals(type)) {
Polygon p = (Polygon) geometry.getCoordinates();
decodePolygon(p);
} else if ("MultiPolygon".equals(type)) {
MultiPolygon mp = (MultiPolygon) geometry.getCoordinates();
for (int k = 0, l = mp.getNumGeometries(); k < l; k++)
decodePolygon(mp.getGeometryN(k));
if ("Polygon".equals(type)) {
Polygon p = (Polygon) geometry.getCoordinates();
decodePolygon(p);
} else if ("MultiPolygon".equals(type)) {
MultiPolygon mp = (MultiPolygon) geometry.getCoordinates();
for (int k = 0, l = mp.getNumGeometries(); k < l; k++)
decodePolygon(mp.getGeometryN(k));
} else if ("LineString".equals(type)) {
LineString ls = (LineString) geometry.getCoordinates();
decodeLineString(ls);
} else if ("LineString".equals(type)) {
LineString ls = (LineString) geometry.getCoordinates();
decodeLineString(ls);
} else if ("MultiLineString".equals(type)) {
MultiLineString ml = (MultiLineString) geometry.getCoordinates();
for (int k = 0, n = ml.getNumGeometries(); k < n; k++)
decodeLineString(ml.getGeometryN(k));
}
}
} else if ("MultiLineString".equals(type)) {
MultiLineString ml = (MultiLineString) geometry.getCoordinates();
for (int k = 0, n = ml.getNumGeometries(); k < n; k++)
decodeLineString(ml.getGeometryN(k));
}
}
private void decodeLineString(LineString l) {
mapElement.startLine();
for (int j = 0, m = l.length(); j < m; j++) {
decodePoint(l.get(j));
}
}
private void decodeLineString(LineString l) {
mapElement.startLine();
for (int j = 0, m = l.length(); j < m; j++) {
decodePoint(l.get(j));
}
}
private void decodePolygon(Polygon p) {
for (int i = 0, n = p.getNumRings(); i < n; i++) {
if (i > 0)
mapElement.startHole();
else
mapElement.startPolygon();
private void decodePolygon(Polygon p) {
for (int i = 0, n = p.getNumRings(); i < n; i++) {
if (i > 0)
mapElement.startHole();
else
mapElement.startPolygon();
LineString ls = p.getRing(i);
for (int j = 0, m = ls.length() - 1; j < m; j++)
decodePoint(ls.get(j));
}
}
LineString ls = p.getRing(i);
for (int j = 0, m = ls.length() - 1; j < m; j++)
decodePoint(ls.get(j));
}
}
private void decodePoint(LngLat point) {
private void decodePoint(LngLat point) {
float x = (float) ((longitudeToX(point.getLongitude()) - mTileX) * mTileScale);
float y = (float) ((latitudeToY(point.getLatitude()) - mTileY) * mTileScale);
float x = (float) ((longitudeToX(point.getLongitude()) - mTileX) * mTileScale);
float y = (float) ((latitudeToY(point.getLatitude()) - mTileY) * mTileScale);
mapElement.addPoint(x, y);
}
mapElement.addPoint(x, y);
}
@Override
public boolean decode(Tile tile, ITileDataSink sink, InputStream is) throws IOException {
return false;
}
@Override
public boolean decode(Tile tile, ITileDataSink sink, InputStream is) throws IOException {
return false;
}
}

View File

@@ -21,15 +21,15 @@ import com.google.gwt.core.client.JsArray;
public abstract class Geometry<T extends JavaScriptObject> extends JsArray<T> {
protected Geometry() {
protected Geometry() {
}
}
public final native String type()/*-{
return this.type
public final native String type()/*-{
return this.type
}-*/;
public final native JsArray<T> getCoordinates() /*-{
return this.coordinates;
public final native JsArray<T> getCoordinates() /*-{
return this.coordinates;
}-*/;
}

View File

@@ -1,100 +1,101 @@
package org.oscim.tiling.source.geojson;
import com.google.gwt.core.client.JavaScriptObject;
import java.util.AbstractCollection;
import java.util.Iterator;
import com.google.gwt.core.client.JavaScriptObject;
/**
* a Java Friendly way of working with Js Arrays using the Java.util.Collection
* API
* https://groups.google.com/forum/#!topic/google-web-toolkit/_8X9WPL6qwM
*
* @author sg
*
*
* @param <T>
* @author sg
*/
public class JsArrayCollection<T> extends AbstractCollection<T> {
private JsArr<T> _data;
private JsArr<T> _data;
/**
* creates an empty array
*/
public JsArrayCollection() {
_data = JsArr.create().cast();
}
/**
* creates an empty array
*/
public JsArrayCollection() {
_data = JsArr.create().cast();
}
/**
* creates JsArrayCollection wrapping an existing js array
*/
public JsArrayCollection(JavaScriptObject data) {
this._data = data.cast();
}
/**
* creates JsArrayCollection wrapping an existing js array
*/
public JsArrayCollection(JavaScriptObject data) {
this._data = data.cast();
}
public static <T> JsArrayCollection<T> create(JavaScriptObject data) {
return new JsArrayCollection<T>(data);
}
public static <T> JsArrayCollection<T> create(JavaScriptObject data) {
return new JsArrayCollection<T>(data);
}
@Override
public Iterator<T> iterator() {
return new JsArrayIterator<T>(this);
}
@Override
public Iterator<T> iterator() {
return new JsArrayIterator<T>(this);
}
@Override
public int size() {
return _data.size();
}
@Override
public int size() {
return _data.size();
}
public static class JsArrayIterator<T> implements Iterator<T> {
public static class JsArrayIterator<T> implements Iterator<T> {
private JsArrayCollection<T> arr;
int currentIndex;
private JsArrayCollection<T> arr;
int currentIndex;
public JsArrayIterator(JsArrayCollection<T> arr) {
this.arr = arr;
currentIndex = 0;
}
public JsArrayIterator(JsArrayCollection<T> arr) {
this.arr = arr;
currentIndex = 0;
}
@Override
public boolean hasNext() {
// System.out.println(currentIndex+" - "+arr.size());
return currentIndex < arr.size();
}
@Override
public boolean hasNext() {
// System.out.println(currentIndex+" - "+arr.size());
return currentIndex < arr.size();
}
@Override
public T next() {
currentIndex++;
return arr._data.get(currentIndex - 1);
}
@Override
public T next() {
currentIndex++;
return arr._data.get(currentIndex - 1);
}
@Override
public void remove() {
arr._data.slice(currentIndex - 1, currentIndex);
}
@Override
public void remove() {
arr._data.slice(currentIndex - 1, currentIndex);
}
}
}
/** untyped array */
private static class JsArr<T> extends JavaScriptObject {
protected JsArr() {
}
/**
* untyped array
*/
private static class JsArr<T> extends JavaScriptObject {
protected JsArr() {
}
public native final JsArr<T> slice(int start, int end)/*-{
return this.slice(start, end);
public native final JsArr<T> slice(int start, int end)/*-{
return this.slice(start, end);
}-*/;
public static final native <T> JsArr<T> create() /*-{
return [];
public static final native <T> JsArr<T> create() /*-{
return [];
}-*/;
public final native int size() /*-{
public final native int size() /*-{
return this.length;
}-*/;
public final native T get(int i) /*-{
public final native T get(int i) /*-{
return this[i];
}-*/;
}
}
}

View File

@@ -18,6 +18,6 @@ package org.oscim.tiling.source.geojson;
public class LineString extends Geometry<LngLat> {
protected LineString() {
}
protected LineString() {
}
}

View File

@@ -4,15 +4,15 @@ import com.google.gwt.core.client.JavaScriptObject;
public class LngLat extends JavaScriptObject {
protected LngLat() {
protected LngLat() {
}
}
public final native double getLongitude() /*-{
return this[0];
public final native double getLongitude() /*-{
return this[0];
}-*/;
public final native double getLatitude() /*-{
return this[1];
public final native double getLatitude() /*-{
return this[1];
}-*/;
}

View File

@@ -18,15 +18,15 @@ package org.oscim.tiling.source.geojson;
public class MultiLineString extends Geometry<LineString> {
protected MultiLineString() {
}
protected MultiLineString() {
}
public final native LineString getGeometryN(int i) /*-{
return this[i];
public final native LineString getGeometryN(int i) /*-{
return this[i];
}-*/;
public final native int getNumGeometries() /*-{
return this.length;
public final native int getNumGeometries() /*-{
return this.length;
}-*/;
}

View File

@@ -18,15 +18,15 @@ package org.oscim.tiling.source.geojson;
public class MultiPolygon extends Geometry<Polygon> {
protected MultiPolygon() {
}
protected MultiPolygon() {
}
public final native Polygon getGeometryN(int i) /*-{
return this[i];
public final native Polygon getGeometryN(int i) /*-{
return this[i];
}-*/;
public final native int getNumGeometries() /*-{
return this.length;
public final native int getNumGeometries() /*-{
return this.length;
}-*/;
}

View File

@@ -18,18 +18,18 @@ package org.oscim.tiling.source.geojson;
public class Polygon extends Geometry<LineString> {
protected Polygon() {
}
protected Polygon() {
}
public final native LineString getExteriorRing()/*-{
return this[0];
public final native LineString getExteriorRing()/*-{
return this[0];
}-*/;
public final native LineString getRing(int i) /*-{
return this[i];
public final native LineString getRing(int i) /*-{
return this[i];
}-*/;
public final native int getNumRings() /*-{
public final native int getNumRings() /*-{
return this.length;
}-*/;