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,6 +0,0 @@
#!/bin/bash
export PATH=$PATH:$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools
echo yes | android update sdk --filter platform-tools --no-ui
echo yes | android update sdk --filter android-21 --no-ui
echo yes | android update sdk --filter extra-android-support --no-ui
echo yes | android update sdk --filter extra-android-m2repository --no-ui

View File

@@ -1,14 +1,14 @@
eclipse.preferences.version=1 eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6 org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6 org.eclipse.jdt.core.compiler.source=1.7
org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=82 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=82
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0
@@ -282,7 +282,7 @@ org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false
org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1
org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false
org.eclipse.jdt.core.formatter.tabulation.char=tab org.eclipse.jdt.core.formatter.tabulation.char=space
org.eclipse.jdt.core.formatter.tabulation.size=4 org.eclipse.jdt.core.formatter.tabulation.size=4
org.eclipse.jdt.core.formatter.use_on_off_tags=false org.eclipse.jdt.core.formatter.use_on_off_tags=false
org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=true org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=true

View File

@@ -1,72 +0,0 @@
def prj = { project ->
"(jde-project-file-version" (["1.0"])
"(jde-set-variables" {
"'(jde-compile-option-directory" ([project.sourceSets.main.output.classesDir])
"'(jde-junit-working-directory" ([project.projectDir])
"'(jde-compile-option-source" {
"'(" (["default"])
}
"'(jde-compile-option-target" {
"'(" (["default"])
}
"'(jde-compile-option-command-line-args" {
"'(" (["-${project.sourceCompatibility}"])
}
"'(jde-sourcepath" {
"'(" (
project.sourceSets.main.allSource.srcDirs
+ project.sourceSets.test.allSource.srcDirs)
}
"'(jde-global-classpath" {
"'(" (
[] + project.sourceSets.main.output.classesDir
+ project.sourceSets.test.output.classesDir
+ project.sourceSets.main.allSource.srcDirs
+ project.sourceSets.test.allSource.srcDirs
+ (([] as Set) + project.configurations.compile.getFiles()
+ project.configurations.testCompile.getFiles()))
}
}
}
subprojects {
task("jdee") << {
def output = new File(project.projectDir, "prj.el").newPrintWriter()
try {
prj.delegate = new NodeBuilder() {
def lev = 0
def write = { Object file ->
output.print '\n' + ''.padRight(lev, ' ') + "\"${file}\"".tr('\\', '/')
}
Object createNode(Object name) {
output.print '\n' + ''.padRight(lev++, ' ') + name
return name
}
Object createNode(Object name, Object value) {
createNode(name)
value.each write
return name
}
void nodeCompleted(Object parent, Object child) {
output.print ")"
lev--
}
}
prj(project)
output.close()
} finally {
output.flush()
}
}
}

View File

@@ -1,274 +1,278 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://opensciencemap.org/rendertheme" <xs:schema xmlns:tns="http://opensciencemap.org/rendertheme"
xmlns:tns="http://opensciencemap.org/rendertheme" elementFormDefault="qualified" xml:lang="en"> xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
<!-- attribute types --> targetNamespace="http://opensciencemap.org/rendertheme" xml:lang="en">
<xs:simpleType name="cap"> <!-- attribute types -->
<xs:restriction base="xs:string"> <xs:simpleType name="cap">
<xs:enumeration value="butt" /> <xs:restriction base="xs:string">
<xs:enumeration value="round" /> <xs:enumeration value="butt" />
<xs:enumeration value="square" /> <xs:enumeration value="round" />
</xs:restriction> <xs:enumeration value="square" />
</xs:simpleType> </xs:restriction>
</xs:simpleType>
<xs:simpleType name="closed"> <xs:simpleType name="closed">
<xs:restriction base="xs:string"> <xs:restriction base="xs:string">
<xs:enumeration value="yes" /> <xs:enumeration value="yes" />
<xs:enumeration value="no" /> <xs:enumeration value="no" />
<xs:enumeration value="any" /> <xs:enumeration value="any" />
</xs:restriction> </xs:restriction>
</xs:simpleType> </xs:simpleType>
<xs:simpleType name="color"> <xs:simpleType name="color">
<xs:restriction base="xs:string"> <xs:restriction base="xs:string">
<xs:pattern value="#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})" /> <xs:pattern value="#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})" />
</xs:restriction> </xs:restriction>
</xs:simpleType> </xs:simpleType>
<xs:simpleType name="elementList"> <xs:simpleType name="elementList">
<xs:restriction base="xs:string"> <xs:restriction base="xs:string">
<xs:enumeration value="node" /> <xs:enumeration value="node" />
<xs:enumeration value="way" /> <xs:enumeration value="way" />
<xs:enumeration value="any" /> <xs:enumeration value="any" />
</xs:restriction> </xs:restriction>
</xs:simpleType> </xs:simpleType>
<xs:simpleType name="selectorList"> <xs:simpleType name="selectorList">
<xs:restriction base="xs:string"> <xs:restriction base="xs:string">
<xs:enumeration value="first" /> <xs:enumeration value="first" />
<xs:enumeration value="any" /> <xs:enumeration value="any" />
<xs:enumeration value="when-matched" /> <xs:enumeration value="when-matched" />
</xs:restriction> </xs:restriction>
</xs:simpleType> </xs:simpleType>
<xs:simpleType name="fontFamily">
<xs:restriction base="xs:string">
<xs:enumeration value="default" />
<xs:enumeration value="default_bold" />
<xs:enumeration value="monospace" />
<xs:enumeration value="sans_serif" />
<xs:enumeration value="serif" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="fontStyle"> <xs:simpleType name="fontFamily">
<xs:restriction base="xs:string"> <xs:restriction base="xs:string">
<xs:enumeration value="bold" /> <xs:enumeration value="default" />
<xs:enumeration value="bold_italic" /> <xs:enumeration value="default_bold" />
<xs:enumeration value="italic" /> <xs:enumeration value="monospace" />
<xs:enumeration value="normal" /> <xs:enumeration value="sans_serif" />
</xs:restriction> <xs:enumeration value="serif" />
</xs:simpleType> </xs:restriction>
</xs:simpleType>
<xs:simpleType name="nonNegativeFloat"> <xs:simpleType name="fontStyle">
<xs:restriction base="xs:float"> <xs:restriction base="xs:string">
<xs:minInclusive value="0" /> <xs:enumeration value="bold" />
</xs:restriction> <xs:enumeration value="bold_italic" />
</xs:simpleType> <xs:enumeration value="italic" />
<xs:enumeration value="normal" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="src"> <xs:simpleType name="nonNegativeFloat">
<xs:restriction base="xs:string"> <xs:restriction base="xs:float">
<!-- <xs:pattern value="(jar|file)\:.+" /> --> <xs:minInclusive value="0" />
<xs:pattern value=".+" /> </xs:restriction>
</xs:restriction> </xs:simpleType>
</xs:simpleType>
<xs:simpleType name="strokeDasharray"> <xs:simpleType name="src">
<xs:restriction base="xs:string"> <xs:restriction base="xs:string">
<xs:pattern value="([0-9]+(\.[0-9]+)? *, *[0-9]+(\.[0-9]+)? *, *)*[0-9]+(\.[0-9]+)? *, *[0-9]+(\.[0-9]+)?" /> <!-- <xs:pattern value="(jar|file)\:.+" /> -->
</xs:restriction> <xs:pattern value=".+" />
</xs:simpleType> </xs:restriction>
</xs:simpleType>
<xs:simpleType name="textKey"> <xs:simpleType name="strokeDasharray">
<xs:restriction base="xs:string"> <xs:restriction base="xs:string">
<xs:enumeration value="ele" /> <xs:pattern
<xs:enumeration value="addr:housenumber" /> value="([0-9]+(\.[0-9]+)? *, *[0-9]+(\.[0-9]+)? *, *)*[0-9]+(\.[0-9]+)? *, *[0-9]+(\.[0-9]+)?" />
<xs:enumeration value="name" /> </xs:restriction>
<xs:enumeration value="ref" /> </xs:simpleType>
</xs:restriction>
</xs:simpleType>
<!-- rendering instructions --> <xs:simpleType name="textKey">
<xs:complexType name="area"> <xs:restriction base="xs:string">
<xs:attribute name="id" type="xs:string" use="optional" default="0" /> <xs:enumeration value="ele" />
<xs:attribute name="use" type="xs:string" use="optional" default="0" /> <xs:enumeration value="addr:housenumber" />
<xs:attribute name="src" type="tns:src" use="optional" /> <xs:enumeration value="name" />
<xs:attribute name="fill" type="tns:color" use="optional" default="#000000" /> <xs:enumeration value="ref" />
<xs:attribute name="stroke" type="tns:color" use="optional" default="#00000000" /> </xs:restriction>
<xs:attribute name="stroke-width" type="tns:nonNegativeFloat" use="optional" default="0" /> </xs:simpleType>
<xs:attribute name="fade" type="xs:integer" use="optional" default="-1" />
<xs:attribute name="blend" type="xs:integer" use="optional" default="-1" />
<xs:attribute name="blend-fill" type="tns:color" use="optional" default="#000000" />
<xs:attribute name="mesh" type="xs:boolean" use="optional" default="false" />
</xs:complexType>
<xs:complexType name="caption"> <!-- rendering instructions -->
<xs:attribute name="k" type="tns:textKey" use="required" /> <xs:complexType name="area">
<xs:attribute name="dy" type="xs:float" use="optional" default="0" /> <xs:attribute name="id" default="0" type="xs:string" use="optional" />
<xs:attribute name="font-family" type="tns:fontFamily" use="optional" default="default" /> <xs:attribute name="use" default="0" type="xs:string" use="optional" />
<xs:attribute name="style" type="tns:fontStyle" use="optional" default="normal" /> <xs:attribute name="src" type="tns:src" use="optional" />
<xs:attribute name="size" type="tns:nonNegativeFloat" use="optional" default="0" /> <xs:attribute name="fill" default="#000000" type="tns:color" use="optional" />
<xs:attribute name="fill" type="tns:color" use="optional" default="#000000" /> <xs:attribute name="stroke" default="#00000000" type="tns:color" use="optional" />
<xs:attribute name="stroke" type="tns:color" use="optional" default="#000000" /> <xs:attribute name="stroke-width" default="0" type="tns:nonNegativeFloat" use="optional" />
<xs:attribute name="stroke-width" type="tns:nonNegativeFloat" use="optional" default="0" /> <xs:attribute name="fade" default="-1" type="xs:integer" use="optional" />
<!-- priority for label placement, 0 = highest priority --> <xs:attribute name="blend" default="-1" type="xs:integer" use="optional" />
<xs:attribute name="priority" type="xs:integer" use="optional" default="0" /> <xs:attribute name="blend-fill" default="#000000" type="tns:color" use="optional" />
<xs:attribute name="mesh" default="false" type="xs:boolean" use="optional" />
<!-- symbol src name in atlas -->
<xs:attribute name="symbol" type="tns:src" use="optional" />
</xs:complexType>
<xs:complexType name="circle">
<xs:attribute name="radius" type="tns:nonNegativeFloat" use="required" />
<xs:attribute name="scale-radius" type="xs:boolean" use="optional" default="false" />
<xs:attribute name="fill" type="tns:color" use="optional" default="#00000000" />
<xs:attribute name="stroke" type="tns:color" use="optional" default="#00000000" />
<xs:attribute name="stroke-width" type="tns:nonNegativeFloat" use="optional" default="0" />
</xs:complexType>
<xs:complexType name="line">
<!-- style: TODO only in style-line-->
<xs:attribute name="id" type="xs:string" use="optional" default="0" />
<!-- inherited style -->
<xs:attribute name="use" type="xs:string" use="optional" default="0" />
<xs:attribute name="src" type="tns:src" use="optional" />
<xs:attribute name="stroke" type="tns:color" use="optional" default="#000000" />
<xs:attribute name="width" type="xs:float" use="optional" default="0" />
<!-- minimum scaled width to draw outline -->
<xs:attribute name="min" type="xs:float" use="optional" default="0" />
<xs:attribute name="dasharray" type="tns:strokeDasharray" use="optional" />
<xs:attribute name="cap" type="tns:cap" use="optional" default="round" />
<xs:attribute name="outline" type="xs:string" use="optional" default="" />
<xs:attribute name="fade" type="xs:integer" use="optional" default="-1" />
<xs:attribute name="blur" type="xs:float" use="optional" default="-1" />
<xs:attribute name="fix" type="xs:boolean" use="optional" default="false" />
<!-- stipple repeat in 'pixel' -->
<xs:attribute name="stipple" type="xs:integer" use="optional" default="0" />
<!-- stipple color -->
<xs:attribute name="stipple-stroke" type="tns:color" use="optional" default="#000000" />
<!-- stipple width relative to line width, i.e 0.0-1.0 -->
<xs:attribute name="stipple-width" type="xs:float" use="optional" default="0" />
</xs:complexType>
<!-- <xs:complexType name="outline">
<xs:attribute name="name" type="xs:string" use="optional"
default="0" />
<xs:attribute name="src" type="tns:src" use="optional" />
<xs:attribute name="stroke" type="tns:color" use="optional"
default="#000000" />
<xs:attribute name="stroke-width" type="tns:nonNegativeFloat"
use="optional" default="0" />
</xs:complexType> </xs:complexType>
-->
<xs:complexType name="lineSymbol">
<xs:attribute name="src" type="tns:src" use="required" />
<xs:attribute name="align-center" type="xs:boolean" use="optional" default="false" />
<xs:attribute name="repeat" type="xs:boolean" use="optional" default="false" />
</xs:complexType>
<xs:complexType name="text"> <xs:complexType name="caption">
<xs:attribute name="id" type="xs:string" use="optional" default="0" /> <xs:attribute name="k" type="tns:textKey" use="required" />
<xs:attribute name="use" type="xs:string" use="optional" default="0" /> <xs:attribute name="dy" default="0" type="xs:float" use="optional" />
<xs:attribute name="font-family" default="default" type="tns:fontFamily" use="optional" />
<xs:attribute name="style" default="normal" type="tns:fontStyle" use="optional" />
<xs:attribute name="size" default="0" type="tns:nonNegativeFloat" use="optional" />
<xs:attribute name="fill" default="#000000" type="tns:color" use="optional" />
<xs:attribute name="stroke" default="#000000" type="tns:color" use="optional" />
<xs:attribute name="stroke-width" default="0" type="tns:nonNegativeFloat" use="optional" />
<!-- priority for label placement, 0 = highest priority -->
<xs:attribute name="priority" default="0" type="xs:integer" use="optional" />
<xs:attribute name="k" type="tns:textKey" use="optional" default="name" /> <!-- symbol src name in atlas -->
<xs:attribute name="dy" type="xs:float" use="optional" default="0" /> <xs:attribute name="symbol" type="tns:src" use="optional" />
<xs:attribute name="font-family" type="tns:fontFamily" use="optional" default="default" /> </xs:complexType>
<xs:attribute name="style" type="tns:fontStyle" use="optional" default="normal" />
<xs:attribute name="size" type="tns:nonNegativeFloat" use="optional" default="0" />
<xs:attribute name="fill" type="tns:color" use="optional" default="#000000" />
<xs:attribute name="stroke" type="tns:color" use="optional" default="#000000" />
<xs:attribute name="stroke-width" type="tns:nonNegativeFloat" use="optional" default="0" />
<xs:attribute name="caption" type="xs:boolean" use="optional" default="false" />
<!-- priority for label placement, 0 = highest priority -->
<xs:attribute name="priority" type="xs:integer" use="optional" default="0" />
</xs:complexType>
<xs:complexType name="symbol"> <xs:complexType name="circle">
<xs:attribute name="src" type="tns:src" use="required" /> <xs:attribute name="radius" type="tns:nonNegativeFloat" use="required" />
</xs:complexType> <xs:attribute name="scale-radius" default="false" type="xs:boolean" use="optional" />
<xs:attribute name="fill" default="#00000000" type="tns:color" use="optional" />
<xs:attribute name="stroke" default="#00000000" type="tns:color" use="optional" />
<xs:attribute name="stroke-width" default="0" type="tns:nonNegativeFloat" use="optional" />
</xs:complexType>
<xs:complexType name="extrusion"> <xs:complexType name="line">
<xs:attribute name="line-color" type="tns:color" use="optional" /> <!-- style: TODO only in style-line-->
<xs:attribute name="side-color" type="tns:color" use="required" /> <xs:attribute name="id" default="0" type="xs:string" use="optional" />
<xs:attribute name="top-color" type="tns:color" use="required" />
</xs:complexType> <!-- inherited style -->
<xs:attribute name="use" default="0" type="xs:string" use="optional" />
<xs:attribute name="src" type="tns:src" use="optional" />
<xs:attribute name="stroke" default="#000000" type="tns:color" use="optional" />
<xs:attribute name="width" default="0" type="xs:float" use="optional" />
<!-- minimum scaled width to draw outline -->
<xs:attribute name="min" default="0" type="xs:float" use="optional" />
<xs:attribute name="dasharray" type="tns:strokeDasharray" use="optional" />
<xs:attribute name="cap" default="round" type="tns:cap" use="optional" />
<xs:attribute name="outline" default="" type="xs:string" use="optional" />
<xs:attribute name="fade" default="-1" type="xs:integer" use="optional" />
<xs:attribute name="blur" default="-1" type="xs:float" use="optional" />
<xs:attribute name="fix" default="false" type="xs:boolean" use="optional" />
<!-- stipple repeat in 'pixel' -->
<xs:attribute name="stipple" default="0" type="xs:integer" use="optional" />
<!-- stipple color -->
<xs:attribute name="stipple-stroke" default="#000000" type="tns:color" use="optional" />
<!-- stipple width relative to line width, i.e 0.0-1.0 -->
<xs:attribute name="stipple-width" default="0" type="xs:float" use="optional" />
</xs:complexType>
<!-- <xs:complexType name="outline">
<xs:attribute name="name" type="xs:string" use="optional"
default="0" />
<xs:attribute name="src" type="tns:src" use="optional" />
<xs:attribute name="stroke" type="tns:color" use="optional"
default="#000000" />
<xs:attribute name="stroke-width" type="tns:nonNegativeFloat"
use="optional" default="0" />
</xs:complexType>
-->
<xs:complexType name="lineSymbol">
<xs:attribute name="src" type="tns:src" use="required" />
<xs:attribute name="align-center" default="false" type="xs:boolean" use="optional" />
<xs:attribute name="repeat" default="false" type="xs:boolean" use="optional" />
</xs:complexType>
<xs:complexType name="text">
<xs:attribute name="id" default="0" type="xs:string" use="optional" />
<xs:attribute name="use" default="0" type="xs:string" use="optional" />
<xs:attribute name="k" default="name" type="tns:textKey" use="optional" />
<xs:attribute name="dy" default="0" type="xs:float" use="optional" />
<xs:attribute name="font-family" default="default" type="tns:fontFamily" use="optional" />
<xs:attribute name="style" default="normal" type="tns:fontStyle" use="optional" />
<xs:attribute name="size" default="0" type="tns:nonNegativeFloat" use="optional" />
<xs:attribute name="fill" default="#000000" type="tns:color" use="optional" />
<xs:attribute name="stroke" default="#000000" type="tns:color" use="optional" />
<xs:attribute name="stroke-width" default="0" type="tns:nonNegativeFloat" use="optional" />
<xs:attribute name="caption" default="false" type="xs:boolean" use="optional" />
<!-- priority for label placement, 0 = highest priority -->
<xs:attribute name="priority" default="0" type="xs:integer" use="optional" />
</xs:complexType>
<xs:complexType name="symbol">
<xs:attribute name="src" type="tns:src" use="required" />
</xs:complexType>
<xs:complexType name="extrusion">
<xs:attribute name="line-color" type="tns:color" use="optional" />
<xs:attribute name="side-color" type="tns:color" use="required" />
<xs:attribute name="top-color" type="tns:color" use="required" />
</xs:complexType>
<!-- match elements --> <!-- match elements -->
<xs:complexType name="m"> <xs:complexType name="m">
<xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:choice maxOccurs="unbounded" minOccurs="0">
<!-- recursion to allow for nested m --> <!-- recursion to allow for nested m -->
<xs:element name="m" type="tns:m" /> <xs:element name="m" type="tns:m" />
<xs:element name="area" type="tns:area" /> <xs:element name="area" type="tns:area" />
<xs:element name="caption" type="tns:caption" /> <xs:element name="caption" type="tns:caption" />
<xs:element name="circle" type="tns:circle" /> <xs:element name="circle" type="tns:circle" />
<xs:element name="line" type="tns:line" /> <xs:element name="line" type="tns:line" />
<xs:element name="outline" type="tns:line" /> <xs:element name="outline" type="tns:line" />
<xs:element name="lineSymbol" type="tns:lineSymbol" /> <xs:element name="lineSymbol" type="tns:lineSymbol" />
<xs:element name="text" type="tns:text" /> <xs:element name="text" type="tns:text" />
<xs:element name="extrusion" type="tns:extrusion" /> <xs:element name="extrusion" type="tns:extrusion" />
<xs:element name="symbol" type="tns:symbol" /> <xs:element name="symbol" type="tns:symbol" />
<!-- outline is defined within rules to match layering --> <!-- outline is defined within rules to match layering -->
<xs:element name="outline-layer" type="tns:line" /> <xs:element name="outline-layer" type="tns:line" />
</xs:choice>
<xs:attribute name="select" type="tns:selectorList" use="optional" default="any"/>
<xs:attribute name="e" type="tns:elementList" use="optional" />
<xs:attribute name="k" type="xs:string" use="optional" />
<xs:attribute name="v" type="xs:string" use="optional" />
<xs:attribute name="closed" type="tns:closed" use="optional" default="any" />
<xs:attribute name="zoom-min" type="xs:unsignedByte" use="optional" default="0" />
<xs:attribute name="zoom-max" type="xs:unsignedByte" use="optional" default="127" />
</xs:complexType>
<xs:complexType name="atlasRect">
<xs:attribute name="id" type="xs:string" use="required" />
<xs:attribute name="pos" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="atlas">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="rect" type="tns:atlasRect" />
</xs:choice>
<xs:attribute name="img" type="xs:string" use="required" />
</xs:complexType>
<!-- rendertheme element -->
<xs:complexType name="rendertheme">
<xs:sequence minOccurs="0" maxOccurs="1">
<!-- style definitions -->
<xs:sequence minOccurs="0" maxOccurs="256">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="style-text" type="tns:text" />
<xs:element name="style-area" type="tns:area" />
<xs:element name="style-line" type="tns:line" />
<!-- <xs:element name="style-outline" type="tns:line" /> -->
</xs:choice> </xs:choice>
</xs:sequence>
<xs:choice minOccurs="0" maxOccurs="1"> <xs:attribute name="select" default="any" type="tns:selectorList" use="optional" />
<xs:element name="atlas" type="tns:atlas"/> <xs:attribute name="e" type="tns:elementList" use="optional" />
</xs:choice> <xs:attribute name="k" type="xs:string" use="optional" />
<xs:attribute name="v" type="xs:string" use="optional" />
<xs:attribute name="closed" default="any" type="tns:closed" use="optional" />
<xs:attribute name="zoom-min" default="0" type="xs:unsignedByte" use="optional" />
<xs:attribute name="zoom-max" default="127" type="xs:unsignedByte" use="optional" />
<!-- matching rules --> </xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name="m" type="tns:m" /> <xs:complexType name="atlasRect">
</xs:sequence> <xs:attribute name="id" type="xs:string" use="required" />
</xs:sequence> <xs:attribute name="pos" type="xs:string" use="required" />
<xs:attribute name="version" type="xs:positiveInteger" use="required" /> </xs:complexType>
<xs:attribute name="map-background" type="tns:color" use="optional" default="#ffffff" />
<xs:attribute name="base-stroke-width" type="tns:nonNegativeFloat" use="optional" default="1" /> <xs:complexType name="atlas">
<xs:attribute name="base-text-scale" type="tns:nonNegativeFloat" use="optional" default="1" /> <xs:choice maxOccurs="unbounded" minOccurs="0">
</xs:complexType> <xs:element name="rect" type="tns:atlasRect" />
</xs:choice>
<xs:attribute name="img" type="xs:string" use="required" />
</xs:complexType>
<!-- rendertheme element -->
<xs:complexType name="rendertheme">
<xs:sequence maxOccurs="1" minOccurs="0">
<!-- style definitions -->
<xs:sequence maxOccurs="256" minOccurs="0">
<xs:choice maxOccurs="unbounded" minOccurs="0">
<xs:element name="style-text" type="tns:text" />
<xs:element name="style-area" type="tns:area" />
<xs:element name="style-line" type="tns:line" />
<!-- <xs:element name="style-outline" type="tns:line" /> -->
</xs:choice>
</xs:sequence>
<xs:choice maxOccurs="1" minOccurs="0">
<xs:element name="atlas" type="tns:atlas" />
</xs:choice>
<!-- matching rules -->
<xs:sequence maxOccurs="unbounded" minOccurs="0">
<xs:element name="m" type="tns:m" />
</xs:sequence>
</xs:sequence>
<xs:attribute name="version" type="xs:positiveInteger" use="required" />
<xs:attribute name="map-background" default="#ffffff" type="tns:color" use="optional" />
<xs:attribute name="base-stroke-width" default="1" type="tns:nonNegativeFloat"
use="optional" />
<xs:attribute name="base-text-scale" default="1" type="tns:nonNegativeFloat"
use="optional" />
</xs:complexType>
<!-- root element --> <!-- root element -->
<xs:element name="rendertheme" type="tns:rendertheme" /> <xs:element name="rendertheme" type="tns:rendertheme" />
</xs:schema> </xs:schema>

View File

@@ -1,20 +0,0 @@
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

View File

@@ -11,6 +11,4 @@
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target. # Project target.
target=android-21 target=android-23
android.library.reference.1=../vtm-android
android.library.reference.2=../appcompat

View File

@@ -1,4 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/filePickerView" <GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent" android:fadingEdge="vertical" android:id="@+id/filePickerView"
android:fadingEdgeLength="30dip" android:columnWidth="100dip" android:numColumns="auto_fit" /> android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fadingEdge="vertical"
android:fadingEdgeLength="30dip"
android:columnWidth="100dip"
android:numColumns="auto_fit" />

View File

@@ -1,7 +1,6 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" > android:layout_height="match_parent">
<org.oscim.android.MapView <org.oscim.android.MapView
android:id="@+id/mapView" android:id="@+id/mapView"

View File

@@ -1,18 +1,16 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" > android:layout_height="match_parent">
<org.oscim.android.MapView <org.oscim.android.MapView
android:id="@+id/mapView" android:id="@+id/mapView"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent" > android:layout_height="fill_parent"></org.oscim.android.MapView>
</org.oscim.android.MapView>
<LinearLayout <LinearLayout
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:orientation="vertical" > android:orientation="vertical">
<ToggleButton <ToggleButton
android:id="@+id/toggleControls" android:id="@+id/toggleControls"
@@ -31,7 +29,7 @@
android:paddingLeft="10dp" android:paddingLeft="10dp"
android:paddingRight="10dp" android:paddingRight="10dp"
android:paddingTop="10dp" android:paddingTop="10dp"
android:visibility="gone" > android:visibility="gone">
<SeekBar <SeekBar
android:id="@+id/seekBarS" android:id="@+id/seekBarS"
@@ -56,10 +54,10 @@
android:paddingTop="10dp" /> android:paddingTop="10dp" />
<RadioGroup <RadioGroup
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:gravity="center" android:gravity="center"
android:orientation="horizontal" > android:orientation="horizontal">
<RadioButton <RadioButton
android:id="@+id/checkBoxLine" android:id="@+id/checkBoxLine"

View File

@@ -1,7 +1,12 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"> android:layout_width="fill_parent"
<LinearLayout android:layout_height="fill_parent">
android:id="@+id/samples" android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical" android:gravity="center_horizontal" /> <LinearLayout
android:id="@+id/samples"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal" />
</ScrollView> </ScrollView>

View File

@@ -1,13 +1,11 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" > android:layout_height="match_parent">
<org.oscim.android.MapView <org.oscim.android.MapView
android:id="@+id/mapView" android:id="@+id/mapView"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent" > android:layout_height="fill_parent"></org.oscim.android.MapView>
</org.oscim.android.MapView>
<LinearLayout <LinearLayout
android:layout_width="wrap_content" android:layout_width="wrap_content"
@@ -15,7 +13,7 @@
android:layout_alignParentRight="true" android:layout_alignParentRight="true"
android:alpha="0.7" android:alpha="0.7"
android:gravity="center" android:gravity="center"
android:orientation="vertical" > android:orientation="vertical">
<ToggleButton <ToggleButton
android:id="@+id/level7" android:id="@+id/level7"

View File

@@ -1,5 +1,6 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android"> <menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_settings" <item
android:id="@+id/menu_settings"
android:title="@string/menu_settings" android:title="@string/menu_settings"
android:orderInCategory="100" android:orderInCategory="100"
android:showAsAction="never" /> android:showAsAction="never" />

View File

@@ -1,37 +1,32 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" > <menu xmlns:android="http://schemas.android.com/apk/res/android">
<group <group
android:id="@+id/themes" android:id="@+id/themes"
android:checkableBehavior="single" > android:checkableBehavior="single">
<item <item
android:id="@+id/theme_default" android:id="@+id/theme_default"
android:checked="true" android:checked="true"
android:showAsAction="never" android:showAsAction="never"
android:title="@string/theme_default"> android:title="@string/theme_default"></item>
</item>
<item <item
android:id="@+id/theme_tubes" android:id="@+id/theme_tubes"
android:showAsAction="never" android:showAsAction="never"
android:title="@string/theme_tubes"> android:title="@string/theme_tubes"></item>
</item>
<item <item
android:id="@+id/theme_osmarender" android:id="@+id/theme_osmarender"
android:showAsAction="never" android:showAsAction="never"
android:title="@string/theme_osmarender"> android:title="@string/theme_osmarender"></item>
</item>
<item <item
android:id="@+id/theme_newtron" android:id="@+id/theme_newtron"
android:showAsAction="never" android:showAsAction="never"
android:title="@string/theme_newtron"> android:title="@string/theme_newtron"></item>
</item>
</group> </group>
<item <item
android:id="@+id/gridlayer" android:id="@+id/gridlayer"
android:showAsAction="never" android:showAsAction="never"
android:checkable="true" android:checkable="true"
android:title="@string/menu_gridlayer"> android:title="@string/menu_gridlayer"></item>
</item>
</menu> </menu>

View File

@@ -14,13 +14,6 @@
*/ */
package org.oscim.android.filepicker; package org.oscim.android.filepicker;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.Comparator;
import org.oscim.android.test.R;
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.app.Dialog; import android.app.Dialog;
@@ -32,6 +25,13 @@ import android.view.View;
import android.widget.AdapterView; import android.widget.AdapterView;
import android.widget.GridView; import android.widget.GridView;
import org.oscim.android.test.R;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.Comparator;
/** /**
* A FilePicker displays the contents of directories. The user can navigate * A FilePicker displays the contents of directories. The user can navigate
* within the file system and select a single * within the file system and select a single
@@ -40,211 +40,208 @@ import android.widget.GridView;
* {@link #setFileComparator(Comparator)}. By default subfolders and files are * {@link #setFileComparator(Comparator)}. By default subfolders and files are
* grouped and each group is ordered * grouped and each group is ordered
* alphabetically. * alphabetically.
* <p> * <p/>
* A {@link FileFilter} can be activated via * A {@link FileFilter} can be activated via
* {@link #setFileDisplayFilter(FileFilter)} to restrict the displayed files and * {@link #setFileDisplayFilter(FileFilter)} to restrict the displayed files and
* folders. By default all files and folders are visible. * folders. By default all files and folders are visible.
* <p> * <p/>
* Another <code>FileFilter</code> can be applied via * Another <code>FileFilter</code> can be applied via
* {@link #setFileSelectFilter(ValidFileFilter)} to check if a selected file is * {@link #setFileSelectFilter(ValidFileFilter)} to check if a selected file is
* valid before its path is returned. By default all files are considered as * valid before its path is returned. By default all files are considered as
* valid and can be selected. * valid and can be selected.
*/ */
public class FilePicker extends Activity implements AdapterView.OnItemClickListener { public class FilePicker extends Activity implements AdapterView.OnItemClickListener {
/** /**
* The name of the extra data in the result {@link Intent}. * The name of the extra data in the result {@link Intent}.
*/ */
public static final String SELECTED_FILE = "selectedFile"; public static final String SELECTED_FILE = "selectedFile";
private static final String PREFERENCES_FILE = "FilePicker"; private static final String PREFERENCES_FILE = "FilePicker";
private static final String CURRENT_DIRECTORY = "currentDirectory"; private static final String CURRENT_DIRECTORY = "currentDirectory";
private static final String DEFAULT_DIRECTORY = "/"; private static final String DEFAULT_DIRECTORY = "/";
private static final int DIALOG_FILE_INVALID = 0; private static final int DIALOG_FILE_INVALID = 0;
// private static final int DIALOG_FILE_SELECT = 1; // private static final int DIALOG_FILE_SELECT = 1;
protected Comparator<File> mFileComparator = getDefaultFileComparator(); protected Comparator<File> mFileComparator = getDefaultFileComparator();
protected FileFilter mFileDisplayFilter; protected FileFilter mFileDisplayFilter;
protected ValidFileFilter mFileSelectFilter; protected ValidFileFilter mFileSelectFilter;
/** /**
* Sets the file comparator which is used to order the contents of all * Sets the file comparator which is used to order the contents of all
* directories before displaying them. If set to * directories before displaying them. If set to
* null, subfolders and files will not be ordered. * null, subfolders and files will not be ordered.
* *
* @param fileComparator * @param fileComparator the file comparator (may be null).
* the file comparator (may be null). */
*/ public void setFileComparator(Comparator<File> fileComparator) {
public void setFileComparator(Comparator<File> fileComparator) { mFileComparator = fileComparator;
mFileComparator = fileComparator; }
}
/** /**
* Sets the file display filter. This filter is used to determine which * Sets the file display filter. This filter is used to determine which
* files and subfolders of directories will be * files and subfolders of directories will be
* displayed. If set to null, all files and subfolders are shown. * displayed. If set to null, all files and subfolders are shown.
* *
* @param fileDisplayFilter * @param fileDisplayFilter the file display filter (may be null).
* the file display filter (may be null). */
*/ public void setFileDisplayFilter(FileFilter fileDisplayFilter) {
public void setFileDisplayFilter(FileFilter fileDisplayFilter) { mFileDisplayFilter = fileDisplayFilter;
mFileDisplayFilter = fileDisplayFilter; }
}
/** /**
* Sets the file select filter. This filter is used when the user selects a * Sets the file select filter. This filter is used when the user selects a
* file to determine if it is valid. If set * file to determine if it is valid. If set
* to null, all files are considered as valid. * to null, all files are considered as valid.
* *
* @param fileSelectFilter * @param fileSelectFilter the file selection filter (may be null).
* the file selection filter (may be null). */
*/ public void setFileSelectFilter(ValidFileFilter fileSelectFilter) {
public void setFileSelectFilter(ValidFileFilter fileSelectFilter) { mFileSelectFilter = fileSelectFilter;
mFileSelectFilter = fileSelectFilter; }
}
/** /**
* Creates the default file comparator. * Creates the default file comparator.
* *
* @return the default file comparator. * @return the default file comparator.
*/ */
private static Comparator<File> getDefaultFileComparator() { private static Comparator<File> getDefaultFileComparator() {
// order all files by type and alphabetically by name // order all files by type and alphabetically by name
return new Comparator<File>() { return new Comparator<File>() {
@Override @Override
public int compare(File file1, File file2) { public int compare(File file1, File file2) {
if (file1.isDirectory() && !file2.isDirectory()) { if (file1.isDirectory() && !file2.isDirectory()) {
return -1; return -1;
} else if (!file1.isDirectory() && file2.isDirectory()) { } else if (!file1.isDirectory() && file2.isDirectory()) {
return 1; return 1;
} else { } else {
return file1.getName().compareToIgnoreCase(file2.getName()); return file1.getName().compareToIgnoreCase(file2.getName());
} }
} }
}; };
} }
private File mDirectory; private File mDirectory;
private FilePickerIconAdapter mFilePickerIconAdapter; private FilePickerIconAdapter mFilePickerIconAdapter;
private File[] mFiles; private File[] mFiles;
private File[] mFilesWithParentFolder; private File[] mFilesWithParentFolder;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Override @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
File selectedFile = mFiles[(int) id]; File selectedFile = mFiles[(int) id];
if (selectedFile.isDirectory()) { if (selectedFile.isDirectory()) {
mDirectory = selectedFile; mDirectory = selectedFile;
browseToCurrentDirectory(); browseToCurrentDirectory();
} else if (mFileSelectFilter == null || mFileSelectFilter.accept(selectedFile)) { } else if (mFileSelectFilter == null || mFileSelectFilter.accept(selectedFile)) {
setResult(RESULT_OK, setResult(RESULT_OK,
new Intent().putExtra(SELECTED_FILE, selectedFile.getAbsolutePath())); new Intent().putExtra(SELECTED_FILE, selectedFile.getAbsolutePath()));
finish(); finish();
} else { } else {
showDialog(DIALOG_FILE_INVALID); showDialog(DIALOG_FILE_INVALID);
} }
} }
/** /**
* Browses to the current directory. * Browses to the current directory.
*/ */
private void browseToCurrentDirectory() { private void browseToCurrentDirectory() {
setTitle(mDirectory.getAbsolutePath()); setTitle(mDirectory.getAbsolutePath());
// read the subfolders and files from the current directory // read the subfolders and files from the current directory
if (mFileDisplayFilter == null) { if (mFileDisplayFilter == null) {
mFiles = mDirectory.listFiles(); mFiles = mDirectory.listFiles();
} else { } else {
mFiles = mDirectory.listFiles(mFileDisplayFilter); mFiles = mDirectory.listFiles(mFileDisplayFilter);
} }
if (mFiles == null) { if (mFiles == null) {
mFiles = new File[0]; mFiles = new File[0];
} else { } else {
// order the subfolders and files // order the subfolders and files
Arrays.sort(mFiles, mFileComparator); Arrays.sort(mFiles, mFileComparator);
} }
// if a parent directory exists, add it at the first position // if a parent directory exists, add it at the first position
if (mDirectory.getParentFile() != null) { if (mDirectory.getParentFile() != null) {
mFilesWithParentFolder = new File[mFiles.length + 1]; mFilesWithParentFolder = new File[mFiles.length + 1];
mFilesWithParentFolder[0] = mDirectory.getParentFile(); mFilesWithParentFolder[0] = mDirectory.getParentFile();
System.arraycopy(mFiles, 0, mFilesWithParentFolder, 1, System.arraycopy(mFiles, 0, mFilesWithParentFolder, 1,
mFiles.length); mFiles.length);
mFiles = mFilesWithParentFolder; mFiles = mFilesWithParentFolder;
mFilePickerIconAdapter.setFiles(mFiles, true); mFilePickerIconAdapter.setFiles(mFiles, true);
} else { } else {
mFilePickerIconAdapter.setFiles(mFiles, false); mFilePickerIconAdapter.setFiles(mFiles, false);
} }
mFilePickerIconAdapter.notifyDataSetChanged(); mFilePickerIconAdapter.notifyDataSetChanged();
} }
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_picker); setContentView(R.layout.activity_file_picker);
mFilePickerIconAdapter = new FilePickerIconAdapter(this); mFilePickerIconAdapter = new FilePickerIconAdapter(this);
GridView gridView = (GridView) findViewById(R.id.filePickerView); GridView gridView = (GridView) findViewById(R.id.filePickerView);
gridView.setOnItemClickListener(this); gridView.setOnItemClickListener(this);
gridView.setAdapter(mFilePickerIconAdapter); gridView.setAdapter(mFilePickerIconAdapter);
// if (savedInstanceState == null) { // if (savedInstanceState == null) {
// // first start of this instance // // first start of this instance
// showDialog(DIALOG_FILE_SELECT); // showDialog(DIALOG_FILE_SELECT);
// } // }
} }
@Override @Override
protected Dialog onCreateDialog(int id) { protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
switch (id) { switch (id) {
case DIALOG_FILE_INVALID: case DIALOG_FILE_INVALID:
builder.setIcon(android.R.drawable.ic_menu_info_details); builder.setIcon(android.R.drawable.ic_menu_info_details);
builder.setTitle(R.string.error); builder.setTitle(R.string.error);
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(getString(R.string.file_invalid)); stringBuilder.append(getString(R.string.file_invalid));
stringBuilder.append("\n\n"); stringBuilder.append("\n\n");
stringBuilder.append(mFileSelectFilter.getFileOpenResult() stringBuilder.append(mFileSelectFilter.getFileOpenResult()
.getErrorMessage()); .getErrorMessage());
builder.setMessage(stringBuilder.toString()); builder.setMessage(stringBuilder.toString());
builder.setPositiveButton(R.string.ok, null); builder.setPositiveButton(R.string.ok, null);
return builder.create(); return builder.create();
// case DIALOG_FILE_SELECT: // case DIALOG_FILE_SELECT:
// builder.setMessage(R.string.file_select); // builder.setMessage(R.string.file_select);
// builder.setPositiveButton(R.string.ok, null); // builder.setPositiveButton(R.string.ok, null);
// return builder.create(); // return builder.create();
default: default:
// do dialog will be created // do dialog will be created
return null; return null;
} }
} }
@Override @Override
protected void onPause() { protected void onPause() {
super.onPause(); super.onPause();
// save the current directory // save the current directory
Editor editor = getSharedPreferences(PREFERENCES_FILE, MODE_PRIVATE).edit(); Editor editor = getSharedPreferences(PREFERENCES_FILE, MODE_PRIVATE).edit();
editor.clear(); editor.clear();
if (mDirectory != null) { if (mDirectory != null) {
editor.putString(CURRENT_DIRECTORY, mDirectory.getAbsolutePath()); editor.putString(CURRENT_DIRECTORY, mDirectory.getAbsolutePath());
} }
editor.commit(); editor.commit();
} }
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
// restore the current directory // restore the current directory
SharedPreferences preferences = getSharedPreferences(PREFERENCES_FILE, SharedPreferences preferences = getSharedPreferences(PREFERENCES_FILE,
MODE_PRIVATE); MODE_PRIVATE);
mDirectory = new File(preferences.getString(CURRENT_DIRECTORY, mDirectory = new File(preferences.getString(CURRENT_DIRECTORY,
DEFAULT_DIRECTORY)); DEFAULT_DIRECTORY));
if (!mDirectory.exists() || !mDirectory.canRead()) { if (!mDirectory.exists() || !mDirectory.canRead()) {
mDirectory = new File(DEFAULT_DIRECTORY); mDirectory = new File(DEFAULT_DIRECTORY);
} }
browseToCurrentDirectory(); browseToCurrentDirectory();
} }
} }

View File

@@ -14,10 +14,6 @@
*/ */
package org.oscim.android.filepicker; package org.oscim.android.filepicker;
import java.io.File;
import org.oscim.android.test.R;
import android.content.Context; import android.content.Context;
import android.view.Gravity; import android.view.Gravity;
import android.view.View; import android.view.View;
@@ -25,92 +21,93 @@ import android.view.ViewGroup;
import android.widget.BaseAdapter; import android.widget.BaseAdapter;
import android.widget.TextView; import android.widget.TextView;
import org.oscim.android.test.R;
import java.io.File;
/** /**
* An adapter for the FilePicker GridView. * An adapter for the FilePicker GridView.
*/ */
class FilePickerIconAdapter extends BaseAdapter { class FilePickerIconAdapter extends BaseAdapter {
private final Context mContext; private final Context mContext;
private File mCurrentFile; private File mCurrentFile;
private File[] mFiles; private File[] mFiles;
private boolean mHasParentFolder; private boolean mHasParentFolder;
private TextView mTextView; private TextView mTextView;
/** /**
* Creates a new FilePickerIconAdapter with the given context. * Creates a new FilePickerIconAdapter with the given context.
* *
* @param context * @param context the context of this adapter, through which new Views are
* the context of this adapter, through which new Views are * created.
* created. */
*/ FilePickerIconAdapter(Context context) {
FilePickerIconAdapter(Context context) { super();
super(); mContext = context;
mContext = context; }
}
@Override @Override
public int getCount() { public int getCount() {
if (mFiles == null) { if (mFiles == null) {
return 0; return 0;
} }
return mFiles.length; return mFiles.length;
} }
@Override @Override
public Object getItem(int index) { public Object getItem(int index) {
return mFiles[index]; return mFiles[index];
} }
@Override @Override
public long getItemId(int index) { public long getItemId(int index) {
return index; return index;
} }
@Override @Override
public View getView(int index, View convertView, ViewGroup parent) { public View getView(int index, View convertView, ViewGroup parent) {
if (convertView instanceof TextView) { if (convertView instanceof TextView) {
// recycle the old view // recycle the old view
mTextView = (TextView) convertView; mTextView = (TextView) convertView;
} else { } else {
// create a new view object // create a new view object
mTextView = new TextView(mContext); mTextView = new TextView(mContext);
mTextView.setLines(2); mTextView.setLines(2);
mTextView.setGravity(Gravity.CENTER_HORIZONTAL); mTextView.setGravity(Gravity.CENTER_HORIZONTAL);
mTextView.setPadding(5, 10, 5, 10); mTextView.setPadding(5, 10, 5, 10);
} }
if (index == 0 && mHasParentFolder) { if (index == 0 && mHasParentFolder) {
// the parent directory of the current folder // the parent directory of the current folder
mTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.file_picker_back, 0, 0); mTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.file_picker_back, 0, 0);
mTextView.setText(".."); mTextView.setText("..");
} else { } else {
mCurrentFile = mFiles[index]; mCurrentFile = mFiles[index];
if (mCurrentFile.isDirectory()) { if (mCurrentFile.isDirectory()) {
mTextView.setCompoundDrawablesWithIntrinsicBounds(0, mTextView.setCompoundDrawablesWithIntrinsicBounds(0,
R.drawable.file_picker_folder, R.drawable.file_picker_folder,
0, 0,
0); 0);
} else { } else {
mTextView.setCompoundDrawablesWithIntrinsicBounds(0, mTextView.setCompoundDrawablesWithIntrinsicBounds(0,
R.drawable.file_picker_file, R.drawable.file_picker_file,
0, 0,
0); 0);
} }
mTextView.setText(mCurrentFile.getName()); mTextView.setText(mCurrentFile.getName());
} }
return mTextView; return mTextView;
} }
/** /**
* Sets the data of this adapter. * Sets the data of this adapter.
* *
* @param files * @param files the new files for this adapter.
* the new files for this adapter. * @param newHasParentFolder true if the file array has a parent folder at index 0, false
* @param newHasParentFolder * otherwise.
* true if the file array has a parent folder at index 0, false */
* otherwise. void setFiles(File[] files, boolean newHasParentFolder) {
*/ mFiles = files.clone();
void setFiles(File[] files, boolean newHasParentFolder) { mHasParentFolder = newHasParentFolder;
mFiles = files.clone(); }
mHasParentFolder = newHasParentFolder;
}
} }

View File

@@ -22,27 +22,26 @@ import java.io.FileFilter;
* extension. * extension.
*/ */
public class FilterByFileExtension implements FileFilter { public class FilterByFileExtension implements FileFilter {
private final String mExtension; private final String mExtension;
/** /**
* @param extension * @param extension the allowed file name extension.
* the allowed file name extension. */
*/ public FilterByFileExtension(String extension) {
public FilterByFileExtension(String extension) { mExtension = extension;
mExtension = extension; }
}
@Override @Override
public boolean accept(File file) { public boolean accept(File file) {
// accept only readable files // accept only readable files
if (file.canRead()) { if (file.canRead()) {
if (file.isDirectory()) { if (file.isDirectory()) {
// accept all directories // accept all directories
return true; return true;
} else if (file.isFile() && file.getName().endsWith(mExtension)) { } else if (file.isFile() && file.getName().endsWith(mExtension)) {
return true; return true;
} }
} }
return false; return false;
} }
} }

View File

@@ -14,16 +14,16 @@
*/ */
package org.oscim.android.filepicker; package org.oscim.android.filepicker;
import java.io.FileFilter;
import org.oscim.tiling.TileSource.OpenResult; import org.oscim.tiling.TileSource.OpenResult;
import java.io.FileFilter;
/** /**
* An extension of the {@link FileFilter} interface. * An extension of the {@link FileFilter} interface.
*/ */
public interface ValidFileFilter extends FileFilter { public interface ValidFileFilter extends FileFilter {
/** /**
* @return the result of the last {@link #accept} call (might be null). * @return the result of the last {@link #accept} call (might be null).
*/ */
OpenResult getFileOpenResult(); OpenResult getFileOpenResult();
} }

View File

@@ -14,29 +14,29 @@
*/ */
package org.oscim.android.filepicker; package org.oscim.android.filepicker;
import java.io.File;
import org.oscim.tiling.TileSource.OpenResult; import org.oscim.tiling.TileSource.OpenResult;
import org.oscim.tiling.source.mapfile.MapFileTileSource; import org.oscim.tiling.source.mapfile.MapFileTileSource;
import java.io.File;
/** /**
* Accepts all valid map files. * Accepts all valid map files.
*/ */
public final class ValidMapFile implements ValidFileFilter { public final class ValidMapFile implements ValidFileFilter {
private OpenResult mOpenResult; private OpenResult mOpenResult;
@Override @Override
public boolean accept(File file) { public boolean accept(File file) {
MapFileTileSource mapFileSource = new MapFileTileSource(); MapFileTileSource mapFileSource = new MapFileTileSource();
mapFileSource.setMapFile(file.getAbsolutePath()); mapFileSource.setMapFile(file.getAbsolutePath());
this.mOpenResult = mapFileSource.open(); this.mOpenResult = mapFileSource.open();
mapFileSource.close(); mapFileSource.close();
return mOpenResult.isSuccess(); return mOpenResult.isSuccess();
} }
@Override @Override
public OpenResult getFileOpenResult() { public OpenResult getFileOpenResult() {
return mOpenResult; return mOpenResult;
} }
} }

View File

@@ -14,6 +14,12 @@
*/ */
package org.oscim.android.filepicker; package org.oscim.android.filepicker;
import org.oscim.theme.XmlThemeBuilder;
import org.oscim.tiling.TileSource.OpenResult;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
@@ -22,50 +28,44 @@ import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParserFactory;
import org.oscim.theme.XmlThemeBuilder;
import org.oscim.tiling.TileSource.OpenResult;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/** /**
* Accepts all valid render theme XML files. * Accepts all valid render theme XML files.
*/ */
public final class ValidRenderTheme implements ValidFileFilter { public final class ValidRenderTheme implements ValidFileFilter {
private OpenResult mOpenResult; private OpenResult mOpenResult;
@Override @Override
public boolean accept(File file) { public boolean accept(File file) {
InputStream inputStream = null; InputStream inputStream = null;
try { try {
inputStream = new FileInputStream(file); inputStream = new FileInputStream(file);
XmlThemeBuilder renderThemeHandler = new XmlThemeBuilder(); XmlThemeBuilder renderThemeHandler = new XmlThemeBuilder();
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
xmlReader.setContentHandler(renderThemeHandler); xmlReader.setContentHandler(renderThemeHandler);
xmlReader.parse(new InputSource(inputStream)); xmlReader.parse(new InputSource(inputStream));
mOpenResult = OpenResult.SUCCESS; mOpenResult = OpenResult.SUCCESS;
} catch (ParserConfigurationException e) { } catch (ParserConfigurationException e) {
mOpenResult = new OpenResult(e.getMessage()); mOpenResult = new OpenResult(e.getMessage());
} catch (SAXException e) { } catch (SAXException e) {
mOpenResult = new OpenResult(e.getMessage()); mOpenResult = new OpenResult(e.getMessage());
} catch (IOException e) { } catch (IOException e) {
mOpenResult = new OpenResult(e.getMessage()); mOpenResult = new OpenResult(e.getMessage());
} finally { } finally {
try { try {
if (inputStream != null) { if (inputStream != null) {
inputStream.close(); inputStream.close();
} }
} catch (IOException e) { } catch (IOException e) {
mOpenResult = new OpenResult(e.getMessage()); mOpenResult = new OpenResult(e.getMessage());
} }
} }
return mOpenResult.isSuccess(); return mOpenResult.isSuccess();
} }
@Override @Override
public OpenResult getFileOpenResult() { public OpenResult getFileOpenResult() {
return mOpenResult; return mOpenResult;
} }
} }

View File

@@ -16,6 +16,10 @@
*/ */
package org.oscim.android.test; package org.oscim.android.test;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import org.oscim.android.cache.TileCache; import org.oscim.android.cache.TileCache;
import org.oscim.core.MapPosition; import org.oscim.core.MapPosition;
import org.oscim.layers.TileGridLayer; import org.oscim.layers.TileGridLayer;
@@ -26,101 +30,97 @@ import org.oscim.tiling.source.oscimap4.OSciMap4TileSource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class BaseMapActivity extends MapActivity { public class BaseMapActivity extends MapActivity {
static final Logger log = LoggerFactory.getLogger(BaseMapActivity.class); static final Logger log = LoggerFactory.getLogger(BaseMapActivity.class);
final static boolean USE_CACHE = true; final static boolean USE_CACHE = true;
VectorTileLayer mBaseLayer; VectorTileLayer mBaseLayer;
TileSource mTileSource; TileSource mTileSource;
TileGridLayer mGridLayer; TileGridLayer mGridLayer;
private TileCache mCache; private TileCache mCache;
public BaseMapActivity(int contentView) { public BaseMapActivity(int contentView) {
super(contentView); super(contentView);
} }
public BaseMapActivity() { public BaseMapActivity() {
} }
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
mTileSource = new OSciMap4TileSource(); mTileSource = new OSciMap4TileSource();
if (USE_CACHE) { if (USE_CACHE) {
mCache = new TileCache(this, null, "tile.db"); mCache = new TileCache(this, null, "tile.db");
mCache.setCacheSize(512 * (1 << 10)); mCache.setCacheSize(512 * (1 << 10));
mTileSource.setCache(mCache); mTileSource.setCache(mCache);
} }
mBaseLayer = mMap.setBaseMap(mTileSource); mBaseLayer = mMap.setBaseMap(mTileSource);
/* set initial position on first run */ /* set initial position on first run */
MapPosition pos = new MapPosition(); MapPosition pos = new MapPosition();
mMap.getMapPosition(pos); mMap.getMapPosition(pos);
if (pos.x == 0.5 && pos.y == 0.5) if (pos.x == 0.5 && pos.y == 0.5)
mMap.setMapPosition(53.08, 8.83, Math.pow(2, 16)); mMap.setMapPosition(53.08, 8.83, Math.pow(2, 16));
} }
@Override @Override
protected void onDestroy() { protected void onDestroy() {
super.onDestroy(); super.onDestroy();
if (mCache != null) if (mCache != null)
mCache.dispose(); mCache.dispose();
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.theme_default: case R.id.theme_default:
mMap.setTheme(VtmThemes.DEFAULT); mMap.setTheme(VtmThemes.DEFAULT);
item.setChecked(true); item.setChecked(true);
return true; return true;
case R.id.theme_tubes: case R.id.theme_tubes:
mMap.setTheme(VtmThemes.TRONRENDER); mMap.setTheme(VtmThemes.TRONRENDER);
item.setChecked(true); item.setChecked(true);
return true; return true;
case R.id.theme_osmarender: case R.id.theme_osmarender:
mMap.setTheme(VtmThemes.OSMARENDER); mMap.setTheme(VtmThemes.OSMARENDER);
item.setChecked(true); item.setChecked(true);
return true; return true;
case R.id.theme_newtron: case R.id.theme_newtron:
mMap.setTheme(VtmThemes.NEWTRON); mMap.setTheme(VtmThemes.NEWTRON);
item.setChecked(true); item.setChecked(true);
return true; return true;
case R.id.gridlayer: case R.id.gridlayer:
if (item.isChecked()) { if (item.isChecked()) {
item.setChecked(false); item.setChecked(false);
mMap.layers().remove(mGridLayer); mMap.layers().remove(mGridLayer);
} else { } else {
item.setChecked(true); item.setChecked(true);
if (mGridLayer == null) if (mGridLayer == null)
mGridLayer = new TileGridLayer(mMap); mGridLayer = new TileGridLayer(mMap);
mMap.layers().add(mGridLayer); mMap.layers().add(mGridLayer);
} }
mMap.updateMap(true); mMap.updateMap(true);
return true; return true;
} }
return false; return false;
} }
@Override @Override
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.theme_menu, menu); getMenuInflater().inflate(R.menu.theme_menu, menu);
return true; return true;
} }
} }

View File

@@ -14,6 +14,8 @@
*/ */
package org.oscim.android.test; package org.oscim.android.test;
import android.os.Bundle;
import org.oscim.android.cache.TileCache; import org.oscim.android.cache.TileCache;
import org.oscim.backend.canvas.Color; import org.oscim.backend.canvas.Color;
import org.oscim.core.MapPosition; import org.oscim.core.MapPosition;
@@ -26,92 +28,90 @@ import org.oscim.tiling.source.bitmap.DefaultSources;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import android.os.Bundle;
public class BitmapTileMapActivity extends MapActivity { public class BitmapTileMapActivity extends MapActivity {
static final Logger log = LoggerFactory.getLogger(BitmapTileMapActivity.class); static final Logger log = LoggerFactory.getLogger(BitmapTileMapActivity.class);
private final static boolean USE_CACHE = true; private final static boolean USE_CACHE = true;
private final BitmapTileSource mTileSource; private final BitmapTileSource mTileSource;
protected BitmapTileLayer mBitmapLayer; protected BitmapTileLayer mBitmapLayer;
public BitmapTileMapActivity() { public BitmapTileMapActivity() {
this(DefaultSources.OPENSTREETMAP.build()); this(DefaultSources.OPENSTREETMAP.build());
} }
public BitmapTileMapActivity(BitmapTileSource tileSource) { public BitmapTileMapActivity(BitmapTileSource tileSource) {
super(R.layout.activity_map); super(R.layout.activity_map);
mTileSource = tileSource; mTileSource = tileSource;
} }
private TileCache mCache; private TileCache mCache;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
MapRenderer.setBackgroundColor(0xff777777); MapRenderer.setBackgroundColor(0xff777777);
mMap.layers().add(new TileGridLayer(mMap, Color.GRAY, 1.8f, 8)); mMap.layers().add(new TileGridLayer(mMap, Color.GRAY, 1.8f, 8));
if (mTileSource == null) if (mTileSource == null)
return; return;
if (USE_CACHE) { if (USE_CACHE) {
String cacheFile = mTileSource.getUrl() String cacheFile = mTileSource.getUrl()
.toString() .toString()
.replaceFirst("https?://", "") .replaceFirst("https?://", "")
.replaceAll("/", "-"); .replaceAll("/", "-");
log.debug("use bitmap cache {}", cacheFile); log.debug("use bitmap cache {}", cacheFile);
mCache = new TileCache(this, null, cacheFile); mCache = new TileCache(this, null, cacheFile);
mCache.setCacheSize(512 * (1 << 10)); mCache.setCacheSize(512 * (1 << 10));
mTileSource.setCache(mCache); mTileSource.setCache(mCache);
} }
mBitmapLayer = new BitmapTileLayer(mMap, mTileSource); mBitmapLayer = new BitmapTileLayer(mMap, mTileSource);
mMap.layers().add(mBitmapLayer); mMap.layers().add(mBitmapLayer);
//loooop(1); //loooop(1);
} }
@Override @Override
protected void onDestroy() { protected void onDestroy() {
super.onDestroy(); super.onDestroy();
if (mCache != null) if (mCache != null)
mCache.dispose(); mCache.dispose();
} }
// Stress testing // Stress testing
void loooop(final int i) { void loooop(final int i) {
final long time = (long) (500 + Math.random() * 1000); final long time = (long) (500 + Math.random() * 1000);
mMapView.postDelayed(new Runnable() { mMapView.postDelayed(new Runnable() {
@Override @Override
public void run() { public void run() {
MapPosition p = new MapPosition(); MapPosition p = new MapPosition();
if (i == 1) { if (i == 1) {
mMapView.map().getMapPosition(p); mMapView.map().getMapPosition(p);
p.setScale(4); p.setScale(4);
mMapView.map().animator().animateTo(time, p); mMapView.map().animator().animateTo(time, p);
} else { } else {
//mMapView.map().setMapPosition(p); //mMapView.map().setMapPosition(p);
p.setScale(2 + (1 << (int) (Math.random() * 13))); p.setScale(2 + (1 << (int) (Math.random() * 13)));
// p.setX((p.getX() + (Math.random() * 4 - 2) / p.getScale())); // p.setX((p.getX() + (Math.random() * 4 - 2) / p.getScale()));
// p.setY((p.getY() + (Math.random() * 4 - 2) / p.getScale())); // p.setY((p.getY() + (Math.random() * 4 - 2) / p.getScale()));
p.setX(MercatorProjection.longitudeToX(Math.random() * 180)); p.setX(MercatorProjection.longitudeToX(Math.random() * 180));
p.setY(MercatorProjection.latitudeToY(Math.random() * 60)); p.setY(MercatorProjection.latitudeToY(Math.random() * 60));
p.setTilt((float) (Math.random() * 60)); p.setTilt((float) (Math.random() * 60));
p.setBearing((float) (Math.random() * 360)); p.setBearing((float) (Math.random() * 360));
//mMapView.map().setMapPosition(p); //mMapView.map().setMapPosition(p);
mMapView.map().animator().animateTo(time, p); mMapView.map().animator().animateTo(time, p);
} }
loooop((i + 1) % 2); loooop((i + 1) % 2);
} }
}, time); }, time);
} }
} }

View File

@@ -16,14 +16,14 @@
*/ */
package org.oscim.android.test; package org.oscim.android.test;
import java.io.IOException; import android.content.Context;
import java.io.InputStream; import android.os.Bundle;
import java.net.URL; import android.view.View;
import java.net.URLConnection; import android.widget.Toast;
import java.util.Arrays; import android.widget.ToggleButton;
import org.jeo.vector.VectorDataset;
import org.jeo.map.Style; import org.jeo.map.Style;
import org.jeo.vector.VectorDataset;
import org.oscim.layers.OSMIndoorLayer; import org.oscim.layers.OSMIndoorLayer;
import org.oscim.layers.tile.buildings.BuildingLayer; import org.oscim.layers.tile.buildings.BuildingLayer;
import org.oscim.layers.tile.vector.labeling.LabelLayer; import org.oscim.layers.tile.vector.labeling.LabelLayer;
@@ -33,146 +33,146 @@ import org.oscim.utils.IOUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import android.content.Context; import java.io.IOException;
import android.os.Bundle; import java.io.InputStream;
import android.view.View; import java.net.URL;
import android.widget.Toast; import java.net.URLConnection;
import android.widget.ToggleButton; import java.util.Arrays;
public class JeoIndoorMapActivity extends BaseMapActivity { public class JeoIndoorMapActivity extends BaseMapActivity {
public static final Logger log = LoggerFactory.getLogger(JeoIndoorMapActivity.class); public static final Logger log = LoggerFactory.getLogger(JeoIndoorMapActivity.class);
// from http://overpass-turbo.eu/s/2vp // from http://overpass-turbo.eu/s/2vp
String PATH = "https://gist.github.com/anonymous/8960337/raw/overpass.geojson"; String PATH = "https://gist.github.com/anonymous/8960337/raw/overpass.geojson";
//String PATH = "https://gist.github.com/hjanetzek/9280925/raw/overpass.geojson"; //String PATH = "https://gist.github.com/hjanetzek/9280925/raw/overpass.geojson";
private OSMIndoorLayer mIndoorLayer; private OSMIndoorLayer mIndoorLayer;
public JeoIndoorMapActivity() { public JeoIndoorMapActivity() {
super(R.layout.jeo_indoor_map); super(R.layout.jeo_indoor_map);
} }
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
mMap.addTask(new Runnable() { mMap.addTask(new Runnable() {
@Override @Override
public void run() { public void run() {
showToast("load data"); showToast("load data");
InputStream is = null; InputStream is = null;
try { try {
// File file = new File(Environment.getExternalStorageDirectory() // File file = new File(Environment.getExternalStorageDirectory()
// .getAbsolutePath(), "osmindoor.json"); // .getAbsolutePath(), "osmindoor.json");
// is = new FileInputStream(file); // is = new FileInputStream(file);
URL url = new URL(PATH); URL url = new URL(PATH);
URLConnection conn = url.openConnection(); URLConnection conn = url.openConnection();
is = conn.getInputStream(); is = conn.getInputStream();
loadJson(is); loadJson(is);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
IOUtils.closeQuietly(is); IOUtils.closeQuietly(is);
} }
} }
}); });
mMap.setTheme(VtmThemes.DEFAULT); mMap.setTheme(VtmThemes.DEFAULT);
mMap.layers().add(new BuildingLayer(mMap, mBaseLayer)); mMap.layers().add(new BuildingLayer(mMap, mBaseLayer));
mMap.layers().add(new LabelLayer(mMap, mBaseLayer)); mMap.layers().add(new LabelLayer(mMap, mBaseLayer));
// mMap.layers().add(new TileGridLayer(mMap)); // mMap.layers().add(new TileGridLayer(mMap));
// String file = Environment.getExternalStorageDirectory().getAbsolutePath(); // String file = Environment.getExternalStorageDirectory().getAbsolutePath();
// VectorDataset data = (VectorDataset) JeoTest.getJsonData(file + "/states.json", true); // VectorDataset data = (VectorDataset) JeoTest.getJsonData(file + "/states.json", true);
// Style style = JeoTest.getStyle(); // Style style = JeoTest.getStyle();
// mMap.layers().add(new JeoVectorLayer(mMap, data, style)); // mMap.layers().add(new JeoVectorLayer(mMap, data, style));
} }
void loadJson(InputStream is) { void loadJson(InputStream is) {
showToast("got data"); showToast("got data");
VectorDataset data = JeoTest.readGeoJson(is); VectorDataset data = JeoTest.readGeoJson(is);
Style style = JeoTest.getStyle(); Style style = JeoTest.getStyle();
mIndoorLayer = new OSMIndoorLayer(mMap, data, style); mIndoorLayer = new OSMIndoorLayer(mMap, data, style);
mMap.layers().add(mIndoorLayer); mMap.layers().add(mIndoorLayer);
showToast("data ready"); showToast("data ready");
mMap.updateMap(true); mMap.updateMap(true);
mIndoorLayer.activeLevels[0] = true; mIndoorLayer.activeLevels[0] = true;
shift(); shift();
} }
public void showToast(final String text) { public void showToast(final String text) {
final Context ctx = this; final Context ctx = this;
runOnUiThread(new Runnable() { runOnUiThread(new Runnable() {
@Override @Override
public void run() { public void run() {
Toast toast = Toast.makeText(ctx, text, Toast.LENGTH_SHORT); Toast toast = Toast.makeText(ctx, text, Toast.LENGTH_SHORT);
toast.show(); toast.show();
} }
}); });
} }
boolean mShift = true; boolean mShift = true;
public void shift() { public void shift() {
if (!mShift) if (!mShift)
return; return;
mMap.postDelayed(new Runnable() { mMap.postDelayed(new Runnable() {
@Override @Override
public void run() { public void run() {
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
if (mIndoorLayer.activeLevels[i]) { if (mIndoorLayer.activeLevels[i]) {
mIndoorLayer.activeLevels[i] = false; mIndoorLayer.activeLevels[i] = false;
mIndoorLayer.activeLevels[(i + 1) % 9] = true; mIndoorLayer.activeLevels[(i + 1) % 9] = true;
mIndoorLayer.update(); mIndoorLayer.update();
break; break;
} }
} }
shift(); shift();
} }
}, 200); }, 200);
} }
public void onClick(View v) { public void onClick(View v) {
mShift = false; mShift = false;
if (mIndoorLayer == null) if (mIndoorLayer == null)
return; return;
int i = 0; int i = 0;
if (v instanceof ToggleButton) { if (v instanceof ToggleButton) {
ToggleButton b = (ToggleButton) v; ToggleButton b = (ToggleButton) v;
i = (b.getTextOn().charAt(0) - '0') + 1; i = (b.getTextOn().charAt(0) - '0') + 1;
} }
if (i < 0 || i > 9) if (i < 0 || i > 9)
i = 0; i = 0;
mIndoorLayer.activeLevels[i] ^= true; mIndoorLayer.activeLevels[i] ^= true;
((ToggleButton) v).setChecked(mIndoorLayer.activeLevels[i]); ((ToggleButton) v).setChecked(mIndoorLayer.activeLevels[i]);
log.debug(Arrays.toString(mIndoorLayer.activeLevels)); log.debug(Arrays.toString(mIndoorLayer.activeLevels));
mIndoorLayer.update(); mIndoorLayer.update();
} }
@Override @Override
protected void onStop() { protected void onStop() {
super.onStop(); super.onStop();
} }
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
/* ignore saved position */ /* ignore saved position */
//mMap.setMapPosition(49.417, 8.673, 1 << 17); //mMap.setMapPosition(49.417, 8.673, 1 << 17);
mMap.setMapPosition(53.5620092, 9.9866457, 1 << 16); mMap.setMapPosition(53.5620092, 9.9866457, 1 << 16);
} }
} }

View File

@@ -16,53 +16,53 @@
*/ */
package org.oscim.android.test; package org.oscim.android.test;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import org.oscim.android.MapPreferences; import org.oscim.android.MapPreferences;
import org.oscim.android.MapView; import org.oscim.android.MapView;
import org.oscim.map.Map; import org.oscim.map.Map;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public abstract class MapActivity extends AppCompatActivity { public abstract class MapActivity extends AppCompatActivity {
MapView mMapView; MapView mMapView;
Map mMap; Map mMap;
MapPreferences mPrefs; MapPreferences mPrefs;
protected final int mContentView; protected final int mContentView;
public MapActivity(int contentView) { public MapActivity(int contentView) {
mContentView = contentView; mContentView = contentView;
} }
public MapActivity() { public MapActivity() {
this(R.layout.activity_map); this(R.layout.activity_map);
} }
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(mContentView); setContentView(mContentView);
setTitle(getClass().getSimpleName()); setTitle(getClass().getSimpleName());
mMapView = (MapView) findViewById(R.id.mapView); mMapView = (MapView) findViewById(R.id.mapView);
mMap = mMapView.map(); mMap = mMapView.map();
mPrefs = new MapPreferences(MapActivity.class.getName(), this); mPrefs = new MapPreferences(MapActivity.class.getName(), this);
} }
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
mPrefs.load(mMapView.map()); mPrefs.load(mMapView.map());
mMapView.onResume(); mMapView.onResume();
} }
@Override @Override
protected void onPause() { protected void onPause() {
super.onPause(); super.onPause();
mMapView.onPause(); mMapView.onPause();
mPrefs.save(mMapView.map()); mPrefs.save(mMapView.map());
} }
} }

View File

@@ -17,6 +17,11 @@
*/ */
package org.oscim.android.test; package org.oscim.android.test;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import org.oscim.android.filepicker.FilePicker; import org.oscim.android.filepicker.FilePicker;
import org.oscim.android.filepicker.FilterByFileExtension; import org.oscim.android.filepicker.FilterByFileExtension;
import org.oscim.android.filepicker.ValidMapFile; import org.oscim.android.filepicker.ValidMapFile;
@@ -30,106 +35,101 @@ import org.oscim.theme.VtmThemes;
import org.oscim.tiling.source.mapfile.MapFileTileSource; import org.oscim.tiling.source.mapfile.MapFileTileSource;
import org.oscim.tiling.source.mapfile.MapInfo; import org.oscim.tiling.source.mapfile.MapInfo;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MapsforgeMapActivity extends MapActivity { public class MapsforgeMapActivity extends MapActivity {
private static final int SELECT_MAP_FILE = 0; private static final int SELECT_MAP_FILE = 0;
private TileGridLayer mGridLayer; private TileGridLayer mGridLayer;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
startActivityForResult(new Intent(this, MapFilePicker.class), startActivityForResult(new Intent(this, MapFilePicker.class),
SELECT_MAP_FILE); SELECT_MAP_FILE);
} }
public static class MapFilePicker extends FilePicker { public static class MapFilePicker extends FilePicker {
public MapFilePicker() { public MapFilePicker() {
setFileDisplayFilter(new FilterByFileExtension(".map")); setFileDisplayFilter(new FilterByFileExtension(".map"));
setFileSelectFilter(new ValidMapFile()); setFileSelectFilter(new ValidMapFile());
} }
} }
@Override @Override
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.theme_menu, menu); getMenuInflater().inflate(R.menu.theme_menu, menu);
return true; return true;
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.theme_default: case R.id.theme_default:
mMap.setTheme(VtmThemes.DEFAULT); mMap.setTheme(VtmThemes.DEFAULT);
item.setChecked(true); item.setChecked(true);
return true; return true;
case R.id.theme_tubes: case R.id.theme_tubes:
mMap.setTheme(VtmThemes.TRONRENDER); mMap.setTheme(VtmThemes.TRONRENDER);
item.setChecked(true); item.setChecked(true);
return true; return true;
case R.id.theme_osmarender: case R.id.theme_osmarender:
mMap.setTheme(VtmThemes.OSMARENDER); mMap.setTheme(VtmThemes.OSMARENDER);
item.setChecked(true); item.setChecked(true);
return true; return true;
case R.id.theme_newtron: case R.id.theme_newtron:
mMap.setTheme(VtmThemes.NEWTRON); mMap.setTheme(VtmThemes.NEWTRON);
item.setChecked(true); item.setChecked(true);
return true; return true;
case R.id.gridlayer: case R.id.gridlayer:
if (item.isChecked()) { if (item.isChecked()) {
item.setChecked(false); item.setChecked(false);
mMap.layers().remove(mGridLayer); mMap.layers().remove(mGridLayer);
} else { } else {
item.setChecked(true); item.setChecked(true);
if (mGridLayer == null) if (mGridLayer == null)
mGridLayer = new TileGridLayer(mMap); mGridLayer = new TileGridLayer(mMap);
mMap.layers().add(mGridLayer); mMap.layers().add(mGridLayer);
} }
mMap.updateMap(true); mMap.updateMap(true);
return true; return true;
} }
return false; return false;
} }
@Override @Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == SELECT_MAP_FILE) { if (requestCode == SELECT_MAP_FILE) {
if (resultCode != RESULT_OK || intent == null || intent.getStringExtra(FilePicker.SELECTED_FILE) == null) { if (resultCode != RESULT_OK || intent == null || intent.getStringExtra(FilePicker.SELECTED_FILE) == null) {
finish(); finish();
return; return;
} }
MapFileTileSource tileSource = new MapFileTileSource(); MapFileTileSource tileSource = new MapFileTileSource();
tileSource.setPreferredLanguage("en"); tileSource.setPreferredLanguage("en");
String file = intent.getStringExtra(FilePicker.SELECTED_FILE); String file = intent.getStringExtra(FilePicker.SELECTED_FILE);
if (tileSource.setMapFile(file)) { if (tileSource.setMapFile(file)) {
VectorTileLayer l = mMap.setBaseMap(tileSource); VectorTileLayer l = mMap.setBaseMap(tileSource);
mMap.setTheme(VtmThemes.DEFAULT); mMap.setTheme(VtmThemes.DEFAULT);
mMap.layers().add(new BuildingLayer(mMap, l)); mMap.layers().add(new BuildingLayer(mMap, l));
mMap.layers().add(new LabelLayer(mMap, l)); mMap.layers().add(new LabelLayer(mMap, l));
MapInfo info = tileSource.getMapInfo(); MapInfo info = tileSource.getMapInfo();
MapPosition pos = new MapPosition(); MapPosition pos = new MapPosition();
pos.setByBoundingBox(info.boundingBox, Tile.SIZE * 4, Tile.SIZE * 4); pos.setByBoundingBox(info.boundingBox, Tile.SIZE * 4, Tile.SIZE * 4);
mMap.setMapPosition(pos); mMap.setMapPosition(pos);
mPrefs.clear(); mPrefs.clear();
} }
} }
} }
} }

View File

@@ -17,11 +17,9 @@
*/ */
package org.oscim.android.test; package org.oscim.android.test;
import static org.oscim.android.canvas.AndroidGraphics.drawableToBitmap; import android.graphics.drawable.Drawable;
import static org.oscim.tiling.source.bitmap.DefaultSources.STAMEN_TONER; import android.os.Bundle;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import org.oscim.backend.canvas.Bitmap; import org.oscim.backend.canvas.Bitmap;
import org.oscim.core.GeoPoint; import org.oscim.core.GeoPoint;
@@ -32,83 +30,85 @@ import org.oscim.layers.marker.MarkerItem;
import org.oscim.layers.marker.MarkerItem.HotspotPlace; import org.oscim.layers.marker.MarkerItem.HotspotPlace;
import org.oscim.layers.marker.MarkerSymbol; import org.oscim.layers.marker.MarkerSymbol;
import android.graphics.drawable.Drawable; import java.util.ArrayList;
import android.os.Bundle; import java.util.List;
import android.widget.Toast;
import static org.oscim.android.canvas.AndroidGraphics.drawableToBitmap;
import static org.oscim.tiling.source.bitmap.DefaultSources.STAMEN_TONER;
public class MarkerOverlayActivity extends BitmapTileMapActivity public class MarkerOverlayActivity extends BitmapTileMapActivity
implements OnItemGestureListener<MarkerItem> { implements OnItemGestureListener<MarkerItem> {
private static final boolean BILLBOARDS = true; private static final boolean BILLBOARDS = true;
private MarkerSymbol mFocusMarker; private MarkerSymbol mFocusMarker;
public MarkerOverlayActivity() { public MarkerOverlayActivity() {
super(STAMEN_TONER.build()); super(STAMEN_TONER.build());
} }
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
/* directly load bitmap from resources */ /* directly load bitmap from resources */
Bitmap bitmap = drawableToBitmap(getResources(), R.drawable.marker_poi); Bitmap bitmap = drawableToBitmap(getResources(), R.drawable.marker_poi);
MarkerSymbol symbol; MarkerSymbol symbol;
if (BILLBOARDS) if (BILLBOARDS)
symbol = new MarkerSymbol(bitmap, HotspotPlace.CENTER); symbol = new MarkerSymbol(bitmap, HotspotPlace.CENTER);
else else
symbol = new MarkerSymbol(bitmap, 0.5f, 0.5f, false); symbol = new MarkerSymbol(bitmap, 0.5f, 0.5f, false);
/* another option: use some bitmap drawable */ /* another option: use some bitmap drawable */
Drawable d = getResources().getDrawable(R.drawable.ic_launcher); Drawable d = getResources().getDrawable(R.drawable.ic_launcher);
if (BILLBOARDS) if (BILLBOARDS)
mFocusMarker = new MarkerSymbol(drawableToBitmap(d), mFocusMarker = new MarkerSymbol(drawableToBitmap(d),
HotspotPlace.BOTTOM_CENTER); HotspotPlace.BOTTOM_CENTER);
else else
mFocusMarker = new MarkerSymbol(drawableToBitmap(d), mFocusMarker = new MarkerSymbol(drawableToBitmap(d),
0.5f, 0.5f, false); 0.5f, 0.5f, false);
ItemizedLayer<MarkerItem> markerLayer = ItemizedLayer<MarkerItem> markerLayer =
new ItemizedLayer<MarkerItem>(mMap, new ArrayList<MarkerItem>(), new ItemizedLayer<MarkerItem>(mMap, new ArrayList<MarkerItem>(),
symbol, this); symbol, this);
mMap.layers().add(markerLayer); mMap.layers().add(markerLayer);
List<MarkerItem> pts = new ArrayList<MarkerItem>(); List<MarkerItem> pts = new ArrayList<MarkerItem>();
for (double lat = -90; lat <= 90; lat += 5) { for (double lat = -90; lat <= 90; lat += 5) {
for (double lon = -180; lon <= 180; lon += 5) for (double lon = -180; lon <= 180; lon += 5)
pts.add(new MarkerItem(lat + "/" + lon, "", pts.add(new MarkerItem(lat + "/" + lon, "",
new GeoPoint(lat, lon))); new GeoPoint(lat, lon)));
} }
markerLayer.addItems(pts); markerLayer.addItems(pts);
mMap.layers().add(new TileGridLayer(mMap)); mMap.layers().add(new TileGridLayer(mMap));
} }
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
/* ignore saved position */ /* ignore saved position */
mMap.setMapPosition(0, 0, 1 << 2); mMap.setMapPosition(0, 0, 1 << 2);
} }
@Override @Override
public boolean onItemSingleTapUp(int index, MarkerItem item) { public boolean onItemSingleTapUp(int index, MarkerItem item) {
if (item.getMarker() == null) if (item.getMarker() == null)
item.setMarker(mFocusMarker); item.setMarker(mFocusMarker);
else else
item.setMarker(null); item.setMarker(null);
Toast toast = Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT); Toast toast = Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT);
toast.show(); toast.show();
return true; return true;
} }
@Override @Override
public boolean onItemLongPress(int index, MarkerItem item) { public boolean onItemLongPress(int index, MarkerItem item) {
return false; return false;
} }
} }

View File

@@ -17,6 +17,8 @@
*/ */
package org.oscim.android.test; package org.oscim.android.test;
import android.os.Bundle;
import org.oscim.layers.TileGridLayer; import org.oscim.layers.TileGridLayer;
import org.oscim.layers.tile.buildings.BuildingLayer; import org.oscim.layers.tile.buildings.BuildingLayer;
import org.oscim.layers.tile.vector.VectorTileLayer; import org.oscim.layers.tile.vector.VectorTileLayer;
@@ -24,49 +26,47 @@ import org.oscim.layers.tile.vector.labeling.LabelLayer;
import org.oscim.theme.IRenderTheme; import org.oscim.theme.IRenderTheme;
import org.oscim.theme.ThemeLoader; import org.oscim.theme.ThemeLoader;
import org.oscim.theme.VtmThemes; import org.oscim.theme.VtmThemes;
import org.oscim.tiling.source.geojson.OsmRoadLineJsonTileSource;
import org.oscim.tiling.source.geojson.OsmBuildingJsonTileSource; import org.oscim.tiling.source.geojson.OsmBuildingJsonTileSource;
import org.oscim.tiling.source.geojson.OsmLanduseJsonTileSource; import org.oscim.tiling.source.geojson.OsmLanduseJsonTileSource;
import org.oscim.tiling.source.geojson.OsmWaterJsonTileSource;
import org.oscim.tiling.source.geojson.OsmRoadLabelJsonTileSource; import org.oscim.tiling.source.geojson.OsmRoadLabelJsonTileSource;
import org.oscim.tiling.source.geojson.OsmRoadLineJsonTileSource;
import android.os.Bundle; import org.oscim.tiling.source.geojson.OsmWaterJsonTileSource;
public class OsmJsonMapActivity extends MapActivity { public class OsmJsonMapActivity extends MapActivity {
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
IRenderTheme theme = ThemeLoader.load(VtmThemes.DEFAULT); IRenderTheme theme = ThemeLoader.load(VtmThemes.DEFAULT);
mMap.setBaseMap(new VectorTileLayer(mMap, new OsmLanduseJsonTileSource())); mMap.setBaseMap(new VectorTileLayer(mMap, new OsmLanduseJsonTileSource()));
mMap.setTheme(theme); mMap.setTheme(theme);
VectorTileLayer l = new VectorTileLayer(mMap, new OsmWaterJsonTileSource()); VectorTileLayer l = new VectorTileLayer(mMap, new OsmWaterJsonTileSource());
l.setRenderTheme(theme); l.setRenderTheme(theme);
l.tileRenderer().setOverdrawColor(0); l.tileRenderer().setOverdrawColor(0);
mMap.layers().add(l); mMap.layers().add(l);
l = new VectorTileLayer(mMap, new OsmRoadLineJsonTileSource()); l = new VectorTileLayer(mMap, new OsmRoadLineJsonTileSource());
l.setRenderTheme(theme); l.setRenderTheme(theme);
l.tileRenderer().setOverdrawColor(0); l.tileRenderer().setOverdrawColor(0);
mMap.layers().add(l); mMap.layers().add(l);
l = new VectorTileLayer(mMap, new OsmBuildingJsonTileSource()); l = new VectorTileLayer(mMap, new OsmBuildingJsonTileSource());
l.setRenderTheme(theme); l.setRenderTheme(theme);
l.tileRenderer().setOverdrawColor(0); l.tileRenderer().setOverdrawColor(0);
mMap.layers().add(l); mMap.layers().add(l);
mMap.layers().add(new BuildingLayer(mMap, l)); mMap.layers().add(new BuildingLayer(mMap, l));
l = new VectorTileLayer(mMap, new OsmRoadLabelJsonTileSource()); l = new VectorTileLayer(mMap, new OsmRoadLabelJsonTileSource());
l.setRenderTheme(theme); l.setRenderTheme(theme);
l.tileRenderer().setOverdrawColor(0); l.tileRenderer().setOverdrawColor(0);
mMap.layers().add(l); mMap.layers().add(l);
mMap.layers().add(new LabelLayer(mMap, l)); mMap.layers().add(new LabelLayer(mMap, l));
mMap.layers().add(new TileGridLayer(mMap)); mMap.layers().add(new TileGridLayer(mMap));
mMap.setMapPosition(53.08, 8.83, Math.pow(2, 16)); mMap.setMapPosition(53.08, 8.83, Math.pow(2, 16));
} }
} }

View File

@@ -17,9 +17,7 @@
*/ */
package org.oscim.android.test; package org.oscim.android.test;
import static org.oscim.tiling.source.bitmap.DefaultSources.STAMEN_TONER; import android.os.Bundle;
import java.util.ArrayList;
import org.oscim.backend.canvas.Color; import org.oscim.backend.canvas.Color;
import org.oscim.core.MapPosition; import org.oscim.core.MapPosition;
@@ -27,7 +25,9 @@ import org.oscim.event.Event;
import org.oscim.layers.JtsPathLayer; import org.oscim.layers.JtsPathLayer;
import org.oscim.map.Map.UpdateListener; import org.oscim.map.Map.UpdateListener;
import android.os.Bundle; import java.util.ArrayList;
import static org.oscim.tiling.source.bitmap.DefaultSources.STAMEN_TONER;
/** /**
* This is a very INEFFICIENT and somewhat less usefull example for how to use * This is a very INEFFICIENT and somewhat less usefull example for how to use
@@ -35,75 +35,75 @@ import android.os.Bundle;
*/ */
public class PathOverlayActivity extends BitmapTileMapActivity { public class PathOverlayActivity extends BitmapTileMapActivity {
public PathOverlayActivity() { public PathOverlayActivity() {
super(STAMEN_TONER.build()); super(STAMEN_TONER.build());
} }
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
//mBitmapLayer.tileRenderer().setBitmapAlpha(0.5f); //mBitmapLayer.tileRenderer().setBitmapAlpha(0.5f);
mMap.setMapPosition(0, 0, 1 << 2); mMap.setMapPosition(0, 0, 1 << 2);
for (double lat = -90; lat <= 90; lat += 5) { for (double lat = -90; lat <= 90; lat += 5) {
int c = Color.fade(Color.rainbow((float) (lat + 90) / 180), 0.5f); int c = Color.fade(Color.rainbow((float) (lat + 90) / 180), 0.5f);
JtsPathLayer pathLayer = new JtsPathLayer(mMap, c, 6); JtsPathLayer pathLayer = new JtsPathLayer(mMap, c, 6);
mMap.layers().add(pathLayer); mMap.layers().add(pathLayer);
mPathLayers.add(pathLayer); mPathLayers.add(pathLayer);
} }
mMap.events.bind(new UpdateListener() { mMap.events.bind(new UpdateListener() {
@Override @Override
public void onMapEvent(Event e, MapPosition mapPosition) { public void onMapEvent(Event e, MapPosition mapPosition) {
//if (e == Map.UPDATE_EVENT) { //if (e == Map.UPDATE_EVENT) {
long t = System.currentTimeMillis(); long t = System.currentTimeMillis();
float pos = t % 20000 / 10000f - 1f; float pos = t % 20000 / 10000f - 1f;
createLayers(pos); createLayers(pos);
mMap.updateMap(true); mMap.updateMap(true);
//} //}
} }
}); });
} }
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
/* ignore saved position */ /* ignore saved position */
mMap.setMapPosition(0, 0, 1 << 2); mMap.setMapPosition(0, 0, 1 << 2);
} }
ArrayList<JtsPathLayer> mPathLayers = new ArrayList<JtsPathLayer>(); ArrayList<JtsPathLayer> mPathLayers = new ArrayList<JtsPathLayer>();
void createLayers(float pos) { void createLayers(float pos) {
int i = 0; int i = 0;
for (double lat = -90; lat <= 90; lat += 5) { for (double lat = -90; lat <= 90; lat += 5) {
double[] packedCoordinates = new double[360 + 2]; double[] packedCoordinates = new double[360 + 2];
//List<GeoPoint> pts = new ArrayList<GeoPoint>(); //List<GeoPoint> pts = new ArrayList<GeoPoint>();
int c = 0; int c = 0;
for (double lon = -180; lon <= 180; lon += 2) { for (double lon = -180; lon <= 180; lon += 2) {
//pts.add(new GeoPoint(lat, lon)); //pts.add(new GeoPoint(lat, lon));
double longitude = lon; double longitude = lon;
double latitude = lat + (pos * 90); double latitude = lat + (pos * 90);
if (latitude < -90) if (latitude < -90)
latitude += 180; latitude += 180;
if (latitude > 90) if (latitude > 90)
latitude -= 180; latitude -= 180;
latitude += Math.sin((Math.abs(pos) * (lon / Math.PI))); latitude += Math.sin((Math.abs(pos) * (lon / Math.PI)));
packedCoordinates[c++] = longitude; packedCoordinates[c++] = longitude;
packedCoordinates[c++] = latitude; packedCoordinates[c++] = latitude;
} }
//LineString line = new LineString(factory.create(packedCoordinates, 2), geomFactory); //LineString line = new LineString(factory.create(packedCoordinates, 2), geomFactory);
//mPathLayers.get(i++).setLineString(line); //mPathLayers.get(i++).setLineString(line);
mPathLayers.get(i++).setLineString(packedCoordinates); mPathLayers.get(i++).setLineString(packedCoordinates);
} }
} }
} }

View File

@@ -16,6 +16,8 @@
*/ */
package org.oscim.android.test; package org.oscim.android.test;
import android.os.Bundle;
import org.oscim.android.cache.TileCache; import org.oscim.android.cache.TileCache;
import org.oscim.layers.tile.TileLayer; import org.oscim.layers.tile.TileLayer;
import org.oscim.layers.tile.buildings.S3DBLayer; import org.oscim.layers.tile.buildings.S3DBLayer;
@@ -24,47 +26,45 @@ import org.oscim.theme.VtmThemes;
import org.oscim.tiling.TileSource; import org.oscim.tiling.TileSource;
import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; import org.oscim.tiling.source.oscimap4.OSciMap4TileSource;
import android.os.Bundle;
public class S3DBMapActivity extends BaseMapActivity { public class S3DBMapActivity extends BaseMapActivity {
TileCache mS3dbCache; TileCache mS3dbCache;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
mMap.setTheme(VtmThemes.DEFAULT); mMap.setTheme(VtmThemes.DEFAULT);
TileSource ts = OSciMap4TileSource.builder() TileSource ts = OSciMap4TileSource.builder()
.url("http://opensciencemap.org/tiles/s3db") .url("http://opensciencemap.org/tiles/s3db")
.zoomMin(16) .zoomMin(16)
.zoomMax(16) .zoomMax(16)
.build(); .build();
if (USE_CACHE) { if (USE_CACHE) {
mS3dbCache = new TileCache(this, null, "s3db.db"); mS3dbCache = new TileCache(this, null, "s3db.db");
mS3dbCache.setCacheSize(512 * (1 << 10)); mS3dbCache.setCacheSize(512 * (1 << 10));
ts.setCache(mS3dbCache); ts.setCache(mS3dbCache);
} }
TileLayer tl = new S3DBLayer(mMap, ts, true, false); TileLayer tl = new S3DBLayer(mMap, ts, true, false);
mMap.layers().add(tl); mMap.layers().add(tl);
mMap.layers().add(new LabelLayer(mMap, mBaseLayer)); mMap.layers().add(new LabelLayer(mMap, mBaseLayer));
} }
@Override @Override
protected void onDestroy() { protected void onDestroy() {
super.onDestroy(); super.onDestroy();
if (mS3dbCache != null) if (mS3dbCache != null)
mS3dbCache.dispose(); mS3dbCache.dispose();
} }
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
/* ignore saved position */ /* ignore saved position */
mMap.setMapPosition(53.5620092, 9.9866457, 1 << 16); mMap.setMapPosition(53.5620092, 9.9866457, 1 << 16);
} }
} }

View File

@@ -17,9 +17,6 @@
*/ */
package org.oscim.android.test; package org.oscim.android.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
@@ -28,47 +25,50 @@ import android.view.View.OnClickListener;
import android.widget.Button; import android.widget.Button;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* A simple start screen for the sample activities. * A simple start screen for the sample activities.
*/ */
public class Samples extends Activity { public class Samples extends Activity {
public static Logger log = LoggerFactory.getLogger(Samples.class); public static Logger log = LoggerFactory.getLogger(Samples.class);
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_samples); setContentView(R.layout.activity_samples);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.samples); LinearLayout linearLayout = (LinearLayout) findViewById(R.id.samples);
linearLayout.addView(createButton(SimpleMapActivity.class)); linearLayout.addView(createButton(SimpleMapActivity.class));
linearLayout.addView(createButton(BitmapTileMapActivity.class)); linearLayout.addView(createButton(BitmapTileMapActivity.class));
linearLayout.addView(createButton(MapsforgeMapActivity.class)); linearLayout.addView(createButton(MapsforgeMapActivity.class));
linearLayout.addView(createButton(PathOverlayActivity.class)); linearLayout.addView(createButton(PathOverlayActivity.class));
linearLayout.addView(createButton(MarkerOverlayActivity.class)); linearLayout.addView(createButton(MarkerOverlayActivity.class));
linearLayout.addView(createButton(ThemeStylerActivity.class)); linearLayout.addView(createButton(ThemeStylerActivity.class));
linearLayout.addView(createButton(S3DBMapActivity.class)); linearLayout.addView(createButton(S3DBMapActivity.class));
linearLayout.addView(createButton(JeoIndoorMapActivity.class)); linearLayout.addView(createButton(JeoIndoorMapActivity.class));
linearLayout.addView(createButton(OsmJsonMapActivity.class)); linearLayout.addView(createButton(OsmJsonMapActivity.class));
linearLayout.addView(createButton(VectorLayerMapActivity.class)); linearLayout.addView(createButton(VectorLayerMapActivity.class));
} }
private Button createButton(final Class<?> clazz) { private Button createButton(final Class<?> clazz) {
return this.createButton(clazz, null); return this.createButton(clazz, null);
} }
private Button createButton(final Class<?> clazz, String text) { private Button createButton(final Class<?> clazz, String text) {
Button button = new Button(this); Button button = new Button(this);
if (text == null) { if (text == null) {
button.setText(clazz.getSimpleName()); button.setText(clazz.getSimpleName());
} else { } else {
button.setText(text); button.setText(text);
} }
button.setOnClickListener(new OnClickListener() { button.setOnClickListener(new OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
startActivity(new Intent(Samples.this, clazz)); startActivity(new Intent(Samples.this, clazz));
} }
}); });
return button; return button;
} }
} }

View File

@@ -13,7 +13,10 @@
* *
* You should have received a copy of the GNU Lesser General Public License along with * You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>. * this program. If not, see <http://www.gnu.org/licenses/>.
*/package org.oscim.android.test; */
package org.oscim.android.test;
import android.os.Bundle;
import org.oscim.android.MapScaleBar; import org.oscim.android.MapScaleBar;
import org.oscim.core.MapPosition; import org.oscim.core.MapPosition;
@@ -25,63 +28,61 @@ import org.oscim.theme.IRenderTheme;
import org.oscim.theme.ThemeLoader; import org.oscim.theme.ThemeLoader;
import org.oscim.theme.VtmThemes; import org.oscim.theme.VtmThemes;
import android.os.Bundle;
public class SimpleMapActivity extends BaseMapActivity { public class SimpleMapActivity extends BaseMapActivity {
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
Layers layers = mMap.layers(); Layers layers = mMap.layers();
layers.add(new BuildingLayer(mMap, mBaseLayer)); layers.add(new BuildingLayer(mMap, mBaseLayer));
layers.add(new LabelLayer(mMap, mBaseLayer)); layers.add(new LabelLayer(mMap, mBaseLayer));
layers.add(new MapScaleBar(mMapView)); layers.add(new MapScaleBar(mMapView));
mMap.setTheme(VtmThemes.DEFAULT); mMap.setTheme(VtmThemes.DEFAULT);
} }
void runTheMonkey() { void runTheMonkey() {
themes[0] = ThemeLoader.load(VtmThemes.DEFAULT); themes[0] = ThemeLoader.load(VtmThemes.DEFAULT);
themes[1] = ThemeLoader.load(VtmThemes.OSMARENDER); themes[1] = ThemeLoader.load(VtmThemes.OSMARENDER);
themes[2] = ThemeLoader.load(VtmThemes.TRONRENDER); themes[2] = ThemeLoader.load(VtmThemes.TRONRENDER);
loooop(1); loooop(1);
} }
IRenderTheme[] themes = new IRenderTheme[3]; IRenderTheme[] themes = new IRenderTheme[3];
// Stress testing // Stress testing
void loooop(final int i) { void loooop(final int i) {
final long time = (long) (500 + Math.random() * 1000); final long time = (long) (500 + Math.random() * 1000);
mMapView.postDelayed(new Runnable() { mMapView.postDelayed(new Runnable() {
@Override @Override
public void run() { public void run() {
mMapView.map().setTheme(themes[i]); mMapView.map().setTheme(themes[i]);
MapPosition p = new MapPosition(); MapPosition p = new MapPosition();
if (i == 1) { if (i == 1) {
mMapView.map().getMapPosition(p); mMapView.map().getMapPosition(p);
p.setScale(4); p.setScale(4);
mMapView.map().animator().animateTo(time, p); mMapView.map().animator().animateTo(time, p);
} else { } else {
//mMapView.map().setMapPosition(p); //mMapView.map().setMapPosition(p);
p.setScale(2 + (1 << (int) (Math.random() * 13))); p.setScale(2 + (1 << (int) (Math.random() * 13)));
// p.setX((p.getX() + (Math.random() * 4 - 2) / p.getScale())); // p.setX((p.getX() + (Math.random() * 4 - 2) / p.getScale()));
// p.setY((p.getY() + (Math.random() * 4 - 2) / p.getScale())); // p.setY((p.getY() + (Math.random() * 4 - 2) / p.getScale()));
p.setX(MercatorProjection.longitudeToX(Math.random() * 180)); p.setX(MercatorProjection.longitudeToX(Math.random() * 180));
p.setY(MercatorProjection.latitudeToY(Math.random() * 60)); p.setY(MercatorProjection.latitudeToY(Math.random() * 60));
p.setTilt((float) (Math.random() * 60)); p.setTilt((float) (Math.random() * 60));
p.setBearing((float) (Math.random() * 360)); p.setBearing((float) (Math.random() * 360));
//mMapView.map().setMapPosition(p); //mMapView.map().setMapPosition(p);
mMapView.map().animator().animateTo(time, p); mMapView.map().animator().animateTo(time, p);
} }
loooop((i + 1) % 2); loooop((i + 1) % 2);
} }
}, time); }, time);
} }
} }

View File

@@ -1,7 +1,11 @@
package org.oscim.android.test; package org.oscim.android.test;
import static org.oscim.utils.ColorUtil.modHsv; import android.os.Bundle;
import static org.oscim.utils.ColorUtil.shiftHue; import android.view.View;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.ToggleButton;
import org.oscim.layers.tile.buildings.BuildingLayer; import org.oscim.layers.tile.buildings.BuildingLayer;
import org.oscim.layers.tile.vector.VectorTileLayer; import org.oscim.layers.tile.vector.VectorTileLayer;
@@ -20,169 +24,165 @@ import org.oscim.theme.styles.RenderStyle;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import android.os.Bundle; import static org.oscim.utils.ColorUtil.modHsv;
import android.view.View; import static org.oscim.utils.ColorUtil.shiftHue;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.ToggleButton;
public class ThemeStylerActivity extends BaseMapActivity implements OnSeekBarChangeListener { public class ThemeStylerActivity extends BaseMapActivity implements OnSeekBarChangeListener {
final Logger log = LoggerFactory.getLogger(ThemeStylerActivity.class); final Logger log = LoggerFactory.getLogger(ThemeStylerActivity.class);
public ThemeStylerActivity() { public ThemeStylerActivity() {
super(R.layout.activity_map_styler); super(R.layout.activity_map_styler);
} }
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
((SeekBar) findViewById(R.id.seekBarH)).setOnSeekBarChangeListener(this); ((SeekBar) findViewById(R.id.seekBarH)).setOnSeekBarChangeListener(this);
((SeekBar) findViewById(R.id.seekBarS)).setOnSeekBarChangeListener(this); ((SeekBar) findViewById(R.id.seekBarS)).setOnSeekBarChangeListener(this);
((SeekBar) findViewById(R.id.seekBarV)).setOnSeekBarChangeListener(this); ((SeekBar) findViewById(R.id.seekBarV)).setOnSeekBarChangeListener(this);
Layers layers = mMap.layers(); Layers layers = mMap.layers();
layers.add(new BuildingLayer(mMap, mBaseLayer)); layers.add(new BuildingLayer(mMap, mBaseLayer));
layers.add(new LabelLayer(mMap, mBaseLayer)); layers.add(new LabelLayer(mMap, mBaseLayer));
mMap.setTheme(VtmThemes.DEFAULT); mMap.setTheme(VtmThemes.DEFAULT);
} }
class ModStyleVisitor extends RuleVisitor { class ModStyleVisitor extends RuleVisitor {
private final LineBuilder<?> lineBuilder = LineStyle.builder(); private final LineBuilder<?> lineBuilder = LineStyle.builder();
private final AreaBuilder<?> areaBuilder = AreaStyle.builder(); private final AreaBuilder<?> areaBuilder = AreaStyle.builder();
@Override @Override
public void apply(Rule r) { public void apply(Rule r) {
for (RenderStyle style : r.styles) { for (RenderStyle style : r.styles) {
if (style instanceof LineStyle) { if (style instanceof LineStyle) {
LineStyle s = (LineStyle) style; LineStyle s = (LineStyle) style;
HSV c = lineColor; HSV c = lineColor;
if (lineColor.changed && s.outline) if (lineColor.changed && s.outline)
continue; continue;
if (outlineColor.changed) { if (outlineColor.changed) {
if (!s.outline) if (!s.outline)
continue; continue;
c = outlineColor; c = outlineColor;
} }
s.set(lineBuilder.set(s) s.set(lineBuilder.set(s)
.color(modColor(s.color, c)) .color(modColor(s.color, c))
.stippleColor(modColor(s.stippleColor, c)) .stippleColor(modColor(s.stippleColor, c))
.build()); .build());
continue; continue;
} }
if (areaColor.changed && style instanceof AreaStyle) { if (areaColor.changed && style instanceof AreaStyle) {
AreaStyle s = (AreaStyle) style; AreaStyle s = (AreaStyle) style;
s.set(areaBuilder.set(s) s.set(areaBuilder.set(s)
.color(modColor(s.color, areaColor)) .color(modColor(s.color, areaColor))
.blendColor(modColor(s.blendColor, areaColor)) .blendColor(modColor(s.blendColor, areaColor))
.strokeColor(modColor(s.strokeColor, areaColor)) .strokeColor(modColor(s.strokeColor, areaColor))
.build()); .build());
} }
} }
super.apply(r); super.apply(r);
} }
} }
int modColor(int color, HSV hsv) { int modColor(int color, HSV hsv) {
return modHsv(shiftHue(color, hsv.hue), 1, hsv.sat, hsv.val, true); return modHsv(shiftHue(color, hsv.hue), 1, hsv.sat, hsv.val, true);
} }
public static class HSV { public static class HSV {
public double hue = 0; public double hue = 0;
public double sat = 1; public double sat = 1;
public double val = 1; public double val = 1;
public boolean changed; public boolean changed;
} }
HSV lineColor = new HSV(); HSV lineColor = new HSV();
HSV outlineColor = new HSV(); HSV outlineColor = new HSV();
HSV areaColor = new HSV(); HSV areaColor = new HSV();
ModStyleVisitor mStyleVisitor = new ModStyleVisitor(); ModStyleVisitor mStyleVisitor = new ModStyleVisitor();
@Override @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (!fromUser) if (!fromUser)
return; return;
int id = seekBar.getId(); int id = seekBar.getId();
boolean modLine = ((RadioButton) findViewById(R.id.checkBoxLine)).isChecked(); boolean modLine = ((RadioButton) findViewById(R.id.checkBoxLine)).isChecked();
boolean modArea = ((RadioButton) findViewById(R.id.checkBoxArea)).isChecked(); boolean modArea = ((RadioButton) findViewById(R.id.checkBoxArea)).isChecked();
HSV c; HSV c;
if (modArea) if (modArea)
c = areaColor; c = areaColor;
else if (modLine) else if (modLine)
c = lineColor; c = lineColor;
else else
c = outlineColor; c = outlineColor;
if (id == R.id.seekBarS) if (id == R.id.seekBarS)
c.sat = progress / 50f; c.sat = progress / 50f;
else if (id == R.id.seekBarV) else if (id == R.id.seekBarV)
c.val = progress / 50f; c.val = progress / 50f;
else if (id == R.id.seekBarH) else if (id == R.id.seekBarH)
c.hue = progress / 100f; c.hue = progress / 100f;
log.debug((modArea ? "area" : "line") log.debug((modArea ? "area" : "line")
+ " h:" + c.hue + " h:" + c.hue
+ " s:" + c.sat + " s:" + c.sat
+ " v:" + c.val); + " v:" + c.val);
VectorTileLayer l = (VectorTileLayer) mMap.layers().get(1); VectorTileLayer l = (VectorTileLayer) mMap.layers().get(1);
RenderTheme t = (RenderTheme) l.getTheme(); RenderTheme t = (RenderTheme) l.getTheme();
c.changed = true; c.changed = true;
t.traverseRules(mStyleVisitor); t.traverseRules(mStyleVisitor);
t.updateStyles(); t.updateStyles();
c.changed = false; c.changed = false;
if (modArea) if (modArea)
MapRenderer.setBackgroundColor(modColor(t.getMapBackground(), c)); MapRenderer.setBackgroundColor(modColor(t.getMapBackground(), c));
mMap.render(); mMap.render();
} }
@Override @Override
public void onStartTrackingTouch(SeekBar seekBar) { public void onStartTrackingTouch(SeekBar seekBar) {
} }
@Override @Override
public void onStopTrackingTouch(SeekBar seekBar) { public void onStopTrackingTouch(SeekBar seekBar) {
} }
public void onToggleControls(View view) { public void onToggleControls(View view) {
findViewById(R.id.controls).setVisibility(((ToggleButton) view).isChecked() ? findViewById(R.id.controls).setVisibility(((ToggleButton) view).isChecked() ?
View.VISIBLE : View.GONE); View.VISIBLE : View.GONE);
} }
public void onRadioButtonClicked(View view) { public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked(); boolean checked = ((RadioButton) view).isChecked();
if (!checked) if (!checked)
return; return;
HSV c = null; HSV c = null;
switch (view.getId()) { switch (view.getId()) {
case R.id.checkBoxArea: case R.id.checkBoxArea:
c = areaColor; c = areaColor;
break; break;
case R.id.checkBoxLine: case R.id.checkBoxLine:
c = lineColor; c = lineColor;
break; break;
case R.id.checkBoxOutline: case R.id.checkBoxOutline:
c = outlineColor; c = outlineColor;
break; break;
} }
if (c == null) if (c == null)
return; return;
((SeekBar) findViewById(R.id.seekBarS)).setProgress((int) (c.sat * 50)); ((SeekBar) findViewById(R.id.seekBarS)).setProgress((int) (c.sat * 50));
((SeekBar) findViewById(R.id.seekBarV)).setProgress((int) (c.val * 50)); ((SeekBar) findViewById(R.id.seekBarV)).setProgress((int) (c.val * 50));
((SeekBar) findViewById(R.id.seekBarH)).setProgress((int) (c.hue * 100)); ((SeekBar) findViewById(R.id.seekBarH)).setProgress((int) (c.hue * 100));
} }
} }

View File

@@ -17,6 +17,8 @@
*/ */
package org.oscim.android.test; package org.oscim.android.test;
import android.os.Bundle;
import org.oscim.backend.canvas.Color; import org.oscim.backend.canvas.Color;
import org.oscim.layers.TileGridLayer; import org.oscim.layers.TileGridLayer;
import org.oscim.layers.vector.VectorLayer; import org.oscim.layers.vector.VectorLayer;
@@ -25,73 +27,71 @@ import org.oscim.layers.vector.geometries.Style;
import org.oscim.theme.VtmThemes; import org.oscim.theme.VtmThemes;
import org.oscim.utils.ColorUtil; import org.oscim.utils.ColorUtil;
import android.os.Bundle;
public class VectorLayerMapActivity extends BaseMapActivity { public class VectorLayerMapActivity extends BaseMapActivity {
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
mMap.setTheme(VtmThemes.DEFAULT); mMap.setTheme(VtmThemes.DEFAULT);
VectorLayer vectorLayer = new VectorLayer(mMap); VectorLayer vectorLayer = new VectorLayer(mMap);
// Geometry g = new GeomBuilder() // Geometry g = new GeomBuilder()
// .point(8.8, 53.1) // .point(8.8, 53.1)
// .point() // .point()
// .buffer(1) // .buffer(1)
// .get(); // .get();
// //
// vectorLayer.add(new PolygonDrawable(g, defaultStyle())); // vectorLayer.add(new PolygonDrawable(g, defaultStyle()));
// //
// vectorLayer.add(new PointDrawable(53.1, 8.8, Style.builder() // vectorLayer.add(new PointDrawable(53.1, 8.8, Style.builder()
// .setBuffer(0.5) // .setBuffer(0.5)
// .setFillColor(Color.RED) // .setFillColor(Color.RED)
// .setFillAlpha(0.2) // .setFillAlpha(0.2)
// .build())); // .build()));
// //
// Style.Builder sb = Style.builder() // Style.Builder sb = Style.builder()
// .setBuffer(0.5) // .setBuffer(0.5)
// .setFillColor(Color.RED) // .setFillColor(Color.RED)
// .setFillAlpha(0.2); // .setFillAlpha(0.2);
// //
// Style style = sb.setFillAlpha(0.2).build(); // Style style = sb.setFillAlpha(0.2).build();
// //
// int tileSize = 5; // int tileSize = 5;
// for (int x = -180; x < 180; x += tileSize) { // for (int x = -180; x < 180; x += tileSize) {
// for (int y = -90; y < 90; y += tileSize) { // for (int y = -90; y < 90; y += tileSize) {
// // Style style = sb.setFillAlpha(FastMath.clamp(FastMath.length(x, y) / 180, 0.2, 1)) // // Style style = sb.setFillAlpha(FastMath.clamp(FastMath.length(x, y) / 180, 0.2, 1))
// // .build(); // // .build();
// //
// vectorLayer.add(new RectangleDrawable(FastMath.clamp(y, -85, 85), x, // vectorLayer.add(new RectangleDrawable(FastMath.clamp(y, -85, 85), x,
// FastMath.clamp(y + tileSize - 0.1, -85, 85), // FastMath.clamp(y + tileSize - 0.1, -85, 85),
// x + tileSize - 0.1, style)); // x + tileSize - 0.1, style));
// //
// } // }
// } // }
Style.Builder sb = Style.builder() Style.Builder sb = Style.builder()
.buffer(0.5) .buffer(0.5)
.fillColor(Color.RED) .fillColor(Color.RED)
.fillAlpha(0.2); .fillAlpha(0.2);
for (int i = 0; i < 2000; i++) { for (int i = 0; i < 2000; i++) {
Style style = sb.buffer(Math.random() + 0.2) Style style = sb.buffer(Math.random() + 0.2)
.fillColor(ColorUtil.setHue(Color.RED, .fillColor(ColorUtil.setHue(Color.RED,
(int) (Math.random() * 50) / 50.0)) (int) (Math.random() * 50) / 50.0))
.fillAlpha(0.5) .fillAlpha(0.5)
.build(); .build();
vectorLayer.add(new PointDrawable(Math.random() * 180 - 90, vectorLayer.add(new PointDrawable(Math.random() * 180 - 90,
Math.random() * 360 - 180, Math.random() * 360 - 180,
style)); style));
} }
mMap.layers().add(vectorLayer); mMap.layers().add(vectorLayer);
mMap.layers().add(new TileGridLayer(mMap, 0xff222222, 1.2f, 1)); mMap.layers().add(new TileGridLayer(mMap, 0xff222222, 1.2f, 1));
mMap.setMapPosition(0, 0, 1 << 2); mMap.setMapPosition(0, 0, 1 << 2);
} }
} }

View File

@@ -2,7 +2,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.oscim.gdx" package="org.oscim.gdx"
android:versionCode="1" android:versionCode="1"
android:versionName="1.0" > android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
@@ -13,15 +13,15 @@
android:targetSdkVersion="22" /> android:targetSdkVersion="22" />
<application <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher" android:icon="@drawable/ic_launcher"
android:label="@string/app_name" android:label="@string/app_name">
android:allowBackup="true" >
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:label="@string/app_name" android:label="@string/app_name"
android:screenOrientation="portrait" android:screenOrientation="portrait">
android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
@@ -29,4 +29,4 @@
</activity> </activity>
</application> </application>
</manifest> </manifest>

View File

@@ -3,9 +3,12 @@
# #
# This file must be checked in Version Control Systems. # This file must be checked in Version Control Systems.
# #
# To customize properties used by the Ant build system use, # To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your # "ant.properties", and override values to adapt the script to your
# project structure. # project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target. # Project target.
target=android-21 target=android-23

View File

@@ -2,6 +2,6 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical" > android:orientation="vertical">
</LinearLayout> </LinearLayout>

View File

@@ -16,88 +16,88 @@
*/ */
package org.oscim.android.canvas; package org.oscim.android.canvas;
import static android.graphics.Bitmap.Config.ARGB_8888;
import java.io.InputStream;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import android.opengl.GLES20; import android.opengl.GLES20;
import android.opengl.GLUtils; import android.opengl.GLUtils;
import java.io.InputStream;
import static android.graphics.Bitmap.Config.ARGB_8888;
public class AndroidBitmap implements org.oscim.backend.canvas.Bitmap { public class AndroidBitmap implements org.oscim.backend.canvas.Bitmap {
final Bitmap mBitmap; final Bitmap mBitmap;
public AndroidBitmap(InputStream inputStream) { public AndroidBitmap(InputStream inputStream) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream); Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
try { try {
GLUtils.getType(bitmap); GLUtils.getType(bitmap);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
bitmap = bitmap.copy(ARGB_8888, false); bitmap = bitmap.copy(ARGB_8888, false);
} }
mBitmap = bitmap; mBitmap = bitmap;
} }
@Override @Override
public boolean isValid() { public boolean isValid() {
return mBitmap != null; return mBitmap != null;
} }
/** /**
* @param format ignored always ARGB8888 * @param format ignored always ARGB8888
*/ */
public AndroidBitmap(int width, int height, int format) { public AndroidBitmap(int width, int height, int format) {
mBitmap = android.graphics.Bitmap mBitmap = android.graphics.Bitmap
.createBitmap(width, height, ARGB_8888); .createBitmap(width, height, ARGB_8888);
} }
public AndroidBitmap(android.graphics.Bitmap bitmap) { public AndroidBitmap(android.graphics.Bitmap bitmap) {
mBitmap = bitmap; mBitmap = bitmap;
} }
@Override @Override
public int getWidth() { public int getWidth() {
return mBitmap.getWidth(); return mBitmap.getWidth();
} }
@Override @Override
public int getHeight() { public int getHeight() {
return mBitmap.getHeight(); return mBitmap.getHeight();
} }
@Override @Override
public int[] getPixels() { public int[] getPixels() {
int width = getWidth(); int width = getWidth();
int height = getHeight(); int height = getHeight();
int[] colors = new int[width * height]; int[] colors = new int[width * height];
mBitmap.getPixels(colors, 0, width, 0, 0, width, height); mBitmap.getPixels(colors, 0, width, 0, 0, width, height);
return colors; return colors;
} }
@Override @Override
public void eraseColor(int color) { public void eraseColor(int color) {
//int a = android.graphics.Color.TRANSPARENT; //int a = android.graphics.Color.TRANSPARENT;
mBitmap.eraseColor(color); mBitmap.eraseColor(color);
} }
@Override @Override
public void uploadToTexture(boolean replace) { public void uploadToTexture(boolean replace) {
int format = GLUtils.getInternalFormat(mBitmap); int format = GLUtils.getInternalFormat(mBitmap);
int type = GLUtils.getType(mBitmap); int type = GLUtils.getType(mBitmap);
if (replace) if (replace)
GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, 0, 0, GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, 0, 0,
mBitmap, format, type); mBitmap, format, type);
else else
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, format, GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, format,
mBitmap, type, 0); mBitmap, type, 0);
} }
@Override @Override
public void recycle() { public void recycle() {
if (mBitmap == null) if (mBitmap == null)
return; return;
mBitmap.recycle(); mBitmap.recycle();
} }
} }

View File

@@ -21,31 +21,31 @@ import org.oscim.backend.canvas.Canvas;
import org.oscim.backend.canvas.Paint; import org.oscim.backend.canvas.Paint;
public class AndroidCanvas implements Canvas { public class AndroidCanvas implements Canvas {
final android.graphics.Canvas canvas; final android.graphics.Canvas canvas;
public AndroidCanvas() { public AndroidCanvas() {
canvas = new android.graphics.Canvas(); canvas = new android.graphics.Canvas();
} }
@Override @Override
public void setBitmap(Bitmap bitmap) { public void setBitmap(Bitmap bitmap) {
canvas.setBitmap(((AndroidBitmap) bitmap).mBitmap); canvas.setBitmap(((AndroidBitmap) bitmap).mBitmap);
} }
@Override @Override
public void drawText(String string, float x, float y, Paint fill, Paint stroke) { public void drawText(String string, float x, float y, Paint fill, Paint stroke) {
if (string != null) { if (string != null) {
if (stroke != null) if (stroke != null)
canvas.drawText(string, x, y, ((AndroidPaint) stroke).mPaint); canvas.drawText(string, x, y, ((AndroidPaint) stroke).mPaint);
canvas.drawText(string, x, y, ((AndroidPaint) fill).mPaint); canvas.drawText(string, x, y, ((AndroidPaint) fill).mPaint);
} }
} }
@Override @Override
public void drawBitmap(Bitmap bitmap, float x, float y) { public void drawBitmap(Bitmap bitmap, float x, float y) {
canvas.drawBitmap(((AndroidBitmap) bitmap).mBitmap, x, y, null); canvas.drawBitmap(((AndroidBitmap) bitmap).mBitmap, x, y, null);
} }
} }

View File

@@ -17,8 +17,10 @@
*/ */
package org.oscim.android.canvas; package org.oscim.android.canvas;
import java.io.IOException; import android.content.res.Resources;
import java.io.InputStream; import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import org.oscim.backend.CanvasAdapter; import org.oscim.backend.CanvasAdapter;
import org.oscim.backend.canvas.Bitmap; import org.oscim.backend.canvas.Bitmap;
@@ -27,99 +29,97 @@ import org.oscim.backend.canvas.Paint;
import org.oscim.layers.marker.MarkerItem.HotspotPlace; import org.oscim.layers.marker.MarkerItem.HotspotPlace;
import org.oscim.layers.marker.MarkerSymbol; import org.oscim.layers.marker.MarkerSymbol;
import android.content.res.Resources; import java.io.IOException;
import android.graphics.Bitmap.Config; import java.io.InputStream;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
public final class AndroidGraphics extends CanvasAdapter { public final class AndroidGraphics extends CanvasAdapter {
public static void init() { public static void init() {
CanvasAdapter.init(new AndroidGraphics()); CanvasAdapter.init(new AndroidGraphics());
} }
public static android.graphics.Paint getAndroidPaint(Paint paint) { public static android.graphics.Paint getAndroidPaint(Paint paint) {
return ((AndroidPaint) paint).mPaint; return ((AndroidPaint) paint).mPaint;
} }
public static android.graphics.Bitmap getBitmap(Bitmap bitmap) { public static android.graphics.Bitmap getBitmap(Bitmap bitmap) {
return ((AndroidBitmap) bitmap).mBitmap; return ((AndroidBitmap) bitmap).mBitmap;
} }
private AndroidGraphics() { private AndroidGraphics() {
// do nothing // do nothing
} }
@Override @Override
public Bitmap decodeBitmapImpl(InputStream inputStream) { public Bitmap decodeBitmapImpl(InputStream inputStream) {
return new AndroidBitmap(inputStream); return new AndroidBitmap(inputStream);
} }
@Override @Override
public Bitmap loadBitmapAssetImpl(String fileName) { public Bitmap loadBitmapAssetImpl(String fileName) {
try { try {
return createBitmap(fileName); return createBitmap(fileName);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
@Override @Override
public Paint newPaintImpl() { public Paint newPaintImpl() {
return new AndroidPaint(); return new AndroidPaint();
} }
@Override @Override
public Bitmap newBitmapImpl(int width, int height, int format) { public Bitmap newBitmapImpl(int width, int height, int format) {
return new AndroidBitmap(width, height, format); return new AndroidBitmap(width, height, format);
} }
@Override @Override
public Canvas newCanvasImpl() { public Canvas newCanvasImpl() {
return new AndroidCanvas(); return new AndroidCanvas();
} }
//------------------------------------- //-------------------------------------
public static Bitmap drawableToBitmap(Drawable drawable) { public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) { if (drawable instanceof BitmapDrawable) {
return new AndroidBitmap(((BitmapDrawable) drawable).getBitmap()); return new AndroidBitmap(((BitmapDrawable) drawable).getBitmap());
} }
android.graphics.Bitmap bitmap = android.graphics.Bitmap android.graphics.Bitmap bitmap = android.graphics.Bitmap
.createBitmap(drawable.getIntrinsicWidth(), .createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), drawable.getIntrinsicHeight(),
Config.ARGB_8888); Config.ARGB_8888);
android.graphics.Canvas canvas = new android.graphics.Canvas(bitmap); android.graphics.Canvas canvas = new android.graphics.Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas); drawable.draw(canvas);
return new AndroidBitmap(bitmap); return new AndroidBitmap(bitmap);
} }
public static Bitmap drawableToBitmap(Resources res, int resId) { public static Bitmap drawableToBitmap(Resources res, int resId) {
return new AndroidBitmap(res.openRawResource(resId)); return new AndroidBitmap(res.openRawResource(resId));
} }
/** /**
* @deprecated * @deprecated
*/ */
public static MarkerSymbol makeMarker(Drawable drawable, HotspotPlace place) { public static MarkerSymbol makeMarker(Drawable drawable, HotspotPlace place) {
if (place == null) if (place == null)
place = HotspotPlace.CENTER; place = HotspotPlace.CENTER;
return new MarkerSymbol(drawableToBitmap(drawable), place); return new MarkerSymbol(drawableToBitmap(drawable), place);
} }
/** /**
* @deprecated * @deprecated
*/ */
public static MarkerSymbol makeMarker(Resources res, int resId, HotspotPlace place) { public static MarkerSymbol makeMarker(Resources res, int resId, HotspotPlace place) {
if (place == null) if (place == null)
place = HotspotPlace.CENTER; place = HotspotPlace.CENTER;
InputStream in = res.openRawResource(resId); InputStream in = res.openRawResource(resId);
return new MarkerSymbol(new AndroidBitmap(in), place); return new MarkerSymbol(new AndroidBitmap(in), place);
} }
} }

View File

@@ -16,110 +16,110 @@
*/ */
package org.oscim.android.canvas; package org.oscim.android.canvas;
import org.oscim.backend.canvas.Paint;
import android.graphics.Paint.FontMetrics; import android.graphics.Paint.FontMetrics;
import android.graphics.Typeface; import android.graphics.Typeface;
import org.oscim.backend.canvas.Paint;
class AndroidPaint implements Paint { class AndroidPaint implements Paint {
private static int getStyle(org.oscim.backend.canvas.Paint.FontStyle fontStyle) { private static int getStyle(org.oscim.backend.canvas.Paint.FontStyle fontStyle) {
switch (fontStyle) { switch (fontStyle) {
case BOLD: case BOLD:
return 1; return 1;
case BOLD_ITALIC: case BOLD_ITALIC:
return 3; return 3;
case ITALIC: case ITALIC:
return 2; return 2;
case NORMAL: case NORMAL:
return 0; return 0;
} }
throw new IllegalArgumentException("unknown font style: " + fontStyle); throw new IllegalArgumentException("unknown font style: " + fontStyle);
} }
private static Typeface getTypeface(org.oscim.backend.canvas.Paint.FontFamily fontFamily) { private static Typeface getTypeface(org.oscim.backend.canvas.Paint.FontFamily fontFamily) {
switch (fontFamily) { switch (fontFamily) {
case DEFAULT: case DEFAULT:
return Typeface.DEFAULT; return Typeface.DEFAULT;
case DEFAULT_BOLD: case DEFAULT_BOLD:
return Typeface.DEFAULT_BOLD; return Typeface.DEFAULT_BOLD;
case MONOSPACE: case MONOSPACE:
return Typeface.MONOSPACE; return Typeface.MONOSPACE;
case SANS_SERIF: case SANS_SERIF:
return Typeface.SANS_SERIF; return Typeface.SANS_SERIF;
case SERIF: case SERIF:
return Typeface.SERIF; return Typeface.SERIF;
} }
throw new IllegalArgumentException("unknown font family: " + fontFamily); throw new IllegalArgumentException("unknown font family: " + fontFamily);
} }
final android.graphics.Paint mPaint; final android.graphics.Paint mPaint;
AndroidPaint() { AndroidPaint() {
mPaint = new android.graphics.Paint( mPaint = new android.graphics.Paint(
android.graphics.Paint.ANTI_ALIAS_FLAG); android.graphics.Paint.ANTI_ALIAS_FLAG);
} }
@Override @Override
public int getColor() { public int getColor() {
return mPaint.getColor(); return mPaint.getColor();
} }
@Override @Override
public void setColor(int color) { public void setColor(int color) {
mPaint.setColor(color); mPaint.setColor(color);
} }
@Override @Override
public void setStrokeCap(Cap cap) { public void setStrokeCap(Cap cap) {
android.graphics.Paint.Cap androidCap = android.graphics.Paint.Cap android.graphics.Paint.Cap androidCap = android.graphics.Paint.Cap
.valueOf(cap.name()); .valueOf(cap.name());
mPaint.setStrokeCap(androidCap); mPaint.setStrokeCap(androidCap);
} }
@Override @Override
public void setStrokeWidth(float width) { public void setStrokeWidth(float width) {
mPaint.setStrokeWidth(width); mPaint.setStrokeWidth(width);
} }
@Override @Override
public void setStyle(Style style) { public void setStyle(Style style) {
mPaint.setStyle(android.graphics.Paint.Style.valueOf(style.name())); mPaint.setStyle(android.graphics.Paint.Style.valueOf(style.name()));
} }
@Override @Override
public void setTextAlign(Align align) { public void setTextAlign(Align align) {
//mPaint.setTextAlign(android.graphics.Paint.Align.valueOf(align.name())); //mPaint.setTextAlign(android.graphics.Paint.Align.valueOf(align.name()));
} }
@Override @Override
public void setTextSize(float textSize) { public void setTextSize(float textSize) {
mPaint.setTextSize(textSize); mPaint.setTextSize(textSize);
} }
@Override @Override
public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) { public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) {
Typeface typeface = Typeface.create(getTypeface(fontFamily), Typeface typeface = Typeface.create(getTypeface(fontFamily),
getStyle(fontStyle)); getStyle(fontStyle));
mPaint.setTypeface(typeface); mPaint.setTypeface(typeface);
} }
@Override @Override
public float measureText(String text) { public float measureText(String text) {
return mPaint.measureText(text); return mPaint.measureText(text);
} }
@Override @Override
public float getFontHeight() { public float getFontHeight() {
FontMetrics fm = mPaint.getFontMetrics(); FontMetrics fm = mPaint.getFontMetrics();
return (float) Math.ceil(Math.abs(fm.bottom) + Math.abs(fm.top)); return (float) Math.ceil(Math.abs(fm.bottom) + Math.abs(fm.top));
} }
@Override @Override
public float getFontDescent() { public float getFontDescent() {
FontMetrics fm = mPaint.getFontMetrics(); FontMetrics fm = mPaint.getFontMetrics();
// //fontDescent = (float) Math.ceil(Math.abs(fm.descent)); // //fontDescent = (float) Math.ceil(Math.abs(fm.descent));
return Math.abs(fm.bottom); return Math.abs(fm.bottom);
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -17,42 +17,42 @@
*/ */
package org.oscim.gdx; package org.oscim.gdx;
import org.oscim.android.canvas.AndroidGraphics;
import org.oscim.backend.GLAdapter;
import org.oscim.core.Tile;
import org.oscim.tiling.TileSource;
import org.oscim.tiling.source.oscimap4.OSciMap4TileSource;
import android.os.Bundle; import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.badlogic.gdx.utils.SharedLibraryLoader; import com.badlogic.gdx.utils.SharedLibraryLoader;
import org.oscim.android.canvas.AndroidGraphics;
import org.oscim.backend.GLAdapter;
import org.oscim.core.Tile;
import org.oscim.tiling.TileSource;
import org.oscim.tiling.source.oscimap4.OSciMap4TileSource;
public class MainActivity extends AndroidApplication { public class MainActivity extends AndroidApplication {
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
AndroidGraphics.init(); AndroidGraphics.init();
GdxAssets.init(""); GdxAssets.init("");
GLAdapter.init(new AndroidGL()); GLAdapter.init(new AndroidGL());
Tile.SIZE = 400; Tile.SIZE = 400;
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration(); AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
cfg.stencil = 8; cfg.stencil = 8;
new SharedLibraryLoader().load("vtm-jni"); new SharedLibraryLoader().load("vtm-jni");
initialize(new GdxMapAndroid(), cfg); initialize(new GdxMapAndroid(), cfg);
} }
class GdxMapAndroid extends GdxMap { class GdxMapAndroid extends GdxMap {
@Override @Override
public void createLayers() { public void createLayers() {
TileSource ts = new OSciMap4TileSource(); TileSource ts = new OSciMap4TileSource();
initDefaultLayers(ts, true, true, true); initDefaultLayers(ts, true, true, true);
} }
} }
} }

View File

@@ -1,31 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.oscim.android.start" package="org.oscim.android.start"
android:versionCode="1" android:versionCode="1"
android:versionName="1.0" > android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="22" />
<application <uses-sdk
android:label="VTM Start" android:minSdkVersion="10"
android:icon="@drawable/ic_launcher" android:targetSdkVersion="22" />
android:allowBackup="true"
android:theme="@style/AppTheme" >
<activity
android:name="org.oscim.android.start.TestActivity"
android:label="VTM Start" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <application
</intent-filter> android:allowBackup="true"
</activity> android:icon="@drawable/ic_launcher"
</application> android:label="VTM Start"
android:theme="@style/AppTheme">
<activity
android:name="org.oscim.android.start.TestActivity"
android:label="VTM Start">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest> </manifest>

View File

@@ -11,6 +11,4 @@
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target. # Project target.
target=android-21 target=android-23
android.library.reference.1=../appcompat
android.library.reference.2=../vtm-android

View File

@@ -1,12 +1,10 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" > android:layout_height="match_parent">
<org.oscim.android.MapView <org.oscim.android.MapView
android:id="@+id/mapView" android:id="@+id/mapView"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent" > android:layout_height="fill_parent"></org.oscim.android.MapView>
</org.oscim.android.MapView>
</RelativeLayout> </RelativeLayout>

View File

@@ -1,5 +1,8 @@
package org.oscim.android.start; package org.oscim.android.start;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import org.oscim.android.MapPreferences; import org.oscim.android.MapPreferences;
import org.oscim.android.MapView; import org.oscim.android.MapView;
import org.oscim.layers.tile.buildings.BuildingLayer; import org.oscim.layers.tile.buildings.BuildingLayer;
@@ -11,42 +14,39 @@ import org.oscim.tiling.source.oscimap4.OSciMap4TileSource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
public class TestActivity extends ActionBarActivity { public class TestActivity extends ActionBarActivity {
public static final Logger log = LoggerFactory.getLogger(TestActivity.class); public static final Logger log = LoggerFactory.getLogger(TestActivity.class);
MapView mMapView; MapView mMapView;
MapPreferences mPrefs; MapPreferences mPrefs;
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map); setContentView(R.layout.activity_map);
mMapView = (MapView) findViewById(R.id.mapView); mMapView = (MapView) findViewById(R.id.mapView);
Map map = mMapView.map(); Map map = mMapView.map();
mPrefs = new MapPreferences(TestActivity.class.getName(), this); mPrefs = new MapPreferences(TestActivity.class.getName(), this);
VectorTileLayer baseLayer = map.setBaseMap(new OSciMap4TileSource()); VectorTileLayer baseLayer = map.setBaseMap(new OSciMap4TileSource());
map.layers().add(new BuildingLayer(map, baseLayer)); map.layers().add(new BuildingLayer(map, baseLayer));
map.layers().add(new LabelLayer(map, baseLayer)); map.layers().add(new LabelLayer(map, baseLayer));
map.setTheme(VtmThemes.DEFAULT); map.setTheme(VtmThemes.DEFAULT);
} }
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
mPrefs.load(mMapView.map()); mPrefs.load(mMapView.map());
mMapView.onResume(); mMapView.onResume();
} }
@Override @Override
protected void onPause() { protected void onPause() {
super.onPause(); super.onPause();
mMapView.onPause(); mMapView.onPause();
mPrefs.save(mMapView.map()); mPrefs.save(mMapView.map());
} }
} }

View File

@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.eclipse.cdt.managedbuilder.core.genmakebuilder"/>
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS">
<mapEntry key="?children?" value="?name?=outputEntries\|?children?=?name?=entry\\\\\\\|\\\|?name?=entry\\\\\\\|\\\|\||"/>
<mapEntry key="?name?" value=""/>
<mapEntry key="org.eclipse.cdt.make.core.append_environment" value="true"/>
<mapEntry key="org.eclipse.cdt.make.core.buildArguments" value=""/>
<mapEntry key="org.eclipse.cdt.make.core.buildCommand" value="ndk-build"/>
<mapEntry key="org.eclipse.cdt.make.core.cleanBuildTarget" value="clean"/>
<mapEntry key="org.eclipse.cdt.make.core.contents" value="org.eclipse.cdt.make.core.activeConfigSettings"/>
<mapEntry key="org.eclipse.cdt.make.core.enableAutoBuild" value="false"/>
<mapEntry key="org.eclipse.cdt.make.core.enableCleanBuild" value="true"/>
<mapEntry key="org.eclipse.cdt.make.core.enableFullBuild" value="true"/>
<mapEntry key="org.eclipse.cdt.make.core.stopOnError" value="true"/>
<mapEntry key="org.eclipse.cdt.make.core.useDefaultBuildCmd" value="true"/>
</mapAttribute>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
</launchConfiguration>

View File

@@ -6,4 +6,4 @@
android:minSdkVersion="10" android:minSdkVersion="10"
android:targetSdkVersion="22" /> android:targetSdkVersion="22" />
</manifest> </manifest>

View File

@@ -1,18 +0,0 @@
# This file is used to override default values used by the Ant build system.
#
# This file must be checked in Version Control Systems, as it is
# integral to the build system of your project.
# This file is only used by the Ant script.
# You can use this to override default values such as
# 'source.dir' for the location of your java source folder and
# 'out.dir' for the location of your output folder.
# You can also use it define how the release builds are signed by declaring
# the following properties:
# 'key.store' for the location of your keystore and
# 'key.alias' for the name of the key to use.
# The password will be asked during the build when you use the 'release' target.
#jar.libs.dir=

View File

@@ -1,85 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="VectorTileMap" default="help">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<loadproperties srcFile="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project'"
unless="sdk.dir"
/>
<!-- extension targets. Uncomment the ones where you want to do custom work
in between standard targets -->
<!--
<target name="-pre-build">
</target>
<target name="-pre-compile">
</target>
/* This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir} */
<target name="-post-compile">
</target>
-->
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<lint>
<issue id="MissingTranslation" severity="warning" />
</lint>

View File

@@ -1,44 +0,0 @@
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-libraryjars lib/postgresql-9.0-801.jdbc4.jar
-ignorewarnings
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}

View File

@@ -3,15 +3,12 @@
# #
# This file must be checked in Version Control Systems. # This file must be checked in Version Control Systems.
# #
# To customize properties used by the Ant build system use, # To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your # "ant.properties", and override values to adapt the script to your
# project structure. # project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Indicates whether an apk should be generated for each density.
split.density=false
# Project target. # Project target.
target=android-21 target=android-23
#proguard.config=proguard.cfg
android.library=true
android.library.reference.1=../appcompat

View File

@@ -16,31 +16,31 @@
*/ */
package org.oscim.android; package org.oscim.android;
import java.io.IOException; import android.content.Context;
import java.io.InputStream;
import org.oscim.backend.AssetAdapter; import org.oscim.backend.AssetAdapter;
import android.content.Context; import java.io.IOException;
import java.io.InputStream;
public class AndroidAssets extends AssetAdapter { public class AndroidAssets extends AssetAdapter {
Context mContext; Context mContext;
public static void init(Context ctx) { public static void init(Context ctx) {
AssetAdapter.init(new AndroidAssets(ctx)); AssetAdapter.init(new AndroidAssets(ctx));
} }
private AndroidAssets(Context ctx) { private AndroidAssets(Context ctx) {
mContext = ctx; mContext = ctx;
} }
@Override @Override
public InputStream openFileAsStream(String fileName) { public InputStream openFileAsStream(String fileName) {
try { try {
return mContext.getAssets().open(fileName); return mContext.getAssets().open(fileName);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
} }

View File

@@ -16,56 +16,56 @@
*/ */
package org.oscim.android; package org.oscim.android;
import org.oscim.map.Map;
import android.content.Context; import android.content.Context;
import android.hardware.Sensor; import android.hardware.Sensor;
import android.hardware.SensorEvent; import android.hardware.SensorEvent;
import android.hardware.SensorEventListener; import android.hardware.SensorEventListener;
import android.hardware.SensorManager; import android.hardware.SensorManager;
import org.oscim.map.Map;
public class Compass { public class Compass {
private final SensorEventListener mListener = new SensorEventListener() { private final SensorEventListener mListener = new SensorEventListener() {
@Override @Override
public void onSensorChanged(SensorEvent event) { public void onSensorChanged(SensorEvent event) {
if (Math.abs(event.values[0] - mAngle) > 0.25) { if (Math.abs(event.values[0] - mAngle) > 0.25) {
mAngle = event.values[0]; mAngle = event.values[0];
if (mMap != null) { if (mMap != null) {
mMap.viewport().setRotation(-mAngle); mMap.viewport().setRotation(-mAngle);
mMap.updateMap(true); mMap.updateMap(true);
} }
} }
} }
@Override @Override
public void onAccuracyChanged(Sensor sensor, int accuracy) { public void onAccuracyChanged(Sensor sensor, int accuracy) {
} }
}; };
/* package */float mAngle = 0; /* package */ float mAngle = 0;
/* package */Map mMap; /* package */ Map mMap;
private final SensorManager mSensorManager; private final SensorManager mSensorManager;
private final Sensor mSensor; private final Sensor mSensor;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Compass(Context context, Map map) { public Compass(Context context, Map map) {
mMap = map; mMap = map;
mSensorManager = (SensorManager) context mSensorManager = (SensorManager) context
.getSystemService(Context.SENSOR_SERVICE); .getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
} }
public void enable() { public void enable() {
mSensorManager.registerListener(mListener, mSensor, mSensorManager.registerListener(mListener, mSensor,
SensorManager.SENSOR_DELAY_UI); SensorManager.SENSOR_DELAY_UI);
} }
public void disable() { public void disable() {
mSensorManager.unregisterListener(mListener); mSensorManager.unregisterListener(mListener);
mMap.viewport().setRotation(0); mMap.viewport().setRotation(0);
} }
} }

View File

@@ -16,80 +16,80 @@
*/ */
package org.oscim.android; package org.oscim.android;
import org.oscim.core.MapPosition;
import org.oscim.map.Map;
import android.app.Activity; import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.Editor;
import org.oscim.core.MapPosition;
import org.oscim.map.Map;
public class MapPreferences { public class MapPreferences {
private static final String KEY_LATITUDE = "latitude"; private static final String KEY_LATITUDE = "latitude";
private static final String KEY_LONGITUDE = "longitude"; private static final String KEY_LONGITUDE = "longitude";
private static final String KEY_SCALE = "scale"; private static final String KEY_SCALE = "scale";
private final String PREFERENCES_FILE; private final String PREFERENCES_FILE;
Context ctx; Context ctx;
public MapPreferences(String name, Context ctx) { public MapPreferences(String name, Context ctx) {
this.ctx = ctx; this.ctx = ctx;
this.PREFERENCES_FILE = name; this.PREFERENCES_FILE = name;
} }
public void clear() { public void clear() {
Editor editor = ctx.getSharedPreferences(PREFERENCES_FILE, Activity.MODE_PRIVATE).edit(); Editor editor = ctx.getSharedPreferences(PREFERENCES_FILE, Activity.MODE_PRIVATE).edit();
editor.clear(); editor.clear();
editor.apply(); editor.apply();
} }
private void putDouble(Editor editor, String key, double value) { private void putDouble(Editor editor, String key, double value) {
editor.putLong(key, Double.doubleToLongBits(value)); editor.putLong(key, Double.doubleToLongBits(value));
} }
private double getDouble(SharedPreferences prefs, String key) { private double getDouble(SharedPreferences prefs, String key) {
return Double.longBitsToDouble(prefs.getLong(key, 0)); return Double.longBitsToDouble(prefs.getLong(key, 0));
} }
public void save(Map map) { public void save(Map map) {
save(map.getMapPosition()); save(map.getMapPosition());
} }
public void save(MapPosition pos) { public void save(MapPosition pos) {
Editor editor = ctx.getSharedPreferences(PREFERENCES_FILE, Editor editor = ctx.getSharedPreferences(PREFERENCES_FILE,
Activity.MODE_PRIVATE).edit(); Activity.MODE_PRIVATE).edit();
editor.clear(); editor.clear();
putDouble(editor, KEY_LATITUDE, pos.y); putDouble(editor, KEY_LATITUDE, pos.y);
putDouble(editor, KEY_LONGITUDE, pos.x); putDouble(editor, KEY_LONGITUDE, pos.x);
putDouble(editor, KEY_SCALE, pos.scale); putDouble(editor, KEY_SCALE, pos.scale);
editor.apply(); editor.apply();
} }
private static boolean containsViewport(SharedPreferences prefs) { private static boolean containsViewport(SharedPreferences prefs) {
return prefs.contains(KEY_LATITUDE) return prefs.contains(KEY_LATITUDE)
&& prefs.contains(KEY_LONGITUDE) && prefs.contains(KEY_LONGITUDE)
&& prefs.contains(KEY_SCALE); && prefs.contains(KEY_SCALE);
} }
public boolean load(Map map) { public boolean load(Map map) {
MapPosition pos = map.getMapPosition(); MapPosition pos = map.getMapPosition();
if (load(pos)) { if (load(pos)) {
map.setMapPosition(pos); map.setMapPosition(pos);
return true; return true;
} }
return false; return false;
} }
public boolean load(MapPosition pos) { public boolean load(MapPosition pos) {
SharedPreferences prefs = ctx.getSharedPreferences(PREFERENCES_FILE, SharedPreferences prefs = ctx.getSharedPreferences(PREFERENCES_FILE,
Activity.MODE_PRIVATE); Activity.MODE_PRIVATE);
if (containsViewport(prefs)) { if (containsViewport(prefs)) {
pos.x = getDouble(prefs, KEY_LONGITUDE); pos.x = getDouble(prefs, KEY_LONGITUDE);
pos.y = getDouble(prefs, KEY_LATITUDE); pos.y = getDouble(prefs, KEY_LATITUDE);
pos.scale = getDouble(prefs, KEY_SCALE); pos.scale = getDouble(prefs, KEY_SCALE);
return true; return true;
} }
return false; return false;
} }
} }

View File

@@ -16,7 +16,11 @@ package org.oscim.android;
* this program. If not, see <http://www.gnu.org/licenses/>. * this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
import java.util.HashMap; import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import org.oscim.android.canvas.AndroidBitmap; import org.oscim.android.canvas.AndroidBitmap;
import org.oscim.core.MapPosition; import org.oscim.core.MapPosition;
@@ -27,11 +31,7 @@ import org.oscim.map.Map;
import org.oscim.map.Map.UpdateListener; import org.oscim.map.Map.UpdateListener;
import org.oscim.renderer.BitmapRenderer; import org.oscim.renderer.BitmapRenderer;
import android.graphics.Bitmap; import java.util.HashMap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
/** /**
* A MapScaleBar displays the ratio of a distance on the map to the * A MapScaleBar displays the ratio of a distance on the map to the
@@ -39,244 +39,239 @@ import android.graphics.Typeface;
*/ */
public class MapScaleBar extends Layer implements UpdateListener { public class MapScaleBar extends Layer implements UpdateListener {
private static final int BITMAP_HEIGHT = 64; private static final int BITMAP_HEIGHT = 64;
private static final int BITMAP_WIDTH = 128; private static final int BITMAP_WIDTH = 128;
private static final double LATITUDE_REDRAW_THRESHOLD = 0.2; private static final double LATITUDE_REDRAW_THRESHOLD = 0.2;
// private static final int MARGIN_BOTTOM = 5; // private static final int MARGIN_BOTTOM = 5;
// private static final int MARGIN_LEFT = 5; // private static final int MARGIN_LEFT = 5;
private static final double METER_FOOT_RATIO = 0.3048; private static final double METER_FOOT_RATIO = 0.3048;
private static final int ONE_KILOMETER = 1000; private static final int ONE_KILOMETER = 1000;
private static final int ONE_MILE = 5280; private static final int ONE_MILE = 5280;
private static final Paint SCALE_BAR = new Paint(Paint.ANTI_ALIAS_FLAG); private static final Paint SCALE_BAR = new Paint(Paint.ANTI_ALIAS_FLAG);
private static final Paint SCALE_BAR_STROKE = new Paint(Paint.ANTI_ALIAS_FLAG); private static final Paint SCALE_BAR_STROKE = new Paint(Paint.ANTI_ALIAS_FLAG);
private static final Paint SCALE_TEXT = new Paint(Paint.ANTI_ALIAS_FLAG); private static final Paint SCALE_TEXT = new Paint(Paint.ANTI_ALIAS_FLAG);
private static final Paint SCALE_TEXT_STROKE = new Paint(Paint.ANTI_ALIAS_FLAG); private static final Paint SCALE_TEXT_STROKE = new Paint(Paint.ANTI_ALIAS_FLAG);
private static final int[] SCALE_BAR_VALUES_IMPERIAL = { private static final int[] SCALE_BAR_VALUES_IMPERIAL = {
26400000, 10560000, 5280000, 26400000, 10560000, 5280000,
2640000, 1056000, 528000, 2640000, 1056000, 528000,
264000, 105600, 52800, 26400, 264000, 105600, 52800, 26400,
10560, 5280, 2000, 1000, 500, 10560, 5280, 2000, 1000, 500,
200, 100, 50, 20, 200, 100, 50, 20,
10, 5, 2, 1 }; 10, 5, 2, 1};
private static final int[] SCALE_BAR_VALUES_METRIC = { private static final int[] SCALE_BAR_VALUES_METRIC = {
10000000, 5000000, 2000000, 1000000, 10000000, 5000000, 2000000, 1000000,
500000, 200000, 100000, 50000, 500000, 200000, 100000, 50000,
20000, 10000, 5000, 2000, 1000, 20000, 10000, 5000, 2000, 1000,
500, 200, 100, 50, 20, 10, 5, 2, 1 }; 500, 200, 100, 50, 20, 10, 5, 2, 1};
private boolean mImperialUnits; private boolean mImperialUnits;
private final Canvas mMapScaleCanvas; private final Canvas mMapScaleCanvas;
private boolean mRedrawNeeded; private boolean mRedrawNeeded;
private double mPrevLatitude = -1; private double mPrevLatitude = -1;
private final double mPrevScale = -1; private final double mPrevScale = -1;
private final HashMap<TextField, String> mTextFields; private final HashMap<TextField, String> mTextFields;
private final Bitmap mBitmap; private final Bitmap mBitmap;
// passed to BitmapRenderer - need to sync on this object. // passed to BitmapRenderer - need to sync on this object.
private final AndroidBitmap mLayerBitmap; private final AndroidBitmap mLayerBitmap;
private final BitmapRenderer mBitmapLayer; private final BitmapRenderer mBitmapLayer;
public MapScaleBar(MapView map) { public MapScaleBar(MapView map) {
super(map.map()); super(map.map());
mBitmap = Bitmap.createBitmap(BITMAP_WIDTH, mBitmap = Bitmap.createBitmap(BITMAP_WIDTH,
BITMAP_HEIGHT, BITMAP_HEIGHT,
Bitmap.Config.ARGB_8888); Bitmap.Config.ARGB_8888);
mMapScaleCanvas = new Canvas(mBitmap); mMapScaleCanvas = new Canvas(mBitmap);
mTextFields = new HashMap<TextField, String>(); mTextFields = new HashMap<TextField, String>();
setDefaultTexts(); setDefaultTexts();
configurePaints(); configurePaints();
mRedrawNeeded = true; mRedrawNeeded = true;
mRenderer = mBitmapLayer = new BitmapRenderer(); mRenderer = mBitmapLayer = new BitmapRenderer();
mLayerBitmap = new AndroidBitmap(mBitmap); mLayerBitmap = new AndroidBitmap(mBitmap);
mBitmapLayer.setBitmap(mLayerBitmap, mBitmapLayer.setBitmap(mLayerBitmap,
BITMAP_WIDTH, BITMAP_WIDTH,
BITMAP_HEIGHT, BITMAP_HEIGHT,
(int) (BITMAP_WIDTH * 1.2f), (int) (BITMAP_WIDTH * 1.2f),
(int) (BITMAP_HEIGHT * 1.2f)); (int) (BITMAP_HEIGHT * 1.2f));
} }
@Override @Override
public void onMapEvent(Event e, MapPosition mapPosition) { public void onMapEvent(Event e, MapPosition mapPosition) {
if (e == Map.UPDATE_EVENT) if (e == Map.UPDATE_EVENT)
return; return;
double latitude = MercatorProjection.toLatitude(mapPosition.y); double latitude = MercatorProjection.toLatitude(mapPosition.y);
if (!mRedrawNeeded) { if (!mRedrawNeeded) {
double scaleDiff = mPrevScale / mapPosition.scale; double scaleDiff = mPrevScale / mapPosition.scale;
if (scaleDiff < 1.1 && scaleDiff > 0.9) { if (scaleDiff < 1.1 && scaleDiff > 0.9) {
double latitudeDiff = Math.abs(mPrevLatitude - latitude); double latitudeDiff = Math.abs(mPrevLatitude - latitude);
if (latitudeDiff < LATITUDE_REDRAW_THRESHOLD) if (latitudeDiff < LATITUDE_REDRAW_THRESHOLD)
return; return;
} }
} }
mPrevLatitude = latitude; mPrevLatitude = latitude;
double groundResolution = MercatorProjection double groundResolution = MercatorProjection
.groundResolution(latitude, mapPosition.scale); .groundResolution(latitude, mapPosition.scale);
int[] scaleBarValues; int[] scaleBarValues;
if (mImperialUnits) { if (mImperialUnits) {
groundResolution = groundResolution / METER_FOOT_RATIO; groundResolution = groundResolution / METER_FOOT_RATIO;
scaleBarValues = SCALE_BAR_VALUES_IMPERIAL; scaleBarValues = SCALE_BAR_VALUES_IMPERIAL;
} else { } else {
scaleBarValues = SCALE_BAR_VALUES_METRIC; scaleBarValues = SCALE_BAR_VALUES_METRIC;
} }
float scaleBarLength = 0; float scaleBarLength = 0;
int mapScaleValue = 0; int mapScaleValue = 0;
for (int i = 0; i < scaleBarValues.length; ++i) { for (int i = 0; i < scaleBarValues.length; ++i) {
mapScaleValue = scaleBarValues[i]; mapScaleValue = scaleBarValues[i];
scaleBarLength = mapScaleValue / (float) groundResolution; scaleBarLength = mapScaleValue / (float) groundResolution;
if (scaleBarLength < (BITMAP_WIDTH - 10)) { if (scaleBarLength < (BITMAP_WIDTH - 10)) {
break; break;
} }
} }
synchronized (mLayerBitmap) { synchronized (mLayerBitmap) {
redrawMapScaleBitmap(scaleBarLength, mapScaleValue); redrawMapScaleBitmap(scaleBarLength, mapScaleValue);
} }
mBitmapLayer.updateBitmap(); mBitmapLayer.updateBitmap();
mRedrawNeeded = false; mRedrawNeeded = false;
} }
/** /**
* @return true if imperial units are used, false otherwise. * @return true if imperial units are used, false otherwise.
*/ */
public boolean isImperialUnits() { public boolean isImperialUnits() {
return mImperialUnits; return mImperialUnits;
} }
/** /**
* @param imperialUnits * @param imperialUnits true if imperial units should be used rather than metric
* true if imperial units should be used rather than metric * units.
* units. */
*/ public void setImperialUnits(boolean imperialUnits) {
public void setImperialUnits(boolean imperialUnits) { mImperialUnits = imperialUnits;
mImperialUnits = imperialUnits; mRedrawNeeded = true;
mRedrawNeeded = true; }
}
/** /**
* Overrides the specified text field with the given string. * Overrides the specified text field with the given string.
* *
* @param textField * @param textField the text field to override.
* the text field to override. * @param value the new value of the text field.
* @param value */
* the new value of the text field. public void setText(TextField textField, String value) {
*/ mTextFields.put(textField, value);
public void setText(TextField textField, String value) { mRedrawNeeded = true;
mTextFields.put(textField, value); }
mRedrawNeeded = true;
}
private void drawScaleBar(float scaleBarLength, Paint paint) { private void drawScaleBar(float scaleBarLength, Paint paint) {
mMapScaleCanvas.drawLine(7, 25, scaleBarLength + 3, 25, paint); mMapScaleCanvas.drawLine(7, 25, scaleBarLength + 3, 25, paint);
mMapScaleCanvas.drawLine(5, 10, 5, 40, paint); mMapScaleCanvas.drawLine(5, 10, 5, 40, paint);
mMapScaleCanvas.drawLine(scaleBarLength + 5, 10, scaleBarLength + 5, 40, paint); mMapScaleCanvas.drawLine(scaleBarLength + 5, 10, scaleBarLength + 5, 40, paint);
} }
private void drawScaleText(int scaleValue, String unitSymbol, Paint paint) { private void drawScaleText(int scaleValue, String unitSymbol, Paint paint) {
mMapScaleCanvas.drawText(scaleValue + unitSymbol, 12, 18, paint); mMapScaleCanvas.drawText(scaleValue + unitSymbol, 12, 18, paint);
} }
/** /**
* Redraws the map scale bitmap with the given parameters. * Redraws the map scale bitmap with the given parameters.
* *
* @param scaleBarLength * @param scaleBarLength the length of the map scale bar in pixels.
* the length of the map scale bar in pixels. * @param mapScaleValue the map scale value in meters.
* @param mapScaleValue */
* the map scale value in meters. private void redrawMapScaleBitmap(float scaleBarLength, int mapScaleValue) {
*/ mBitmap.eraseColor(Color.TRANSPARENT);
private void redrawMapScaleBitmap(float scaleBarLength, int mapScaleValue) {
mBitmap.eraseColor(Color.TRANSPARENT);
// draw the scale bar // draw the scale bar
drawScaleBar(scaleBarLength, SCALE_BAR_STROKE); drawScaleBar(scaleBarLength, SCALE_BAR_STROKE);
drawScaleBar(scaleBarLength, SCALE_BAR); drawScaleBar(scaleBarLength, SCALE_BAR);
int scaleValue; int scaleValue;
String unitSymbol; String unitSymbol;
if (mImperialUnits) { if (mImperialUnits) {
if (mapScaleValue < ONE_MILE) { if (mapScaleValue < ONE_MILE) {
scaleValue = mapScaleValue; scaleValue = mapScaleValue;
unitSymbol = mTextFields.get(TextField.FOOT); unitSymbol = mTextFields.get(TextField.FOOT);
} else { } else {
scaleValue = mapScaleValue / ONE_MILE; scaleValue = mapScaleValue / ONE_MILE;
unitSymbol = mTextFields.get(TextField.MILE); unitSymbol = mTextFields.get(TextField.MILE);
} }
} else { } else {
if (mapScaleValue < ONE_KILOMETER) { if (mapScaleValue < ONE_KILOMETER) {
scaleValue = mapScaleValue; scaleValue = mapScaleValue;
unitSymbol = mTextFields.get(TextField.METER); unitSymbol = mTextFields.get(TextField.METER);
} else { } else {
scaleValue = mapScaleValue / ONE_KILOMETER; scaleValue = mapScaleValue / ONE_KILOMETER;
unitSymbol = mTextFields.get(TextField.KILOMETER); unitSymbol = mTextFields.get(TextField.KILOMETER);
} }
} }
// draw the scale text // draw the scale text
drawScaleText(scaleValue, unitSymbol, SCALE_TEXT_STROKE); drawScaleText(scaleValue, unitSymbol, SCALE_TEXT_STROKE);
drawScaleText(scaleValue, unitSymbol, SCALE_TEXT); drawScaleText(scaleValue, unitSymbol, SCALE_TEXT);
} }
private void setDefaultTexts() { private void setDefaultTexts() {
mTextFields.put(TextField.FOOT, " ft"); mTextFields.put(TextField.FOOT, " ft");
mTextFields.put(TextField.MILE, " mi"); mTextFields.put(TextField.MILE, " mi");
mTextFields.put(TextField.METER, " m"); mTextFields.put(TextField.METER, " m");
mTextFields.put(TextField.KILOMETER, " km"); mTextFields.put(TextField.KILOMETER, " km");
} }
private static void configurePaints() { private static void configurePaints() {
SCALE_BAR.setStrokeWidth(2); SCALE_BAR.setStrokeWidth(2);
SCALE_BAR.setStrokeCap(Paint.Cap.SQUARE); SCALE_BAR.setStrokeCap(Paint.Cap.SQUARE);
SCALE_BAR.setColor(Color.BLACK); SCALE_BAR.setColor(Color.BLACK);
SCALE_BAR_STROKE.setStrokeWidth(5); SCALE_BAR_STROKE.setStrokeWidth(5);
SCALE_BAR_STROKE.setStrokeCap(Paint.Cap.SQUARE); SCALE_BAR_STROKE.setStrokeCap(Paint.Cap.SQUARE);
SCALE_BAR_STROKE.setColor(Color.WHITE); SCALE_BAR_STROKE.setColor(Color.WHITE);
SCALE_TEXT.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); SCALE_TEXT.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
SCALE_TEXT.setTextSize(17); SCALE_TEXT.setTextSize(17);
SCALE_TEXT.setColor(Color.BLACK); SCALE_TEXT.setColor(Color.BLACK);
SCALE_TEXT_STROKE.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); SCALE_TEXT_STROKE.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
SCALE_TEXT_STROKE.setStyle(Paint.Style.STROKE); SCALE_TEXT_STROKE.setStyle(Paint.Style.STROKE);
SCALE_TEXT_STROKE.setColor(Color.WHITE); SCALE_TEXT_STROKE.setColor(Color.WHITE);
SCALE_TEXT_STROKE.setStrokeWidth(2); SCALE_TEXT_STROKE.setStrokeWidth(2);
SCALE_TEXT_STROKE.setTextSize(17); SCALE_TEXT_STROKE.setTextSize(17);
} }
/** /**
* Enumeration of all text fields. * Enumeration of all text fields.
*/ */
public enum TextField { public enum TextField {
/** /**
* Unit symbol for one foot. * Unit symbol for one foot.
*/ */
FOOT, FOOT,
/** /**
* Unit symbol for one kilometer. * Unit symbol for one kilometer.
*/ */
KILOMETER, KILOMETER,
/** /**
* Unit symbol for one meter. * Unit symbol for one meter.
*/ */
METER, METER,
/** /**
* Unit symbol for one mile. * Unit symbol for one mile.
*/ */
MILE; MILE;
} }
} }

View File

@@ -16,8 +16,12 @@
*/ */
package org.oscim.android; package org.oscim.android;
import javax.microedition.khronos.egl.EGLConfig; import android.annotation.SuppressLint;
import javax.microedition.khronos.opengles.GL10; import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import org.oscim.android.canvas.AndroidGraphics; import org.oscim.android.canvas.AndroidGraphics;
import org.oscim.android.gl.AndroidGL; import org.oscim.android.gl.AndroidGL;
@@ -30,224 +34,220 @@ import org.oscim.map.Map;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import android.annotation.SuppressLint; import javax.microedition.khronos.egl.EGLConfig;
import android.content.Context; import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
/** /**
* The MapView, * The MapView,
* * <p/>
* add it your App, have a map! * add it your App, have a map!
* * <p/>
* Dont forget to call onPause / onResume! * Dont forget to call onPause / onResume!
*/ */
public class MapView extends GLSurfaceView { public class MapView extends GLSurfaceView {
static final Logger log = LoggerFactory.getLogger(MapView.class); static final Logger log = LoggerFactory.getLogger(MapView.class);
static { static {
System.loadLibrary("vtm-jni"); System.loadLibrary("vtm-jni");
} }
protected final AndroidMap mMap; protected final AndroidMap mMap;
protected final GestureDetector mGestureDetector; protected final GestureDetector mGestureDetector;
protected final AndroidMotionEvent mMotionEvent; protected final AndroidMotionEvent mMotionEvent;
public MapView(Context context) { public MapView(Context context) {
this(context, null); this(context, null);
} }
public MapView(Context context, AttributeSet attributeSet) { public MapView(Context context, AttributeSet attributeSet) {
super(context, attributeSet); super(context, attributeSet);
/* Not sure if this makes sense */ /* Not sure if this makes sense */
this.setWillNotDraw(true); this.setWillNotDraw(true);
this.setClickable(true); this.setClickable(true);
this.setFocusable(true); this.setFocusable(true);
this.setFocusableInTouchMode(true); this.setFocusableInTouchMode(true);
/* Setup android backedn */ /* Setup android backedn */
AndroidGraphics.init(); AndroidGraphics.init();
AndroidAssets.init(context); AndroidAssets.init(context);
GLAdapter.init(new AndroidGL()); GLAdapter.init(new AndroidGL());
DisplayMetrics metrics = getResources().getDisplayMetrics(); DisplayMetrics metrics = getResources().getDisplayMetrics();
CanvasAdapter.dpi = (int) Math.max(metrics.xdpi, metrics.ydpi); CanvasAdapter.dpi = (int) Math.max(metrics.xdpi, metrics.ydpi);
/* Initialize the Map */ /* Initialize the Map */
mMap = new AndroidMap(this); mMap = new AndroidMap(this);
/* Initialize Renderer */ /* Initialize Renderer */
setEGLConfigChooser(new GlConfigChooser()); setEGLConfigChooser(new GlConfigChooser());
setEGLContextClientVersion(2); setEGLContextClientVersion(2);
if (GLAdapter.debug) if (GLAdapter.debug)
setDebugFlags(GLSurfaceView.DEBUG_CHECK_GL_ERROR setDebugFlags(GLSurfaceView.DEBUG_CHECK_GL_ERROR
| GLSurfaceView.DEBUG_LOG_GL_CALLS); | GLSurfaceView.DEBUG_LOG_GL_CALLS);
setRenderer(new GLRenderer(mMap)); setRenderer(new GLRenderer(mMap));
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
mMap.clearMap(); mMap.clearMap();
mMap.updateMap(false); mMap.updateMap(false);
GestureHandler gestureHandler = new GestureHandler(mMap); GestureHandler gestureHandler = new GestureHandler(mMap);
mGestureDetector = new GestureDetector(context, gestureHandler); mGestureDetector = new GestureDetector(context, gestureHandler);
mGestureDetector.setOnDoubleTapListener(gestureHandler); mGestureDetector.setOnDoubleTapListener(gestureHandler);
mMotionEvent = new AndroidMotionEvent(); mMotionEvent = new AndroidMotionEvent();
} }
public void onStop() { public void onStop() {
} }
public void onPause() { public void onPause() {
mMap.pause(true); mMap.pause(true);
} }
public void onResume() { public void onResume() {
mMap.pause(false); mMap.pause(false);
} }
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@Override @Override
public boolean onTouchEvent(android.view.MotionEvent motionEvent) { public boolean onTouchEvent(android.view.MotionEvent motionEvent) {
if (!isClickable()) if (!isClickable())
return false; return false;
if (mGestureDetector.onTouchEvent(motionEvent)) if (mGestureDetector.onTouchEvent(motionEvent))
return true; return true;
mMap.input.fire(null, mMotionEvent.wrap(motionEvent)); mMap.input.fire(null, mMotionEvent.wrap(motionEvent));
return true; return true;
} }
@Override @Override
protected void onSizeChanged(int width, int height, protected void onSizeChanged(int width, int height,
int oldWidth, int oldHeight) { int oldWidth, int oldHeight) {
super.onSizeChanged(width, height, oldWidth, oldHeight); super.onSizeChanged(width, height, oldWidth, oldHeight);
if (width > 0 && height > 0) if (width > 0 && height > 0)
mMap.viewport().setScreenSize(width, height); mMap.viewport().setScreenSize(width, height);
} }
public Map map() { public Map map() {
return mMap; return mMap;
} }
static class AndroidMap extends Map { static class AndroidMap extends Map {
private final MapView mMapView; private final MapView mMapView;
private boolean mRenderRequest; private boolean mRenderRequest;
private boolean mRenderWait; private boolean mRenderWait;
private boolean mPausing; private boolean mPausing;
public AndroidMap(MapView mapView) { public AndroidMap(MapView mapView) {
super(); super();
mMapView = mapView; mMapView = mapView;
} }
@Override @Override
public int getWidth() { public int getWidth() {
return mMapView.getWidth(); return mMapView.getWidth();
} }
@Override @Override
public int getHeight() { public int getHeight() {
return mMapView.getHeight(); return mMapView.getHeight();
} }
private final Runnable mRedrawCb = new Runnable() { private final Runnable mRedrawCb = new Runnable() {
@Override @Override
public void run() { public void run() {
prepareFrame(); prepareFrame();
mMapView.requestRender(); mMapView.requestRender();
} }
}; };
@Override @Override
public void updateMap(boolean redraw) { public void updateMap(boolean redraw) {
synchronized (mRedrawCb) { synchronized (mRedrawCb) {
if (mPausing) if (mPausing)
return; return;
if (!mRenderRequest) { if (!mRenderRequest) {
mRenderRequest = true; mRenderRequest = true;
mMapView.post(mRedrawCb); mMapView.post(mRedrawCb);
} else { } else {
mRenderWait = true; mRenderWait = true;
} }
} }
} }
@Override @Override
public void render() { public void render() {
if (mPausing) if (mPausing)
return; return;
/** TODO should not need to call prepareFrame in mRedrawCb */ /** TODO should not need to call prepareFrame in mRedrawCb */
updateMap(false); updateMap(false);
} }
@Override @Override
public void beginFrame() { public void beginFrame() {
} }
@Override @Override
public void doneFrame(boolean animate) { public void doneFrame(boolean animate) {
synchronized (mRedrawCb) { synchronized (mRedrawCb) {
mRenderRequest = false; mRenderRequest = false;
if (animate || mRenderWait) { if (animate || mRenderWait) {
mRenderWait = false; mRenderWait = false;
render(); render();
} }
} }
} }
@Override @Override
public boolean post(Runnable runnable) { public boolean post(Runnable runnable) {
return mMapView.post(runnable); return mMapView.post(runnable);
} }
@Override @Override
public boolean postDelayed(Runnable action, long delay) { public boolean postDelayed(Runnable action, long delay) {
return mMapView.postDelayed(action, delay); return mMapView.postDelayed(action, delay);
} }
public void pause(boolean pause) { public void pause(boolean pause) {
log.debug("pause... {}", pause); log.debug("pause... {}", pause);
mPausing = pause; mPausing = pause;
} }
} }
static class GLRenderer extends org.oscim.renderer.MapRenderer static class GLRenderer extends org.oscim.renderer.MapRenderer
implements GLSurfaceView.Renderer { implements GLSurfaceView.Renderer {
public GLRenderer(Map map) { public GLRenderer(Map map) {
super(map); super(map);
} }
@Override @Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) { public void onSurfaceCreated(GL10 gl, EGLConfig config) {
super.onSurfaceCreated(); super.onSurfaceCreated();
} }
@Override @Override
public void onSurfaceChanged(GL10 gl, int width, int height) { public void onSurfaceChanged(GL10 gl, int width, int height) {
super.onSurfaceChanged(width, height); super.onSurfaceChanged(width, height);
} }
@Override @Override
public void onDrawFrame(GL10 gl) { public void onDrawFrame(GL10 gl) {
super.onDrawFrame(); super.onDrawFrame();
} }
} }
} }

View File

@@ -16,17 +16,6 @@
*/ */
package org.oscim.android.cache; package org.oscim.android.cache;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import org.oscim.core.Tile;
import org.oscim.tiling.ITileCache;
import org.slf4j.LoggerFactory;
import android.annotation.TargetApi; import android.annotation.TargetApi;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
@@ -37,247 +26,258 @@ import android.database.sqlite.SQLiteStatement;
import android.os.Build; import android.os.Build;
import android.os.ParcelFileDescriptor; import android.os.ParcelFileDescriptor;
import org.oscim.core.Tile;
import org.oscim.tiling.ITileCache;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
public class TileCache implements ITileCache { public class TileCache implements ITileCache {
final static org.slf4j.Logger log = LoggerFactory.getLogger(TileCache.class); final static org.slf4j.Logger log = LoggerFactory.getLogger(TileCache.class);
final static boolean dbg = false; final static boolean dbg = false;
class CacheTileReader implements TileReader { class CacheTileReader implements TileReader {
final InputStream mInputStream; final InputStream mInputStream;
final Tile mTile; final Tile mTile;
public CacheTileReader(Tile tile, InputStream is) { public CacheTileReader(Tile tile, InputStream is) {
mTile = tile; mTile = tile;
mInputStream = is; mInputStream = is;
} }
@Override @Override
public Tile getTile() { public Tile getTile() {
return mTile; return mTile;
} }
@Override @Override
public InputStream getInputStream() { public InputStream getInputStream() {
return mInputStream; return mInputStream;
} }
} }
class CacheTileWriter implements TileWriter { class CacheTileWriter implements TileWriter {
final ByteArrayOutputStream mOutputStream; final ByteArrayOutputStream mOutputStream;
final Tile mTile; final Tile mTile;
CacheTileWriter(Tile tile, ByteArrayOutputStream os) { CacheTileWriter(Tile tile, ByteArrayOutputStream os) {
mTile = tile; mTile = tile;
mOutputStream = os; mOutputStream = os;
} }
@Override @Override
public Tile getTile() { public Tile getTile() {
return mTile; return mTile;
} }
@Override @Override
public OutputStream getOutputStream() { public OutputStream getOutputStream() {
return mOutputStream; return mOutputStream;
} }
@Override @Override
public void complete(boolean success) { public void complete(boolean success) {
saveTile(mTile, mOutputStream, success); saveTile(mTile, mOutputStream, success);
} }
} }
private final ArrayList<ByteArrayOutputStream> mCacheBuffers; private final ArrayList<ByteArrayOutputStream> mCacheBuffers;
private final SQLiteHelper dbHelper; private final SQLiteHelper dbHelper;
private final SQLiteDatabase mDatabase; private final SQLiteDatabase mDatabase;
private final SQLiteStatement mStmtGetTile; private final SQLiteStatement mStmtGetTile;
private final SQLiteStatement mStmtPutTile; private final SQLiteStatement mStmtPutTile;
//private final SQLiteStatement mStmtUpdateTile; //private final SQLiteStatement mStmtUpdateTile;
public void dispose() { public void dispose() {
if (mDatabase.isOpen()) if (mDatabase.isOpen())
mDatabase.close(); mDatabase.close();
} }
@TargetApi(Build.VERSION_CODES.JELLY_BEAN) @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public TileCache(Context context, String cacheDirectory, String dbName) { public TileCache(Context context, String cacheDirectory, String dbName) {
if (dbg) if (dbg)
log.debug("open cache {}, {}", cacheDirectory, dbName); log.debug("open cache {}, {}", cacheDirectory, dbName);
dbHelper = new SQLiteHelper(context, dbName); dbHelper = new SQLiteHelper(context, dbName);
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
dbHelper.setWriteAheadLoggingEnabled(true); dbHelper.setWriteAheadLoggingEnabled(true);
mDatabase = dbHelper.getWritableDatabase(); mDatabase = dbHelper.getWritableDatabase();
mStmtGetTile = mDatabase.compileStatement("" + mStmtGetTile = mDatabase.compileStatement("" +
"SELECT " + COLUMN_DATA + "SELECT " + COLUMN_DATA +
" FROM " + TABLE_NAME + " FROM " + TABLE_NAME +
" WHERE x=? AND y=? AND z = ?"); " WHERE x=? AND y=? AND z = ?");
mStmtPutTile = mDatabase.compileStatement("" + mStmtPutTile = mDatabase.compileStatement("" +
"INSERT INTO " + TABLE_NAME + "INSERT INTO " + TABLE_NAME +
" (x, y, z, time, last_access, data)" + " (x, y, z, time, last_access, data)" +
" VALUES(?,?,?,?,?,?)"); " VALUES(?,?,?,?,?,?)");
//mStmtUpdateTile = mDatabase.compileStatement("" + //mStmtUpdateTile = mDatabase.compileStatement("" +
// "UPDATE " + TABLE_NAME + // "UPDATE " + TABLE_NAME +
// " SET last_access=?" + // " SET last_access=?" +
// " WHERE x=? AND y=? AND z=?"); // " WHERE x=? AND y=? AND z=?");
mCacheBuffers = new ArrayList<ByteArrayOutputStream>(); mCacheBuffers = new ArrayList<ByteArrayOutputStream>();
} }
@Override @Override
public TileWriter writeTile(Tile tile) { public TileWriter writeTile(Tile tile) {
ByteArrayOutputStream os; ByteArrayOutputStream os;
synchronized (mCacheBuffers) { synchronized (mCacheBuffers) {
if (mCacheBuffers.size() == 0) if (mCacheBuffers.size() == 0)
os = new ByteArrayOutputStream(32 * 1024); os = new ByteArrayOutputStream(32 * 1024);
else else
os = mCacheBuffers.remove(mCacheBuffers.size() - 1); os = mCacheBuffers.remove(mCacheBuffers.size() - 1);
} }
return new CacheTileWriter(tile, os); return new CacheTileWriter(tile, os);
} }
static final String TABLE_NAME = "tiles"; static final String TABLE_NAME = "tiles";
static final String COLUMN_TIME = "time"; static final String COLUMN_TIME = "time";
static final String COLUMN_ACCESS = "last_access"; static final String COLUMN_ACCESS = "last_access";
static final String COLUMN_DATA = "data"; static final String COLUMN_DATA = "data";
//static final String COLUMN_SIZE = "size"; //static final String COLUMN_SIZE = "size";
class SQLiteHelper extends SQLiteOpenHelper { class SQLiteHelper extends SQLiteOpenHelper {
//private static final String DATABASE_NAME = "tile.db"; //private static final String DATABASE_NAME = "tile.db";
private static final int DATABASE_VERSION = 1; private static final int DATABASE_VERSION = 1;
private static final String TILE_SCHEMA = private static final String TILE_SCHEMA =
"CREATE TABLE " "CREATE TABLE "
+ TABLE_NAME + "(" + TABLE_NAME + "("
+ "x INTEGER NOT NULL," + "x INTEGER NOT NULL,"
+ "y INTEGER NOT NULL," + "y INTEGER NOT NULL,"
+ "z INTEGER NOT NULL," + "z INTEGER NOT NULL,"
+ COLUMN_TIME + " LONG NOT NULL," + COLUMN_TIME + " LONG NOT NULL,"
//+ COLUMN_SIZE + " LONG NOT NULL," //+ COLUMN_SIZE + " LONG NOT NULL,"
+ COLUMN_ACCESS + " LONG NOT NULL," + COLUMN_ACCESS + " LONG NOT NULL,"
+ COLUMN_DATA + " BLOB," + COLUMN_DATA + " BLOB,"
+ "PRIMARY KEY(x,y,z));"; + "PRIMARY KEY(x,y,z));";
public SQLiteHelper(Context context, String dbName) { public SQLiteHelper(Context context, String dbName) {
super(context, dbName, null, DATABASE_VERSION); super(context, dbName, null, DATABASE_VERSION);
} }
@Override @Override
public void onCreate(SQLiteDatabase db) { public void onCreate(SQLiteDatabase db) {
log.debug("create table"); log.debug("create table");
db.execSQL(TILE_SCHEMA); db.execSQL(TILE_SCHEMA);
} }
@Override @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
log.debug("drop table"); log.debug("drop table");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db); onCreate(db);
} }
@Override @Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion); onUpgrade(db, oldVersion, newVersion);
} }
} }
public void saveTile(Tile tile, ByteArrayOutputStream data, boolean success) { public void saveTile(Tile tile, ByteArrayOutputStream data, boolean success) {
byte[] bytes = null; byte[] bytes = null;
if (success) if (success)
bytes = data.toByteArray(); bytes = data.toByteArray();
synchronized (mCacheBuffers) { synchronized (mCacheBuffers) {
data.reset(); data.reset();
mCacheBuffers.add(data); mCacheBuffers.add(data);
} }
if (dbg) if (dbg)
log.debug("store tile {} {}", tile, Boolean.valueOf(success)); log.debug("store tile {} {}", tile, Boolean.valueOf(success));
if (!success) if (!success)
return; return;
synchronized (mStmtPutTile) { synchronized (mStmtPutTile) {
mStmtPutTile.bindLong(1, tile.tileX); mStmtPutTile.bindLong(1, tile.tileX);
mStmtPutTile.bindLong(2, tile.tileY); mStmtPutTile.bindLong(2, tile.tileY);
mStmtPutTile.bindLong(3, tile.zoomLevel); mStmtPutTile.bindLong(3, tile.zoomLevel);
mStmtPutTile.bindLong(4, 0); mStmtPutTile.bindLong(4, 0);
mStmtPutTile.bindLong(5, 0); mStmtPutTile.bindLong(5, 0);
mStmtPutTile.bindBlob(6, bytes); mStmtPutTile.bindBlob(6, bytes);
mStmtPutTile.execute(); mStmtPutTile.execute();
mStmtPutTile.clearBindings(); mStmtPutTile.clearBindings();
} }
} }
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @TargetApi(Build.VERSION_CODES.HONEYCOMB)
public TileReader getTileApi11(Tile tile) { public TileReader getTileApi11(Tile tile) {
InputStream in = null; InputStream in = null;
mStmtGetTile.bindLong(1, tile.tileX); mStmtGetTile.bindLong(1, tile.tileX);
mStmtGetTile.bindLong(2, tile.tileY); mStmtGetTile.bindLong(2, tile.tileY);
mStmtGetTile.bindLong(3, tile.zoomLevel); mStmtGetTile.bindLong(3, tile.zoomLevel);
try { try {
ParcelFileDescriptor result = mStmtGetTile.simpleQueryForBlobFileDescriptor(); ParcelFileDescriptor result = mStmtGetTile.simpleQueryForBlobFileDescriptor();
in = new FileInputStream(result.getFileDescriptor()); in = new FileInputStream(result.getFileDescriptor());
} catch (SQLiteDoneException e) { } catch (SQLiteDoneException e) {
log.debug("not in cache {}", tile); log.debug("not in cache {}", tile);
return null; return null;
} finally { } finally {
mStmtGetTile.clearBindings(); mStmtGetTile.clearBindings();
} }
if (dbg) if (dbg)
log.debug("load tile {}", tile); log.debug("load tile {}", tile);
return new CacheTileReader(tile, in); return new CacheTileReader(tile, in);
} }
private final String[] mQueryVals = new String[3]; private final String[] mQueryVals = new String[3];
@Override @Override
public synchronized TileReader getTile(Tile tile) { public synchronized TileReader getTile(Tile tile) {
//if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) //if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
// return getTileApi11(tile); // return getTileApi11(tile);
mQueryVals[0] = String.valueOf(tile.zoomLevel); mQueryVals[0] = String.valueOf(tile.zoomLevel);
mQueryVals[1] = String.valueOf(tile.tileX); mQueryVals[1] = String.valueOf(tile.tileX);
mQueryVals[2] = String.valueOf(tile.tileY); mQueryVals[2] = String.valueOf(tile.tileY);
Cursor cursor = mDatabase.rawQuery("SELECT " + COLUMN_DATA + Cursor cursor = mDatabase.rawQuery("SELECT " + COLUMN_DATA +
" FROM " + TABLE_NAME + " FROM " + TABLE_NAME +
" WHERE z=? AND x=? AND y=?", mQueryVals); " WHERE z=? AND x=? AND y=?", mQueryVals);
if (!cursor.moveToFirst()) { if (!cursor.moveToFirst()) {
if (dbg) if (dbg)
log.debug("not in cache {}", tile); log.debug("not in cache {}", tile);
cursor.close(); cursor.close();
return null; return null;
} }
InputStream in = new ByteArrayInputStream(cursor.getBlob(0)); InputStream in = new ByteArrayInputStream(cursor.getBlob(0));
cursor.close(); cursor.close();
if (dbg) if (dbg)
log.debug("load tile {}", tile); log.debug("load tile {}", tile);
return new CacheTileReader(tile, in); return new CacheTileReader(tile, in);
} }
@Override @Override
public void setCacheSize(long size) { public void setCacheSize(long size) {
} }
} }

View File

@@ -16,88 +16,88 @@
*/ */
package org.oscim.android.canvas; package org.oscim.android.canvas;
import static android.graphics.Bitmap.Config.ARGB_8888;
import java.io.InputStream;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import android.opengl.GLES20; import android.opengl.GLES20;
import android.opengl.GLUtils; import android.opengl.GLUtils;
import java.io.InputStream;
import static android.graphics.Bitmap.Config.ARGB_8888;
public class AndroidBitmap implements org.oscim.backend.canvas.Bitmap { public class AndroidBitmap implements org.oscim.backend.canvas.Bitmap {
final Bitmap mBitmap; final Bitmap mBitmap;
public AndroidBitmap(InputStream inputStream) { public AndroidBitmap(InputStream inputStream) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream); Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
try { try {
GLUtils.getType(bitmap); GLUtils.getType(bitmap);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
bitmap = bitmap.copy(ARGB_8888, false); bitmap = bitmap.copy(ARGB_8888, false);
} }
mBitmap = bitmap; mBitmap = bitmap;
} }
@Override @Override
public boolean isValid() { public boolean isValid() {
return mBitmap != null; return mBitmap != null;
} }
/** /**
* @param format ignored always ARGB8888 * @param format ignored always ARGB8888
*/ */
public AndroidBitmap(int width, int height, int format) { public AndroidBitmap(int width, int height, int format) {
mBitmap = android.graphics.Bitmap mBitmap = android.graphics.Bitmap
.createBitmap(width, height, ARGB_8888); .createBitmap(width, height, ARGB_8888);
} }
public AndroidBitmap(android.graphics.Bitmap bitmap) { public AndroidBitmap(android.graphics.Bitmap bitmap) {
mBitmap = bitmap; mBitmap = bitmap;
} }
@Override @Override
public int getWidth() { public int getWidth() {
return mBitmap.getWidth(); return mBitmap.getWidth();
} }
@Override @Override
public int getHeight() { public int getHeight() {
return mBitmap.getHeight(); return mBitmap.getHeight();
} }
@Override @Override
public int[] getPixels() { public int[] getPixels() {
int width = getWidth(); int width = getWidth();
int height = getHeight(); int height = getHeight();
int[] colors = new int[width * height]; int[] colors = new int[width * height];
mBitmap.getPixels(colors, 0, width, 0, 0, width, height); mBitmap.getPixels(colors, 0, width, 0, 0, width, height);
return colors; return colors;
} }
@Override @Override
public void eraseColor(int color) { public void eraseColor(int color) {
//int a = android.graphics.Color.TRANSPARENT; //int a = android.graphics.Color.TRANSPARENT;
mBitmap.eraseColor(color); mBitmap.eraseColor(color);
} }
@Override @Override
public void uploadToTexture(boolean replace) { public void uploadToTexture(boolean replace) {
int format = GLUtils.getInternalFormat(mBitmap); int format = GLUtils.getInternalFormat(mBitmap);
int type = GLUtils.getType(mBitmap); int type = GLUtils.getType(mBitmap);
if (replace) if (replace)
GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, 0, 0, GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, 0, 0,
mBitmap, format, type); mBitmap, format, type);
else else
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, format, GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, format,
mBitmap, type, 0); mBitmap, type, 0);
} }
@Override @Override
public void recycle() { public void recycle() {
if (mBitmap == null) if (mBitmap == null)
return; return;
mBitmap.recycle(); mBitmap.recycle();
} }
} }

View File

@@ -21,31 +21,31 @@ import org.oscim.backend.canvas.Canvas;
import org.oscim.backend.canvas.Paint; import org.oscim.backend.canvas.Paint;
public class AndroidCanvas implements Canvas { public class AndroidCanvas implements Canvas {
final android.graphics.Canvas canvas; final android.graphics.Canvas canvas;
public AndroidCanvas() { public AndroidCanvas() {
canvas = new android.graphics.Canvas(); canvas = new android.graphics.Canvas();
} }
@Override @Override
public void setBitmap(Bitmap bitmap) { public void setBitmap(Bitmap bitmap) {
canvas.setBitmap(((AndroidBitmap) bitmap).mBitmap); canvas.setBitmap(((AndroidBitmap) bitmap).mBitmap);
} }
@Override @Override
public void drawText(String string, float x, float y, Paint fill, Paint stroke) { public void drawText(String string, float x, float y, Paint fill, Paint stroke) {
if (string != null) { if (string != null) {
if (stroke != null) if (stroke != null)
canvas.drawText(string, x, y, ((AndroidPaint) stroke).mPaint); canvas.drawText(string, x, y, ((AndroidPaint) stroke).mPaint);
canvas.drawText(string, x, y, ((AndroidPaint) fill).mPaint); canvas.drawText(string, x, y, ((AndroidPaint) fill).mPaint);
} }
} }
@Override @Override
public void drawBitmap(Bitmap bitmap, float x, float y) { public void drawBitmap(Bitmap bitmap, float x, float y) {
canvas.drawBitmap(((AndroidBitmap) bitmap).mBitmap, x, y, null); canvas.drawBitmap(((AndroidBitmap) bitmap).mBitmap, x, y, null);
} }
} }

View File

@@ -17,8 +17,10 @@
*/ */
package org.oscim.android.canvas; package org.oscim.android.canvas;
import java.io.IOException; import android.content.res.Resources;
import java.io.InputStream; import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import org.oscim.backend.CanvasAdapter; import org.oscim.backend.CanvasAdapter;
import org.oscim.backend.canvas.Bitmap; import org.oscim.backend.canvas.Bitmap;
@@ -27,99 +29,97 @@ import org.oscim.backend.canvas.Paint;
import org.oscim.layers.marker.MarkerItem.HotspotPlace; import org.oscim.layers.marker.MarkerItem.HotspotPlace;
import org.oscim.layers.marker.MarkerSymbol; import org.oscim.layers.marker.MarkerSymbol;
import android.content.res.Resources; import java.io.IOException;
import android.graphics.Bitmap.Config; import java.io.InputStream;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
public final class AndroidGraphics extends CanvasAdapter { public final class AndroidGraphics extends CanvasAdapter {
public static void init() { public static void init() {
CanvasAdapter.init(new AndroidGraphics()); CanvasAdapter.init(new AndroidGraphics());
} }
public static android.graphics.Paint getAndroidPaint(Paint paint) { public static android.graphics.Paint getAndroidPaint(Paint paint) {
return ((AndroidPaint) paint).mPaint; return ((AndroidPaint) paint).mPaint;
} }
public static android.graphics.Bitmap getBitmap(Bitmap bitmap) { public static android.graphics.Bitmap getBitmap(Bitmap bitmap) {
return ((AndroidBitmap) bitmap).mBitmap; return ((AndroidBitmap) bitmap).mBitmap;
} }
private AndroidGraphics() { private AndroidGraphics() {
// do nothing // do nothing
} }
@Override @Override
public Bitmap decodeBitmapImpl(InputStream inputStream) { public Bitmap decodeBitmapImpl(InputStream inputStream) {
return new AndroidBitmap(inputStream); return new AndroidBitmap(inputStream);
} }
@Override @Override
public Bitmap loadBitmapAssetImpl(String fileName) { public Bitmap loadBitmapAssetImpl(String fileName) {
try { try {
return createBitmap(fileName); return createBitmap(fileName);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
@Override @Override
public Paint newPaintImpl() { public Paint newPaintImpl() {
return new AndroidPaint(); return new AndroidPaint();
} }
@Override @Override
public Bitmap newBitmapImpl(int width, int height, int format) { public Bitmap newBitmapImpl(int width, int height, int format) {
return new AndroidBitmap(width, height, format); return new AndroidBitmap(width, height, format);
} }
@Override @Override
public Canvas newCanvasImpl() { public Canvas newCanvasImpl() {
return new AndroidCanvas(); return new AndroidCanvas();
} }
//------------------------------------- //-------------------------------------
public static Bitmap drawableToBitmap(Drawable drawable) { public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) { if (drawable instanceof BitmapDrawable) {
return new AndroidBitmap(((BitmapDrawable) drawable).getBitmap()); return new AndroidBitmap(((BitmapDrawable) drawable).getBitmap());
} }
android.graphics.Bitmap bitmap = android.graphics.Bitmap android.graphics.Bitmap bitmap = android.graphics.Bitmap
.createBitmap(drawable.getIntrinsicWidth(), .createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), drawable.getIntrinsicHeight(),
Config.ARGB_8888); Config.ARGB_8888);
android.graphics.Canvas canvas = new android.graphics.Canvas(bitmap); android.graphics.Canvas canvas = new android.graphics.Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas); drawable.draw(canvas);
return new AndroidBitmap(bitmap); return new AndroidBitmap(bitmap);
} }
public static Bitmap drawableToBitmap(Resources res, int resId) { public static Bitmap drawableToBitmap(Resources res, int resId) {
return new AndroidBitmap(res.openRawResource(resId)); return new AndroidBitmap(res.openRawResource(resId));
} }
/** /**
* @deprecated * @deprecated
*/ */
public static MarkerSymbol makeMarker(Drawable drawable, HotspotPlace place) { public static MarkerSymbol makeMarker(Drawable drawable, HotspotPlace place) {
if (place == null) if (place == null)
place = HotspotPlace.CENTER; place = HotspotPlace.CENTER;
return new MarkerSymbol(drawableToBitmap(drawable), place); return new MarkerSymbol(drawableToBitmap(drawable), place);
} }
/** /**
* @deprecated * @deprecated
*/ */
public static MarkerSymbol makeMarker(Resources res, int resId, HotspotPlace place) { public static MarkerSymbol makeMarker(Resources res, int resId, HotspotPlace place) {
if (place == null) if (place == null)
place = HotspotPlace.CENTER; place = HotspotPlace.CENTER;
InputStream in = res.openRawResource(resId); InputStream in = res.openRawResource(resId);
return new MarkerSymbol(new AndroidBitmap(in), place); return new MarkerSymbol(new AndroidBitmap(in), place);
} }
} }

View File

@@ -16,110 +16,110 @@
*/ */
package org.oscim.android.canvas; package org.oscim.android.canvas;
import org.oscim.backend.canvas.Paint;
import android.graphics.Paint.FontMetrics; import android.graphics.Paint.FontMetrics;
import android.graphics.Typeface; import android.graphics.Typeface;
import org.oscim.backend.canvas.Paint;
class AndroidPaint implements Paint { class AndroidPaint implements Paint {
private static int getStyle(org.oscim.backend.canvas.Paint.FontStyle fontStyle) { private static int getStyle(org.oscim.backend.canvas.Paint.FontStyle fontStyle) {
switch (fontStyle) { switch (fontStyle) {
case BOLD: case BOLD:
return 1; return 1;
case BOLD_ITALIC: case BOLD_ITALIC:
return 3; return 3;
case ITALIC: case ITALIC:
return 2; return 2;
case NORMAL: case NORMAL:
return 0; return 0;
} }
throw new IllegalArgumentException("unknown font style: " + fontStyle); throw new IllegalArgumentException("unknown font style: " + fontStyle);
} }
private static Typeface getTypeface(org.oscim.backend.canvas.Paint.FontFamily fontFamily) { private static Typeface getTypeface(org.oscim.backend.canvas.Paint.FontFamily fontFamily) {
switch (fontFamily) { switch (fontFamily) {
case DEFAULT: case DEFAULT:
return Typeface.DEFAULT; return Typeface.DEFAULT;
case DEFAULT_BOLD: case DEFAULT_BOLD:
return Typeface.DEFAULT_BOLD; return Typeface.DEFAULT_BOLD;
case MONOSPACE: case MONOSPACE:
return Typeface.MONOSPACE; return Typeface.MONOSPACE;
case SANS_SERIF: case SANS_SERIF:
return Typeface.SANS_SERIF; return Typeface.SANS_SERIF;
case SERIF: case SERIF:
return Typeface.SERIF; return Typeface.SERIF;
} }
throw new IllegalArgumentException("unknown font family: " + fontFamily); throw new IllegalArgumentException("unknown font family: " + fontFamily);
} }
final android.graphics.Paint mPaint; final android.graphics.Paint mPaint;
AndroidPaint() { AndroidPaint() {
mPaint = new android.graphics.Paint( mPaint = new android.graphics.Paint(
android.graphics.Paint.ANTI_ALIAS_FLAG); android.graphics.Paint.ANTI_ALIAS_FLAG);
} }
@Override @Override
public int getColor() { public int getColor() {
return mPaint.getColor(); return mPaint.getColor();
} }
@Override @Override
public void setColor(int color) { public void setColor(int color) {
mPaint.setColor(color); mPaint.setColor(color);
} }
@Override @Override
public void setStrokeCap(Cap cap) { public void setStrokeCap(Cap cap) {
android.graphics.Paint.Cap androidCap = android.graphics.Paint.Cap android.graphics.Paint.Cap androidCap = android.graphics.Paint.Cap
.valueOf(cap.name()); .valueOf(cap.name());
mPaint.setStrokeCap(androidCap); mPaint.setStrokeCap(androidCap);
} }
@Override @Override
public void setStrokeWidth(float width) { public void setStrokeWidth(float width) {
mPaint.setStrokeWidth(width); mPaint.setStrokeWidth(width);
} }
@Override @Override
public void setStyle(Style style) { public void setStyle(Style style) {
mPaint.setStyle(android.graphics.Paint.Style.valueOf(style.name())); mPaint.setStyle(android.graphics.Paint.Style.valueOf(style.name()));
} }
@Override @Override
public void setTextAlign(Align align) { public void setTextAlign(Align align) {
//mPaint.setTextAlign(android.graphics.Paint.Align.valueOf(align.name())); //mPaint.setTextAlign(android.graphics.Paint.Align.valueOf(align.name()));
} }
@Override @Override
public void setTextSize(float textSize) { public void setTextSize(float textSize) {
mPaint.setTextSize(textSize); mPaint.setTextSize(textSize);
} }
@Override @Override
public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) { public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) {
Typeface typeface = Typeface.create(getTypeface(fontFamily), Typeface typeface = Typeface.create(getTypeface(fontFamily),
getStyle(fontStyle)); getStyle(fontStyle));
mPaint.setTypeface(typeface); mPaint.setTypeface(typeface);
} }
@Override @Override
public float measureText(String text) { public float measureText(String text) {
return mPaint.measureText(text); return mPaint.measureText(text);
} }
@Override @Override
public float getFontHeight() { public float getFontHeight() {
FontMetrics fm = mPaint.getFontMetrics(); FontMetrics fm = mPaint.getFontMetrics();
return (float) Math.ceil(Math.abs(fm.bottom) + Math.abs(fm.top)); return (float) Math.ceil(Math.abs(fm.bottom) + Math.abs(fm.top));
} }
@Override @Override
public float getFontDescent() { public float getFontDescent() {
FontMetrics fm = mPaint.getFontMetrics(); FontMetrics fm = mPaint.getFontMetrics();
// //fontDescent = (float) Math.ceil(Math.abs(fm.descent)); // //fontDescent = (float) Math.ceil(Math.abs(fm.descent));
return Math.abs(fm.bottom); return Math.abs(fm.bottom);
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,72 +1,72 @@
package org.oscim.android.gl; package org.oscim.android.gl;
import android.opengl.GLSurfaceView;
import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLDisplay;
import android.opengl.GLSurfaceView;
public class GlConfigChooser implements GLSurfaceView.EGLConfigChooser { public class GlConfigChooser implements GLSurfaceView.EGLConfigChooser {
@Override @Override
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) { public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
int[] val = new int[1]; int[] val = new int[1];
// Try to find a normal multisample configuration first. // Try to find a normal multisample configuration first.
int[] configSpec = { int[] configSpec = {
EGL10.EGL_RED_SIZE, 5, EGL10.EGL_RED_SIZE, 5,
EGL10.EGL_GREEN_SIZE, 6, EGL10.EGL_GREEN_SIZE, 6,
EGL10.EGL_BLUE_SIZE, 5, EGL10.EGL_BLUE_SIZE, 5,
EGL10.EGL_ALPHA_SIZE, 8, EGL10.EGL_ALPHA_SIZE, 8,
EGL10.EGL_DEPTH_SIZE, 16, EGL10.EGL_DEPTH_SIZE, 16,
// Requires that setEGLContextClientVersion(2) is called on the view. // Requires that setEGLContextClientVersion(2) is called on the view.
EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */, EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */,
EGL10.EGL_STENCIL_SIZE, 8, EGL10.EGL_STENCIL_SIZE, 8,
EGL10.EGL_NONE }; EGL10.EGL_NONE};
if (!egl.eglChooseConfig(display, configSpec, null, 0, val)) { if (!egl.eglChooseConfig(display, configSpec, null, 0, val)) {
throw new IllegalArgumentException("eglChooseConfig failed"); throw new IllegalArgumentException("eglChooseConfig failed");
} }
int numConfigs = val[0]; int numConfigs = val[0];
if (numConfigs <= 0) { if (numConfigs <= 0) {
configSpec = new int[] { configSpec = new int[]{
// EGL10.EGL_RENDERABLE_TYPE, 4, EGL10.EGL_NONE }; // EGL10.EGL_RENDERABLE_TYPE, 4, EGL10.EGL_NONE };
EGL10.EGL_RED_SIZE, 8, EGL10.EGL_RED_SIZE, 8,
EGL10.EGL_GREEN_SIZE, 8, EGL10.EGL_GREEN_SIZE, 8,
EGL10.EGL_BLUE_SIZE, 8, EGL10.EGL_BLUE_SIZE, 8,
EGL10.EGL_ALPHA_SIZE, 8, EGL10.EGL_ALPHA_SIZE, 8,
EGL10.EGL_DEPTH_SIZE, 16, EGL10.EGL_DEPTH_SIZE, 16,
EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */, EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */,
EGL10.EGL_STENCIL_SIZE, 8, EGL10.EGL_STENCIL_SIZE, 8,
EGL10.EGL_NONE }; EGL10.EGL_NONE};
if (!egl.eglChooseConfig(display, configSpec, null, 0, val)) { if (!egl.eglChooseConfig(display, configSpec, null, 0, val)) {
throw new IllegalArgumentException("eglChooseConfig failed"); throw new IllegalArgumentException("eglChooseConfig failed");
} }
numConfigs = val[0]; numConfigs = val[0];
if (numConfigs <= 0) { if (numConfigs <= 0) {
throw new IllegalArgumentException("No configs match configSpec"); throw new IllegalArgumentException("No configs match configSpec");
} }
} }
// Get all matching configurations. // Get all matching configurations.
EGLConfig[] configs = new EGLConfig[numConfigs]; EGLConfig[] configs = new EGLConfig[numConfigs];
if (!egl.eglChooseConfig(display, configSpec, configs, numConfigs, val)) { if (!egl.eglChooseConfig(display, configSpec, configs, numConfigs, val)) {
throw new IllegalArgumentException("data eglChooseConfig failed"); throw new IllegalArgumentException("data eglChooseConfig failed");
} }
// CAUTION! eglChooseConfigs returns configs with higher bit depth // CAUTION! eglChooseConfigs returns configs with higher bit depth
// first: Even though we asked for rgb565 configurations, rgb888 // first: Even though we asked for rgb565 configurations, rgb888
// configurations are considered to be "better" and returned first. // configurations are considered to be "better" and returned first.
// You need to explicitly filter the data returned by eglChooseConfig! // You need to explicitly filter the data returned by eglChooseConfig!
EGLConfig config = configs.length > 0 ? configs[0] : null; EGLConfig config = configs.length > 0 ? configs[0] : null;
if (config == null) { if (config == null) {
throw new IllegalArgumentException("No config chosen"); throw new IllegalArgumentException("No config chosen");
} }
return config; return config;
} }
} }

View File

@@ -20,46 +20,46 @@ import org.oscim.event.MotionEvent;
public class AndroidMotionEvent extends MotionEvent { public class AndroidMotionEvent extends MotionEvent {
android.view.MotionEvent mEvent; android.view.MotionEvent mEvent;
public MotionEvent wrap(android.view.MotionEvent e) { public MotionEvent wrap(android.view.MotionEvent e) {
mEvent = e; mEvent = e;
return this; return this;
} }
@Override @Override
public int getAction() { public int getAction() {
return mEvent.getAction(); return mEvent.getAction();
} }
@Override @Override
public float getX() { public float getX() {
return mEvent.getX(); return mEvent.getX();
} }
@Override @Override
public float getY() { public float getY() {
return mEvent.getY(); return mEvent.getY();
} }
@Override @Override
public float getX(int pointer) { public float getX(int pointer) {
return mEvent.getX(pointer); return mEvent.getX(pointer);
} }
@Override @Override
public float getY(int pointer) { public float getY(int pointer) {
return mEvent.getY(pointer); return mEvent.getY(pointer);
} }
@Override @Override
public int getPointerCount() { public int getPointerCount() {
return mEvent.getPointerCount(); return mEvent.getPointerCount();
} }
@Override @Override
public long getTime() { public long getTime() {
return mEvent.getEventTime(); return mEvent.getEventTime();
} }
} }

View File

@@ -1,66 +1,66 @@
package org.oscim.android.input; package org.oscim.android.input;
import org.oscim.event.Gesture;
import org.oscim.map.Map;
import android.view.GestureDetector.OnDoubleTapListener; import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener; import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent; import android.view.MotionEvent;
public class GestureHandler implements OnGestureListener, OnDoubleTapListener { import org.oscim.event.Gesture;
private final AndroidMotionEvent mMotionEvent; import org.oscim.map.Map;
private final Map mMap;
public GestureHandler(Map map) { public class GestureHandler implements OnGestureListener, OnDoubleTapListener {
mMotionEvent = new AndroidMotionEvent(); private final AndroidMotionEvent mMotionEvent;
mMap = map; private final Map mMap;
}
public GestureHandler(Map map) {
mMotionEvent = new AndroidMotionEvent();
mMap = map;
}
/* GesturListener */ /* GesturListener */
@Override @Override
public boolean onSingleTapUp(MotionEvent e) { public boolean onSingleTapUp(MotionEvent e) {
// return mMap.handleGesture(Gesture.TAP, mMotionEvent.wrap(e)); // return mMap.handleGesture(Gesture.TAP, mMotionEvent.wrap(e));
return false; return false;
} }
@Override @Override
public void onShowPress(MotionEvent e) { public void onShowPress(MotionEvent e) {
} }
@Override @Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false; return false;
} }
@Override @Override
public void onLongPress(MotionEvent e) { public void onLongPress(MotionEvent e) {
mMap.handleGesture(Gesture.LONG_PRESS, mMotionEvent.wrap(e)); mMap.handleGesture(Gesture.LONG_PRESS, mMotionEvent.wrap(e));
} }
@Override @Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false; return false;
} }
@Override @Override
public boolean onDown(MotionEvent e) { public boolean onDown(MotionEvent e) {
return mMap.handleGesture(Gesture.PRESS, mMotionEvent.wrap(e)); return mMap.handleGesture(Gesture.PRESS, mMotionEvent.wrap(e));
} }
/* DoubleTapListener */ /* DoubleTapListener */
@Override @Override
public boolean onSingleTapConfirmed(MotionEvent e) { public boolean onSingleTapConfirmed(MotionEvent e) {
return mMap.handleGesture(Gesture.TAP, mMotionEvent.wrap(e)); return mMap.handleGesture(Gesture.TAP, mMotionEvent.wrap(e));
} }
@Override @Override
public boolean onDoubleTapEvent(MotionEvent e) { public boolean onDoubleTapEvent(MotionEvent e) {
return false; return false;
} }
@Override @Override
public boolean onDoubleTap(MotionEvent e) { public boolean onDoubleTap(MotionEvent e) {
return mMap.handleGesture(Gesture.DOUBLE_TAP, mMotionEvent.wrap(e)); return mMap.handleGesture(Gesture.DOUBLE_TAP, mMotionEvent.wrap(e));
} }
} }

View File

@@ -14,7 +14,6 @@ dependencies {
sourceSets { sourceSets {
main { main {
java.srcDirs = ['src'] java.srcDirs = ['src']
output.resourcesDir = 'assets'
} }
} }

View File

@@ -17,6 +17,13 @@
*/ */
package org.oscim.awt; package org.oscim.awt;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.BufferUtils;
import org.oscim.backend.GL;
import org.oscim.backend.canvas.Bitmap;
import org.oscim.renderer.bucket.TextureBucket;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@@ -25,130 +32,123 @@ import java.nio.IntBuffer;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import org.oscim.backend.GL;
import org.oscim.backend.canvas.Bitmap;
import org.oscim.renderer.bucket.TextureBucket;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.BufferUtils;
public class AwtBitmap implements Bitmap { public class AwtBitmap implements Bitmap {
BufferedImage bitmap; BufferedImage bitmap;
int width; int width;
int height; int height;
boolean internal; boolean internal;
public AwtBitmap(int width, int height, int format) { public AwtBitmap(int width, int height, int format) {
bitmap = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); bitmap = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
this.width = width; this.width = width;
this.height = height; this.height = height;
internal = true; internal = true;
// if (!this.bitmap.isAlphaPremultiplied()) // if (!this.bitmap.isAlphaPremultiplied())
// this.bitmap.coerceData(true); // this.bitmap.coerceData(true);
} }
AwtBitmap(InputStream inputStream) throws IOException { AwtBitmap(InputStream inputStream) throws IOException {
this.bitmap = ImageIO.read(inputStream); this.bitmap = ImageIO.read(inputStream);
this.width = this.bitmap.getWidth(); this.width = this.bitmap.getWidth();
this.height = this.bitmap.getHeight(); this.height = this.bitmap.getHeight();
if (!this.bitmap.isAlphaPremultiplied() if (!this.bitmap.isAlphaPremultiplied()
&& this.bitmap.getType() == BufferedImage.TYPE_INT_ARGB) && this.bitmap.getType() == BufferedImage.TYPE_INT_ARGB)
this.bitmap.coerceData(true); this.bitmap.coerceData(true);
} }
public AwtBitmap(BufferedImage bitmap) { public AwtBitmap(BufferedImage bitmap) {
this.bitmap = bitmap; this.bitmap = bitmap;
this.width = this.bitmap.getWidth(); this.width = this.bitmap.getWidth();
this.height = this.bitmap.getHeight(); this.height = this.bitmap.getHeight();
if (!this.bitmap.isAlphaPremultiplied() if (!this.bitmap.isAlphaPremultiplied()
&& this.bitmap.getType() == BufferedImage.TYPE_INT_ARGB) && this.bitmap.getType() == BufferedImage.TYPE_INT_ARGB)
this.bitmap.coerceData(true); this.bitmap.coerceData(true);
} }
@Override @Override
public int getWidth() { public int getWidth() {
return width; return width;
} }
@Override @Override
public int getHeight() { public int getHeight() {
return height; return height;
} }
@Override @Override
public int[] getPixels() { public int[] getPixels() {
return null; return null;
} }
@Override @Override
public void eraseColor(int transparent) { public void eraseColor(int transparent) {
} }
private final static IntBuffer tmpBuffer = BufferUtils private final static IntBuffer tmpBuffer = BufferUtils
.newIntBuffer(TextureBucket.TEXTURE_HEIGHT .newIntBuffer(TextureBucket.TEXTURE_HEIGHT
* TextureBucket.TEXTURE_WIDTH); * TextureBucket.TEXTURE_WIDTH);
private final static int[] tmpPixel = new int[TextureBucket.TEXTURE_HEIGHT private final static int[] tmpPixel = new int[TextureBucket.TEXTURE_HEIGHT
* TextureBucket.TEXTURE_WIDTH]; * TextureBucket.TEXTURE_WIDTH];
private final static boolean WRITE_TEX = false; private final static boolean WRITE_TEX = false;
private int dbgCnt; private int dbgCnt;
@Override @Override
public void uploadToTexture(boolean replace) { public void uploadToTexture(boolean replace) {
int[] pixels; int[] pixels;
IntBuffer buffer; IntBuffer buffer;
if (width * height < TextureBucket.TEXTURE_HEIGHT * TextureBucket.TEXTURE_WIDTH) { if (width * height < TextureBucket.TEXTURE_HEIGHT * TextureBucket.TEXTURE_WIDTH) {
pixels = tmpPixel; pixels = tmpPixel;
buffer = tmpBuffer; buffer = tmpBuffer;
buffer.clear(); buffer.clear();
} else { } else {
pixels = new int[width * height]; pixels = new int[width * height];
buffer = BufferUtils.newIntBuffer(width * height); buffer = BufferUtils.newIntBuffer(width * height);
} }
// FIXME dont convert to argb when there data is greyscale // FIXME dont convert to argb when there data is greyscale
bitmap.getRGB(0, 0, width, height, pixels, 0, width); bitmap.getRGB(0, 0, width, height, pixels, 0, width);
if (WRITE_TEX) { if (WRITE_TEX) {
try { try {
boolean ok = ImageIO.write(bitmap, "png", new File("texture_" + dbgCnt + ".png")); boolean ok = ImageIO.write(bitmap, "png", new File("texture_" + dbgCnt + ".png"));
System.out.println("write tex " + ok + " " + dbgCnt); System.out.println("write tex " + ok + " " + dbgCnt);
dbgCnt++; dbgCnt++;
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
for (int i = 0, n = width * height; i < n; i++) { for (int i = 0, n = width * height; i < n; i++) {
int c = pixels[i]; int c = pixels[i];
if (c == 0) if (c == 0)
continue; continue;
float alpha = (c >>> 24) / 255f; float alpha = (c >>> 24) / 255f;
int r = (int) ((c & 0x000000ff) * alpha); int r = (int) ((c & 0x000000ff) * alpha);
int b = (int) (((c & 0x00ff0000) >>> 16) * alpha); int b = (int) (((c & 0x00ff0000) >>> 16) * alpha);
int g = (int) (((c & 0x0000ff00) >>> 8) * alpha); int g = (int) (((c & 0x0000ff00) >>> 8) * alpha);
pixels[i] = (c & 0xff000000) | r << 16 | g << 8 | b; pixels[i] = (c & 0xff000000) | r << 16 | g << 8 | b;
} }
buffer.put(pixels, 0, width * height); buffer.put(pixels, 0, width * height);
buffer.flip(); buffer.flip();
Gdx.gl20.glTexImage2D(GL.TEXTURE_2D, 0, GL.RGBA, width, Gdx.gl20.glTexImage2D(GL.TEXTURE_2D, 0, GL.RGBA, width,
height, 0, GL.RGBA, GL.UNSIGNED_BYTE, buffer); height, 0, GL.RGBA, GL.UNSIGNED_BYTE, buffer);
} }
@Override @Override
public void recycle() { public void recycle() {
} }
@Override @Override
public boolean isValid() { public boolean isValid() {
return true; return true;
} }
} }

View File

@@ -17,6 +17,10 @@
*/ */
package org.oscim.awt; package org.oscim.awt;
import org.oscim.backend.canvas.Bitmap;
import org.oscim.backend.canvas.Canvas;
import org.oscim.backend.canvas.Paint;
import java.awt.AlphaComposite; import java.awt.AlphaComposite;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import java.awt.RenderingHints; import java.awt.RenderingHints;
@@ -24,73 +28,69 @@ import java.awt.Shape;
import java.awt.font.TextLayout; import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform; import java.awt.geom.AffineTransform;
import org.oscim.backend.canvas.Bitmap;
import org.oscim.backend.canvas.Canvas;
import org.oscim.backend.canvas.Paint;
public class AwtCanvas implements Canvas { public class AwtCanvas implements Canvas {
Graphics2D canvas; Graphics2D canvas;
public AwtCanvas() { public AwtCanvas() {
} }
@Override @Override
public void setBitmap(Bitmap bitmap) { public void setBitmap(Bitmap bitmap) {
if (canvas != null) if (canvas != null)
canvas.dispose(); canvas.dispose();
AwtBitmap awtBitamp = (AwtBitmap) bitmap; AwtBitmap awtBitamp = (AwtBitmap) bitmap;
canvas = awtBitamp.bitmap.createGraphics(); canvas = awtBitamp.bitmap.createGraphics();
canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0)); canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0));
canvas.fillRect(0, 0, bitmap.getWidth(), bitmap.getHeight()); canvas.fillRect(0, 0, bitmap.getWidth(), bitmap.getHeight());
canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
//canvas.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, //canvas.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
// RenderingHints.VALUE_FRACTIONALMETRICS_ON); // RenderingHints.VALUE_FRACTIONALMETRICS_ON);
canvas.setRenderingHint(RenderingHints.KEY_RENDERING, canvas.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY); RenderingHints.VALUE_RENDER_QUALITY);
canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON); RenderingHints.VALUE_ANTIALIAS_ON);
} }
private final AffineTransform tx = new AffineTransform(); private final AffineTransform tx = new AffineTransform();
@Override @Override
public void drawText(String text, float x, float y, Paint fill, Paint stroke) { public void drawText(String text, float x, float y, Paint fill, Paint stroke) {
AwtPaint fillPaint = (AwtPaint) fill; AwtPaint fillPaint = (AwtPaint) fill;
if (stroke == null) { if (stroke == null) {
canvas.setColor(fillPaint.color); canvas.setColor(fillPaint.color);
canvas.setFont(fillPaint.font); canvas.setFont(fillPaint.font);
canvas.drawString(text, x + AwtPaint.TEXT_OFFSET, y); canvas.drawString(text, x + AwtPaint.TEXT_OFFSET, y);
} else { } else {
AwtPaint strokePaint = (AwtPaint) stroke; AwtPaint strokePaint = (AwtPaint) stroke;
canvas.setColor(strokePaint.color); canvas.setColor(strokePaint.color);
canvas.setStroke(strokePaint.stroke); canvas.setStroke(strokePaint.stroke);
TextLayout tl = new TextLayout(text, fillPaint.font, TextLayout tl = new TextLayout(text, fillPaint.font,
canvas.getFontRenderContext()); canvas.getFontRenderContext());
tx.setToIdentity(); tx.setToIdentity();
tx.translate(x, y); tx.translate(x, y);
Shape s = tl.getOutline(tx); Shape s = tl.getOutline(tx);
canvas.draw(s); canvas.draw(s);
canvas.setColor(fillPaint.color); canvas.setColor(fillPaint.color);
canvas.fill(s); canvas.fill(s);
} }
} }
@Override @Override
public void drawBitmap(Bitmap bitmap, float x, float y) { public void drawBitmap(Bitmap bitmap, float x, float y) {
throw new UnknownError("not implemented"); throw new UnknownError("not implemented");
} }
} }

View File

@@ -17,6 +17,11 @@
*/ */
package org.oscim.awt; package org.oscim.awt;
import org.oscim.backend.CanvasAdapter;
import org.oscim.backend.canvas.Bitmap;
import org.oscim.backend.canvas.Canvas;
import org.oscim.backend.canvas.Paint;
import java.awt.Font; import java.awt.Font;
import java.awt.FontMetrics; import java.awt.FontMetrics;
import java.awt.Graphics2D; import java.awt.Graphics2D;
@@ -25,88 +30,83 @@ import java.awt.image.BufferedImage;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import org.oscim.backend.CanvasAdapter;
import org.oscim.backend.canvas.Bitmap;
import org.oscim.backend.canvas.Canvas;
import org.oscim.backend.canvas.Paint;
public class AwtGraphics extends CanvasAdapter { public class AwtGraphics extends CanvasAdapter {
public static void init() { public static void init() {
CanvasAdapter.init(new AwtGraphics()); CanvasAdapter.init(new AwtGraphics());
} }
public static BufferedImage getBitmap(Bitmap bitmap) { public static BufferedImage getBitmap(Bitmap bitmap) {
return ((AwtBitmap) bitmap).bitmap; return ((AwtBitmap) bitmap).bitmap;
} }
private AwtGraphics() { private AwtGraphics() {
// do nothing // do nothing
} }
@Override @Override
public Paint newPaintImpl() { public Paint newPaintImpl() {
return new AwtPaint(); return new AwtPaint();
} }
@Override @Override
public Bitmap newBitmapImpl(int width, int height, int format) { public Bitmap newBitmapImpl(int width, int height, int format) {
return new AwtBitmap(width, height, format); return new AwtBitmap(width, height, format);
} }
@Override @Override
public Canvas newCanvasImpl() { public Canvas newCanvasImpl() {
return new AwtCanvas(); return new AwtCanvas();
} }
static final BufferedImage image; static final BufferedImage image;
static final Graphics2D canvas; static final Graphics2D canvas;
static { static {
image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
canvas = image.createGraphics(); canvas = image.createGraphics();
canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON); RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//canvas.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); //canvas.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
//canvas.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); //canvas.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
} }
static synchronized FontMetrics getFontMetrics(Font font) { static synchronized FontMetrics getFontMetrics(Font font) {
canvas.setFont(font); canvas.setFont(font);
// get character measurements // get character measurements
FontMetrics fm = canvas.getFontMetrics(); FontMetrics fm = canvas.getFontMetrics();
// int ascent = fm.getMaxAscent(); // int ascent = fm.getMaxAscent();
// int descent = fm.getMaxDescent(); // int descent = fm.getMaxDescent();
// int advance = fm.charWidth('W'); // width of widest char, more // int advance = fm.charWidth('W'); // width of widest char, more
// reliable than getMaxAdvance(); // reliable than getMaxAdvance();
// int leading = fm.getLeading(); // int leading = fm.getLeading();
// //
return fm; return fm;
} }
static synchronized float getTextWidth(FontMetrics fm, String text) { static synchronized float getTextWidth(FontMetrics fm, String text) {
//return (float)fm.getStringBounds(text, canvas).getWidth(); //return (float)fm.getStringBounds(text, canvas).getWidth();
return fm.stringWidth(text); return fm.stringWidth(text);
} }
@Override @Override
public Bitmap decodeBitmapImpl(InputStream inputStream) { public Bitmap decodeBitmapImpl(InputStream inputStream) {
try { try {
return new AwtBitmap(inputStream); return new AwtBitmap(inputStream);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
@Override @Override
public Bitmap loadBitmapAssetImpl(String fileName) { public Bitmap loadBitmapAssetImpl(String fileName) {
try { try {
return createBitmap(fileName); return createBitmap(fileName);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
} }

View File

@@ -17,6 +17,8 @@
*/ */
package org.oscim.awt; package org.oscim.awt;
import org.oscim.backend.canvas.Paint;
import java.awt.BasicStroke; import java.awt.BasicStroke;
import java.awt.Color; import java.awt.Color;
import java.awt.Font; import java.awt.Font;
@@ -27,136 +29,135 @@ import java.text.AttributedCharacterIterator.Attribute;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.oscim.backend.canvas.Paint;
public class AwtPaint implements Paint { public class AwtPaint implements Paint {
final static float TEXT_OFFSET = 2; final static float TEXT_OFFSET = 2;
private static int getCap(Cap cap) { private static int getCap(Cap cap) {
switch (cap) { switch (cap) {
case BUTT: case BUTT:
return BasicStroke.CAP_BUTT; return BasicStroke.CAP_BUTT;
case ROUND: case ROUND:
return BasicStroke.CAP_ROUND; return BasicStroke.CAP_ROUND;
case SQUARE: case SQUARE:
return BasicStroke.CAP_SQUARE; return BasicStroke.CAP_SQUARE;
} }
throw new IllegalArgumentException("unknown cap: " + cap); throw new IllegalArgumentException("unknown cap: " + cap);
} }
static final Font defaultFont; static final Font defaultFont;
static {
Map<Attribute, Object> textAttributes = new HashMap<Attribute, Object>();
textAttributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
textAttributes.put(TextAttribute.FAMILY, "Arial");
textAttributes.put(TextAttribute.SIZE, 14);
defaultFont = Font.getFont(textAttributes); static {
} Map<Attribute, Object> textAttributes = new HashMap<Attribute, Object>();
textAttributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
textAttributes.put(TextAttribute.FAMILY, "Arial");
textAttributes.put(TextAttribute.SIZE, 14);
Font font = defaultFont; // new Font("Default", Font.PLAIN, 13); defaultFont = Font.getFont(textAttributes);
Stroke stroke; }
FontMetrics fm;
Color color = new Color(0.1f, 0.1f, 0.1f, 1);
private int cap; Font font = defaultFont; // new Font("Default", Font.PLAIN, 13);
private float strokeWidth; Stroke stroke;
FontMetrics fm;
Color color = new Color(0.1f, 0.1f, 0.1f, 1);
//private Align mAlign; private int cap;
private float strokeWidth;
@Override //private Align mAlign;
public int getColor() {
return 0;
}
@Override @Override
public void setColor(int c) { public int getColor() {
color = new Color(((c >> 16) & 0xff) / 255f, return 0;
((c >> 8) & 0xff) / 255f, }
((c >> 0) & 0xff) / 255f,
((c >> 24) & 0xff) / 255f);
}
@Override @Override
public void setStrokeCap(Cap cap) { public void setColor(int c) {
this.cap = getCap(cap); color = new Color(((c >> 16) & 0xff) / 255f,
createStroke(); ((c >> 8) & 0xff) / 255f,
} ((c >> 0) & 0xff) / 255f,
((c >> 24) & 0xff) / 255f);
}
@Override @Override
public void setStrokeWidth(float width) { public void setStrokeCap(Cap cap) {
strokeWidth = width + 1; this.cap = getCap(cap);
createStroke(); createStroke();
}
// int size = font.getSize(); @Override
// font = font.deriveFont(size + width * 4); public void setStrokeWidth(float width) {
strokeWidth = width + 1;
createStroke();
// TODO Auto-generated method stub // int size = font.getSize();
// font = font.deriveFont(size + width * 4);
} // TODO Auto-generated method stub
@Override }
public void setStyle(Style style) {
// TODO Auto-generated method stub
} @Override
public void setStyle(Style style) {
// TODO Auto-generated method stub
@Override }
public void setTextAlign(Align align) {
//mAlign = align;
}
@Override @Override
public void setTextSize(float textSize) { public void setTextAlign(Align align) {
font = font.deriveFont(textSize); //mAlign = align;
}
} @Override
public void setTextSize(float textSize) {
font = font.deriveFont(textSize);
@Override }
public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) {
// TODO Auto-generated method stub
} @Override
public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) {
// TODO Auto-generated method stub
@Override }
public float measureText(String text) {
if (fm == null)
fm = AwtGraphics.getFontMetrics(this.font);
float w = AwtGraphics.getTextWidth(fm, text); @Override
//Gdx.app.log("text width:", text + " " + w); public float measureText(String text) {
return w + 4; if (fm == null)
// return fm.getStringBounds(text, A).getWidth(); fm = AwtGraphics.getFontMetrics(this.font);
// return AwtGraphics.getTextWidth(fm, text);
// return fm.stringWidth(text);
}
@Override float w = AwtGraphics.getTextWidth(fm, text);
public float getFontHeight() { //Gdx.app.log("text width:", text + " " + w);
if (fm == null) return w + 4;
fm = AwtGraphics.getFontMetrics(this.font); // return fm.getStringBounds(text, A).getWidth();
// return AwtGraphics.getTextWidth(fm, text);
// return fm.stringWidth(text);
}
float height = fm.getHeight(); @Override
public float getFontHeight() {
if (fm == null)
fm = AwtGraphics.getFontMetrics(this.font);
return height; float height = fm.getHeight();
}
@Override return height;
public float getFontDescent() { }
if (fm == null)
fm = AwtGraphics.getFontMetrics(this.font);
float desc = fm.getDescent(); @Override
public float getFontDescent() {
if (fm == null)
fm = AwtGraphics.getFontMetrics(this.font);
return desc; float desc = fm.getDescent();
}
private void createStroke() { return desc;
if (strokeWidth <= 0) { }
return;
} private void createStroke() {
stroke = new BasicStroke(strokeWidth, cap, BasicStroke.JOIN_MITER, 1, null, 0); if (strokeWidth <= 0) {
} return;
}
stroke = new BasicStroke(strokeWidth, cap, BasicStroke.JOIN_MITER, 1, null, 0);
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -17,6 +17,10 @@
*/ */
package org.oscim.gdx; package org.oscim.gdx;
import com.badlogic.gdx.backends.jglfw.JglfwApplication;
import com.badlogic.gdx.backends.jglfw.JglfwApplicationConfiguration;
import com.badlogic.gdx.utils.SharedLibraryLoader;
import org.oscim.awt.AwtGraphics; import org.oscim.awt.AwtGraphics;
import org.oscim.backend.GLAdapter; import org.oscim.backend.GLAdapter;
import org.oscim.core.Tile; import org.oscim.core.Tile;
@@ -26,65 +30,61 @@ import org.oscim.utils.FastMath;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.badlogic.gdx.backends.jglfw.JglfwApplication;
import com.badlogic.gdx.backends.jglfw.JglfwApplicationConfiguration;
import com.badlogic.gdx.utils.SharedLibraryLoader;
public class GdxMapApp extends GdxMap { public class GdxMapApp extends GdxMap {
public static final Logger log = LoggerFactory.getLogger(GdxMapApp.class); public static final Logger log = LoggerFactory.getLogger(GdxMapApp.class);
public static void init() { public static void init() {
// load native library // load native library
new SharedLibraryLoader().load("vtm-jni"); new SharedLibraryLoader().load("vtm-jni");
// init globals // init globals
AwtGraphics.init(); AwtGraphics.init();
GdxAssets.init("assets/"); GdxAssets.init("assets/");
GLAdapter.init(new GdxGL()); GLAdapter.init(new GdxGL());
GLAdapter.GDX_DESKTOP_QUIRKS = true; GLAdapter.GDX_DESKTOP_QUIRKS = true;
} }
public static void main(String[] args) { public static void main(String[] args) {
Tile.SIZE = 360; Tile.SIZE = 360;
init(); init();
new JglfwApplication(new GdxMapApp(), getConfig()); new JglfwApplication(new GdxMapApp(), getConfig());
} }
public static void run(GdxMap map, JglfwApplicationConfiguration config, int tileSize) { public static void run(GdxMap map, JglfwApplicationConfiguration config, int tileSize) {
Tile.SIZE = FastMath.clamp(tileSize, 128, 512); Tile.SIZE = FastMath.clamp(tileSize, 128, 512);
new JglfwApplication(map, (config == null ? getConfig() : config)); new JglfwApplication(map, (config == null ? getConfig() : config));
} }
public static void run(JglfwApplicationConfiguration config, int tileSize, GdxMap map) { public static void run(JglfwApplicationConfiguration config, int tileSize, GdxMap map) {
run(map, config, tileSize); run(map, config, tileSize);
} }
static protected JglfwApplicationConfiguration getConfig() { static protected JglfwApplicationConfiguration getConfig() {
JglfwApplicationConfiguration cfg = new JglfwApplicationConfiguration(); JglfwApplicationConfiguration cfg = new JglfwApplicationConfiguration();
cfg.title = "vtm-gdx"; cfg.title = "vtm-gdx";
cfg.width = 800; cfg.width = 800;
cfg.height = 600; cfg.height = 600;
cfg.stencil = 8; cfg.stencil = 8;
//cfg.samples = 2; //cfg.samples = 2;
cfg.foregroundFPS = 30; cfg.foregroundFPS = 30;
cfg.backgroundFPS = 10; cfg.backgroundFPS = 10;
return cfg; return cfg;
} }
@Override @Override
public void createLayers() { public void createLayers() {
TileSource tileSource = new OSciMap4TileSource(); TileSource tileSource = new OSciMap4TileSource();
// TileSource tileSource = new MapFileTileSource(); // TileSource tileSource = new MapFileTileSource();
// tileSource.setOption("file", "/home/jeff/germany.map"); // tileSource.setOption("file", "/home/jeff/germany.map");
initDefaultLayers(tileSource, false, true, true); initDefaultLayers(tileSource, false, true, true);
//mMap.getLayers().add(new BitmapTileLayer(mMap, new ImagicoLandcover(), 20)); //mMap.getLayers().add(new BitmapTileLayer(mMap, new ImagicoLandcover(), 20));
//mMap.getLayers().add(new BitmapTileLayer(mMap, new OSMTileSource(), 20)); //mMap.getLayers().add(new BitmapTileLayer(mMap, new OSMTileSource(), 20));
//mMap.getLayers().add(new BitmapTileLayer(mMap, new ArcGISWorldShaded(), 20)); //mMap.getLayers().add(new BitmapTileLayer(mMap, new ArcGISWorldShaded(), 20));
mMap.setMapPosition(0, 0, 1 << 2); mMap.setMapPosition(0, 0, 1 << 2);
} }
} }

View File

@@ -23,35 +23,35 @@ import java.util.Collection;
*/ */
public class OsmData { public class OsmData {
private final Collection<Bound> bounds; private final Collection<Bound> bounds;
private final Collection<OsmNode> nodes; private final Collection<OsmNode> nodes;
private final Collection<OsmWay> ways; private final Collection<OsmWay> ways;
private final Collection<OsmRelation> relations; private final Collection<OsmRelation> relations;
public OsmData(Collection<Bound> bounds, Collection<OsmNode> nodes, public OsmData(Collection<Bound> bounds, Collection<OsmNode> nodes,
Collection<OsmWay> ways, Collection<OsmRelation> relations) { Collection<OsmWay> ways, Collection<OsmRelation> relations) {
this.bounds = bounds; this.bounds = bounds;
this.nodes = nodes; this.nodes = nodes;
this.ways = ways; this.ways = ways;
this.relations = relations; this.relations = relations;
} }
public Collection<OsmNode> getNodes() { public Collection<OsmNode> getNodes() {
return nodes; return nodes;
} }
public Collection<OsmWay> getWays() { public Collection<OsmWay> getWays() {
return ways; return ways;
} }
public Collection<OsmRelation> getRelations() { public Collection<OsmRelation> getRelations() {
return relations; return relations;
} }
public Collection<Bound> getBounds() { public Collection<Bound> getBounds() {
return bounds; return bounds;
} }
} }

View File

@@ -16,50 +16,50 @@
*/ */
package org.oscim.core.osm; package org.oscim.core.osm;
import org.oscim.core.TagSet;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import org.oscim.core.TagSet;
public abstract class OsmElement { public abstract class OsmElement {
public final TagSet tags; public final TagSet tags;
public final long id; public final long id;
public OsmElement(TagSet tags, long id) { public OsmElement(TagSet tags, long id) {
assert tags != null; assert tags != null;
this.tags = tags; this.tags = tags;
this.id = id; this.id = id;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + (int) (id ^ (id >>> 32)); result = prime * result + (int) (id ^ (id >>> 32));
return result; return result;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) if (this == obj)
return true; return true;
if (obj == null) if (obj == null)
return false; return false;
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
OsmElement other = (OsmElement) obj; OsmElement other = (OsmElement) obj;
if (id != other.id) if (id != other.id)
return false; return false;
return true; return true;
} }
/** /**
* returns the id, plus an one-letter prefix for the element type * returns the id, plus an one-letter prefix for the element type
*/ */
@Override @Override
public String toString() { public String toString() {
return "?" + id; return "?" + id;
} }
public abstract Geometry toJts(); public abstract Geometry toJts();
} }

View File

@@ -17,24 +17,24 @@
package org.oscim.core.osm; package org.oscim.core.osm;
public class OsmMember { public class OsmMember {
public enum MemberType { public enum MemberType {
NODE, NODE,
WAY, WAY,
RELATIOM RELATIOM
} }
public final String role; public final String role;
public final OsmElement member; public final OsmElement member;
public OsmMember(String role, OsmElement member) { public OsmMember(String role, OsmElement member) {
assert role != null && member != null; assert role != null && member != null;
this.role = role; this.role = role;
this.member = member; this.member = member;
} }
@Override @Override
public String toString() { public String toString() {
return role + ":" + member; return role + ":" + member;
} }
} }

View File

@@ -16,28 +16,28 @@
*/ */
package org.oscim.core.osm; package org.oscim.core.osm;
import org.oscim.core.TagSet;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import org.oscim.core.TagSet;
public class OsmNode extends OsmElement { public class OsmNode extends OsmElement {
public final double lat; public final double lat;
public final double lon; public final double lon;
public OsmNode(double lat, double lon, TagSet tags, long id) { public OsmNode(double lat, double lon, TagSet tags, long id) {
super(tags, id); super(tags, id);
this.lat = lat; this.lat = lat;
this.lon = lon; this.lon = lon;
} }
@Override @Override
public String toString() { public String toString() {
return "n" + id; return "n" + id;
} }
@Override @Override
public Geometry toJts() { public Geometry toJts() {
return null; //bnew Point(new Coordinate(lat, lon), null); return null; //bnew Point(new Coordinate(lat, lon), null);
} }
} }

View File

@@ -16,32 +16,32 @@
*/ */
package org.oscim.core.osm; package org.oscim.core.osm;
import java.util.ArrayList; import com.vividsolutions.jts.geom.Geometry;
import java.util.List;
import org.oscim.core.TagSet; import org.oscim.core.TagSet;
import com.vividsolutions.jts.geom.Geometry; import java.util.ArrayList;
import java.util.List;
public class OsmRelation extends OsmElement { public class OsmRelation extends OsmElement {
public final List<OsmMember> relationMembers; public final List<OsmMember> relationMembers;
// content added after constructor call // content added after constructor call
public OsmRelation(TagSet tags, long id, int initialMemberSize) { public OsmRelation(TagSet tags, long id, int initialMemberSize) {
super(tags, id); super(tags, id);
this.relationMembers = this.relationMembers =
new ArrayList<OsmMember>(initialMemberSize); new ArrayList<OsmMember>(initialMemberSize);
} }
@Override @Override
public String toString() { public String toString() {
return "r" + id; return "r" + id;
} }
@Override @Override
public Geometry toJts() { public Geometry toJts() {
return null; return null;
} }
} }

View File

@@ -16,43 +16,43 @@
*/ */
package org.oscim.core.osm; package org.oscim.core.osm;
import java.util.List;
import org.oscim.core.TagSet;
import com.vividsolutions.jts.geom.CoordinateSequence; import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.impl.PackedCoordinateSequenceFactory; import com.vividsolutions.jts.geom.impl.PackedCoordinateSequenceFactory;
import org.oscim.core.TagSet;
import java.util.List;
public class OsmWay extends OsmElement { public class OsmWay extends OsmElement {
public final List<OsmNode> nodes; public final List<OsmNode> nodes;
public OsmWay(TagSet tags, long id, List<OsmNode> nodes) { public OsmWay(TagSet tags, long id, List<OsmNode> nodes) {
super(tags, id); super(tags, id);
this.nodes = nodes; this.nodes = nodes;
} }
public boolean isClosed() { public boolean isClosed() {
return nodes.size() > 0 && return nodes.size() > 0 &&
nodes.get(0).equals(nodes.get(nodes.size() - 1)); nodes.get(0).equals(nodes.get(nodes.size() - 1));
} }
@Override @Override
public String toString() { public String toString() {
return "w" + id; return "w" + id;
} }
public Geometry toJts() { public Geometry toJts() {
double[] coords = new double[nodes.size() * 2]; double[] coords = new double[nodes.size() * 2];
int i = 0; int i = 0;
for (OsmNode n : nodes) { for (OsmNode n : nodes) {
coords[i++] = n.lon; coords[i++] = n.lon;
coords[i++] = n.lat; coords[i++] = n.lat;
} }
CoordinateSequence c = PackedCoordinateSequenceFactory.DOUBLE_FACTORY.create(coords, 2); CoordinateSequence c = PackedCoordinateSequenceFactory.DOUBLE_FACTORY.create(coords, 2);
return new LineString(c, null); return new LineString(c, null);
} }
} }

View File

@@ -7,13 +7,13 @@ import org.oscim.map.Map;
public class OsmVectorLayer extends AbstractVectorLayer<OsmElement> { public class OsmVectorLayer extends AbstractVectorLayer<OsmElement> {
public OsmVectorLayer(Map map) { public OsmVectorLayer(Map map) {
super(map); super(map);
} }
@Override @Override
protected void processFeatures(Task t, Box b) { protected void processFeatures(Task t, Box b) {
} }
} }

View File

@@ -16,6 +16,25 @@
*/ */
package org.oscim.tiling.source.geojson; package org.oscim.tiling.source.geojson;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import org.oscim.core.GeometryBuffer.GeometryType;
import org.oscim.core.MapElement;
import org.oscim.core.Tile;
import org.oscim.tiling.ITileDataSink;
import org.oscim.tiling.source.ITileDecoder;
import org.oscim.utils.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import static com.fasterxml.jackson.core.JsonToken.END_ARRAY; import static com.fasterxml.jackson.core.JsonToken.END_ARRAY;
import static com.fasterxml.jackson.core.JsonToken.END_OBJECT; import static com.fasterxml.jackson.core.JsonToken.END_OBJECT;
import static com.fasterxml.jackson.core.JsonToken.FIELD_NAME; import static com.fasterxml.jackson.core.JsonToken.FIELD_NAME;
@@ -27,324 +46,304 @@ import static com.fasterxml.jackson.core.JsonToken.VALUE_STRING;
import static org.oscim.core.MercatorProjection.latitudeToY; import static org.oscim.core.MercatorProjection.latitudeToY;
import static org.oscim.core.MercatorProjection.longitudeToX; import static org.oscim.core.MercatorProjection.longitudeToX;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import org.oscim.core.GeometryBuffer.GeometryType;
import org.oscim.core.MapElement;
import org.oscim.core.Tile;
import org.oscim.tiling.ITileDataSink;
import org.oscim.tiling.source.ITileDecoder;
import org.oscim.utils.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
public class GeoJsonTileDecoder implements ITileDecoder { public class GeoJsonTileDecoder implements ITileDecoder {
static final Logger log = LoggerFactory.getLogger(GeoJsonTileDecoder.class); static final Logger log = LoggerFactory.getLogger(GeoJsonTileDecoder.class);
private final MapElement mMapElement; private final MapElement mMapElement;
private final GeoJsonTileSource mTileSource; private final GeoJsonTileSource mTileSource;
private final LinkedHashMap<String, Object> mTagMap; private final LinkedHashMap<String, Object> mTagMap;
private final JsonFactory mJsonFactory; private final JsonFactory mJsonFactory;
private final static char[] FIELD_FEATURES = "features".toCharArray(); private final static char[] FIELD_FEATURES = "features".toCharArray();
private final static char[] FIELD_GEOMETRY = "geometry".toCharArray(); private final static char[] FIELD_GEOMETRY = "geometry".toCharArray();
private final static char[] FIELD_PROPERTIES = "properties".toCharArray(); private final static char[] FIELD_PROPERTIES = "properties".toCharArray();
private final static char[] FIELD_COORDINATES = "coordinates".toCharArray(); private final static char[] FIELD_COORDINATES = "coordinates".toCharArray();
private final static char[] FIELD_TYPE = "type".toCharArray(); private final static char[] FIELD_TYPE = "type".toCharArray();
private final static char[] LINETRING = "LineString".toCharArray(); private final static char[] LINETRING = "LineString".toCharArray();
private final static char[] POLYGON = "Polygon".toCharArray(); private final static char[] POLYGON = "Polygon".toCharArray();
private final static char[] POINT = "Point".toCharArray(); private final static char[] POINT = "Point".toCharArray();
private final static char[] MULTI_LINESTRING = "MultiLineString".toCharArray(); private final static char[] MULTI_LINESTRING = "MultiLineString".toCharArray();
private final static char[] MULTI_POLYGON = "MultiPolygon".toCharArray(); private final static char[] MULTI_POLYGON = "MultiPolygon".toCharArray();
private final static char[] MULTI_POINT = "MultiPoint".toCharArray(); private final static char[] MULTI_POINT = "MultiPoint".toCharArray();
private ITileDataSink mTileDataSink; private ITileDataSink mTileDataSink;
private double mTileY, mTileX, mTileScale; private double mTileY, mTileX, mTileScale;
public GeoJsonTileDecoder(GeoJsonTileSource tileSource) { public GeoJsonTileDecoder(GeoJsonTileSource tileSource) {
mTileSource = tileSource; mTileSource = tileSource;
mTagMap = new LinkedHashMap<String, Object>(); mTagMap = new LinkedHashMap<String, Object>();
mJsonFactory = new JsonFactory(); mJsonFactory = new JsonFactory();
mMapElement = new MapElement(); mMapElement = new MapElement();
mMapElement.layer = 5; mMapElement.layer = 5;
} }
@Override @Override
public boolean decode(Tile tile, ITileDataSink sink, InputStream is) throws IOException { public boolean decode(Tile tile, ITileDataSink sink, InputStream is) throws IOException {
mTileDataSink = sink; mTileDataSink = sink;
mTileScale = 1 << tile.zoomLevel; mTileScale = 1 << tile.zoomLevel;
mTileX = tile.tileX / mTileScale; mTileX = tile.tileX / mTileScale;
mTileY = tile.tileY / mTileScale; mTileY = tile.tileY / mTileScale;
mTileScale *= Tile.SIZE; mTileScale *= Tile.SIZE;
JsonParser jp = mJsonFactory.createParser(new InputStreamReader(is)); JsonParser jp = mJsonFactory.createParser(new InputStreamReader(is));
for (JsonToken t; (t = jp.nextToken()) != null;) { for (JsonToken t; (t = jp.nextToken()) != null; ) {
if (t == FIELD_NAME) { if (t == FIELD_NAME) {
if (match(jp, FIELD_FEATURES)) { if (match(jp, FIELD_FEATURES)) {
if (jp.nextToken() != START_ARRAY) if (jp.nextToken() != START_ARRAY)
continue; continue;
while ((t = jp.nextToken()) != null) { while ((t = jp.nextToken()) != null) {
if (t == START_OBJECT) if (t == START_OBJECT)
parseFeature(jp); parseFeature(jp);
if (t == END_ARRAY) if (t == END_ARRAY)
break; break;
} }
} }
} }
} }
return true; return true;
} }
private void parseFeature(JsonParser jp) private void parseFeature(JsonParser jp)
throws JsonParseException, IOException { throws JsonParseException, IOException {
mMapElement.clear(); mMapElement.clear();
mMapElement.tags.clear(); mMapElement.tags.clear();
mTagMap.clear(); mTagMap.clear();
for (JsonToken t; (t = jp.nextToken()) != null;) { for (JsonToken t; (t = jp.nextToken()) != null; ) {
if (t == FIELD_NAME) { if (t == FIELD_NAME) {
if (match(jp, FIELD_GEOMETRY)) { if (match(jp, FIELD_GEOMETRY)) {
if (jp.nextToken() == START_OBJECT) if (jp.nextToken() == START_OBJECT)
parseGeometry(jp); parseGeometry(jp);
} }
if (match(jp, FIELD_PROPERTIES)) { if (match(jp, FIELD_PROPERTIES)) {
if (jp.nextToken() == START_OBJECT) if (jp.nextToken() == START_OBJECT)
parseProperties(jp); parseProperties(jp);
} }
continue; continue;
} }
if (t == END_OBJECT) if (t == END_OBJECT)
break; break;
} }
//add tag information //add tag information
mTileSource.decodeTags(mMapElement, mTagMap); mTileSource.decodeTags(mMapElement, mTagMap);
if (mMapElement.tags.numTags == 0) if (mMapElement.tags.numTags == 0)
return; return;
mTileSource.postGeomHook(mMapElement); mTileSource.postGeomHook(mMapElement);
if (mMapElement.type == GeometryType.NONE) if (mMapElement.type == GeometryType.NONE)
return; return;
//process this element //process this element
mTileDataSink.process(mMapElement); mTileDataSink.process(mMapElement);
} }
private void parseProperties(JsonParser jp) private void parseProperties(JsonParser jp)
throws JsonParseException, IOException { throws JsonParseException, IOException {
for (JsonToken t; (t = jp.nextToken()) != null;) { for (JsonToken t; (t = jp.nextToken()) != null; ) {
if (t == FIELD_NAME) { if (t == FIELD_NAME) {
String text = jp.getCurrentName(); String text = jp.getCurrentName();
t = jp.nextToken(); t = jp.nextToken();
if (t == VALUE_STRING) { if (t == VALUE_STRING) {
mTagMap.put(text, jp.getText()); mTagMap.put(text, jp.getText());
} else if (t == VALUE_NUMBER_INT) { } else if (t == VALUE_NUMBER_INT) {
mTagMap.put(text, jp.getNumberValue()); mTagMap.put(text, jp.getNumberValue());
} }
continue; continue;
} }
if (t == END_OBJECT) if (t == END_OBJECT)
break; break;
} }
} }
private void parseGeometry(JsonParser jp) private void parseGeometry(JsonParser jp)
throws JsonParseException, IOException { throws JsonParseException, IOException {
boolean multi = false; boolean multi = false;
GeometryType type = GeometryType.NONE; GeometryType type = GeometryType.NONE;
for (JsonToken t; (t = jp.nextToken()) != null;) { for (JsonToken t; (t = jp.nextToken()) != null; ) {
if (t == FIELD_NAME) { if (t == FIELD_NAME) {
if (match(jp, FIELD_COORDINATES)) { if (match(jp, FIELD_COORDINATES)) {
if (jp.nextToken() != START_ARRAY) if (jp.nextToken() != START_ARRAY)
continue; continue;
if (multi) { if (multi) {
parseMulti(jp, type); parseMulti(jp, type);
} else { } else {
if (type == GeometryType.POLY) if (type == GeometryType.POLY)
parsePolygon(jp); parsePolygon(jp);
if (type == GeometryType.LINE) if (type == GeometryType.LINE)
parseLineString(jp); parseLineString(jp);
if (type == GeometryType.POINT) if (type == GeometryType.POINT)
parseCoordinate(jp); parseCoordinate(jp);
} }
} else if (match(jp, FIELD_TYPE)) { } else if (match(jp, FIELD_TYPE)) {
multi = false; multi = false;
jp.nextToken(); jp.nextToken();
if (match(jp, LINETRING)) if (match(jp, LINETRING))
type = GeometryType.LINE; type = GeometryType.LINE;
else if (match(jp, POLYGON)) else if (match(jp, POLYGON))
type = GeometryType.POLY; type = GeometryType.POLY;
else if (match(jp, POINT)) else if (match(jp, POINT))
type = GeometryType.POINT; type = GeometryType.POINT;
else if (match(jp, MULTI_LINESTRING)) { else if (match(jp, MULTI_LINESTRING)) {
type = GeometryType.LINE; type = GeometryType.LINE;
multi = true; multi = true;
} } else if (match(jp, MULTI_POLYGON)) {
else if (match(jp, MULTI_POLYGON)) { type = GeometryType.POLY;
type = GeometryType.POLY; multi = true;
multi = true; } else if (match(jp, MULTI_POINT)) {
} type = GeometryType.POINT;
else if (match(jp, MULTI_POINT)) { multi = true;
type = GeometryType.POINT; }
multi = true;
}
if (type == GeometryType.POINT) if (type == GeometryType.POINT)
mMapElement.startPoints(); mMapElement.startPoints();
} }
continue; continue;
} }
if (t == END_OBJECT) if (t == END_OBJECT)
break; break;
} }
} }
private void parseMulti(JsonParser jp, GeometryType type) private void parseMulti(JsonParser jp, GeometryType type)
throws JsonParseException, IOException { throws JsonParseException, IOException {
for (JsonToken t; (t = jp.nextToken()) != null;) { for (JsonToken t; (t = jp.nextToken()) != null; ) {
if (t == END_ARRAY) if (t == END_ARRAY)
break; break;
if (t == START_ARRAY) { if (t == START_ARRAY) {
if (type == GeometryType.POLY) if (type == GeometryType.POLY)
parsePolygon(jp); parsePolygon(jp);
else if (type == GeometryType.LINE) else if (type == GeometryType.LINE)
parseLineString(jp); parseLineString(jp);
else if (type == GeometryType.POINT) else if (type == GeometryType.POINT)
parseCoordinate(jp);; parseCoordinate(jp);
;
} else { } else {
//.... //....
} }
} }
} }
private void parsePolygon(JsonParser jp) private void parsePolygon(JsonParser jp)
throws JsonParseException, IOException { throws JsonParseException, IOException {
int ring = 0; int ring = 0;
for (JsonToken t; (t = jp.nextToken()) != null;) { for (JsonToken t; (t = jp.nextToken()) != null; ) {
if (t == START_ARRAY) { if (t == START_ARRAY) {
if (ring == 0) if (ring == 0)
mMapElement.startPolygon(); mMapElement.startPolygon();
else else
mMapElement.startHole(); mMapElement.startHole();
ring++; ring++;
parseCoordSequence(jp); parseCoordSequence(jp);
removeLastPoint(); removeLastPoint();
continue; continue;
} }
if (t == END_ARRAY) if (t == END_ARRAY)
break; break;
} }
} }
private void removeLastPoint() { private void removeLastPoint() {
mMapElement.pointPos -= 2; mMapElement.pointPos -= 2;
mMapElement.index[mMapElement.indexPos] -= 2; mMapElement.index[mMapElement.indexPos] -= 2;
} }
private void parseLineString(JsonParser jp) private void parseLineString(JsonParser jp)
throws JsonParseException, IOException { throws JsonParseException, IOException {
mMapElement.startLine(); mMapElement.startLine();
parseCoordSequence(jp); parseCoordSequence(jp);
} }
private void parseCoordSequence(JsonParser jp) private void parseCoordSequence(JsonParser jp)
throws JsonParseException, IOException { throws JsonParseException, IOException {
for (JsonToken t; (t = jp.nextToken()) != null;) { for (JsonToken t; (t = jp.nextToken()) != null; ) {
if (t == START_ARRAY) { if (t == START_ARRAY) {
parseCoordinate(jp); parseCoordinate(jp);
continue; continue;
} }
if (t == END_ARRAY) if (t == END_ARRAY)
break; break;
} }
} }
private void parseCoordinate(JsonParser jp) private void parseCoordinate(JsonParser jp)
throws JsonParseException, IOException { throws JsonParseException, IOException {
int pos = 0; int pos = 0;
double x = 0, y = 0; //, z = 0; double x = 0, y = 0; //, z = 0;
for (JsonToken t; (t = jp.nextToken()) != null;) { for (JsonToken t; (t = jp.nextToken()) != null; ) {
if (t == VALUE_NUMBER_FLOAT || t == VALUE_NUMBER_INT) { if (t == VALUE_NUMBER_FLOAT || t == VALUE_NUMBER_INT) {
// avoid String allocation (by getDouble...) // avoid String allocation (by getDouble...)
char[] val = jp.getTextCharacters(); char[] val = jp.getTextCharacters();
int offset = jp.getTextOffset(); int offset = jp.getTextOffset();
int length = jp.getTextLength(); int length = jp.getTextLength();
double c = ArrayUtils.parseNumber(val, offset, offset + length); double c = ArrayUtils.parseNumber(val, offset, offset + length);
if (pos == 0) if (pos == 0)
x = c; x = c;
if (pos == 1) if (pos == 1)
y = c; y = c;
//if (pos == 2) //if (pos == 2)
//z = c; //z = c;
pos++; pos++;
continue; continue;
} }
if (t == END_ARRAY) if (t == END_ARRAY)
break; break;
} }
mMapElement.addPoint((float) ((longitudeToX(x) - mTileX) * mTileScale), mMapElement.addPoint((float) ((longitudeToX(x) - mTileX) * mTileScale),
(float) ((latitudeToY(y) - mTileY) * mTileScale)); (float) ((latitudeToY(y) - mTileY) * mTileScale));
} }
private final static boolean match(JsonParser jp, char[] fieldName) private final static boolean match(JsonParser jp, char[] fieldName)
throws JsonParseException, IOException { throws JsonParseException, IOException {
int length = jp.getTextLength(); int length = jp.getTextLength();
if (length != fieldName.length) if (length != fieldName.length)
return false; return false;
char[] val = jp.getTextCharacters(); char[] val = jp.getTextCharacters();
int offset = jp.getTextOffset(); int offset = jp.getTextOffset();
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
if (fieldName[i] != val[i + offset]) if (fieldName[i] != val[i + offset])
return false; return false;
} }
return true; return true;
} }
} }

View File

@@ -16,56 +16,60 @@
*/ */
package org.oscim.tiling.source.geojson; package org.oscim.tiling.source.geojson;
import java.util.HashMap;
import java.util.Map;
import org.oscim.core.MapElement; import org.oscim.core.MapElement;
import org.oscim.core.Tag; import org.oscim.core.Tag;
import org.oscim.tiling.ITileDataSource; import org.oscim.tiling.ITileDataSource;
import org.oscim.tiling.source.UrlTileDataSource; import org.oscim.tiling.source.UrlTileDataSource;
import org.oscim.tiling.source.UrlTileSource; import org.oscim.tiling.source.UrlTileSource;
import java.util.HashMap;
import java.util.Map;
public abstract class GeoJsonTileSource extends UrlTileSource { public abstract class GeoJsonTileSource extends UrlTileSource {
public GeoJsonTileSource(String url) { public GeoJsonTileSource(String url) {
super(url, "/{Z}/{X}/{Y}.json"); super(url, "/{Z}/{X}/{Y}.json");
Map<String, String> opt = new HashMap<String, String>(); Map<String, String> opt = new HashMap<String, String>();
opt.put("Accept-Encoding", "gzip"); opt.put("Accept-Encoding", "gzip");
setHttpRequestHeaders(opt); setHttpRequestHeaders(opt);
} }
public GeoJsonTileSource(String url, int zoomMin, int zoomMax) { public GeoJsonTileSource(String url, int zoomMin, int zoomMax) {
super(url, "/{Z}/{X}/{Y}.json", zoomMin, zoomMax); super(url, "/{Z}/{X}/{Y}.json", zoomMin, zoomMax);
Map<String, String> opt = new HashMap<String, String>(); Map<String, String> opt = new HashMap<String, String>();
opt.put("Accept-Encoding", "gzip"); opt.put("Accept-Encoding", "gzip");
setHttpRequestHeaders(opt); setHttpRequestHeaders(opt);
} }
@Override @Override
public ITileDataSource getDataSource() { public ITileDataSource getDataSource() {
return new UrlTileDataSource(this, new GeoJsonTileDecoder(this), getHttpEngine()); return new UrlTileDataSource(this, new GeoJsonTileDecoder(this), getHttpEngine());
} }
public Tag getFeatureTag() { public Tag getFeatureTag() {
return null; 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) if (value == null)
return 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

@@ -16,23 +16,23 @@
*/ */
package org.oscim.tiling.source.geojson; package org.oscim.tiling.source.geojson;
import java.util.Map;
import org.oscim.core.MapElement; import org.oscim.core.MapElement;
import org.oscim.core.Tag; import org.oscim.core.Tag;
import java.util.Map;
public class OsmBuildingJsonTileSource extends GeoJsonTileSource { public class OsmBuildingJsonTileSource extends GeoJsonTileSource {
public OsmBuildingJsonTileSource() { public OsmBuildingJsonTileSource() {
super("http://tile.openstreetmap.us/vectiles-buildings"); super("http://tile.openstreetmap.us/vectiles-buildings");
} }
Tag mTagBuilding = new Tag("building", "yes"); Tag mTagBuilding = new Tag("building", "yes");
@Override @Override
public void decodeTags(MapElement mapElement, Map<String, Object> properties) { public void decodeTags(MapElement mapElement, Map<String, Object> properties) {
mapElement.tags.add(mTagBuilding); mapElement.tags.add(mTagBuilding);
} }
} }

View File

@@ -16,112 +16,112 @@
*/ */
package org.oscim.tiling.source.geojson; package org.oscim.tiling.source.geojson;
import java.util.LinkedHashMap;
import java.util.Map;
import org.oscim.core.GeometryBuffer.GeometryType; import org.oscim.core.GeometryBuffer.GeometryType;
import org.oscim.core.MapElement; import org.oscim.core.MapElement;
import org.oscim.core.Tag; import org.oscim.core.Tag;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.LinkedHashMap;
import java.util.Map;
public class OsmLanduseJsonTileSource extends GeoJsonTileSource { public class OsmLanduseJsonTileSource extends GeoJsonTileSource {
static final Logger log = LoggerFactory.getLogger(OsmLanduseJsonTileSource.class); static final Logger log = LoggerFactory.getLogger(OsmLanduseJsonTileSource.class);
public OsmLanduseJsonTileSource() { public OsmLanduseJsonTileSource() {
super("http://tile.openstreetmap.us/vectiles-land-usages"); super("http://tile.openstreetmap.us/vectiles-land-usages");
} }
private static LinkedHashMap<String, Tag> mappings = private static LinkedHashMap<String, Tag> mappings =
new LinkedHashMap<String, Tag>(); new LinkedHashMap<String, Tag>();
static void addMapping(String key, String val) { static void addMapping(String key, String val) {
mappings.put(val, new Tag(key, val)); mappings.put(val, new Tag(key, val));
} }
static { static {
addMapping("landuse", "residential"); addMapping("landuse", "residential");
addMapping("landuse", "commercial"); addMapping("landuse", "commercial");
addMapping("landuse", "retail"); addMapping("landuse", "retail");
addMapping("landuse", "railway"); addMapping("landuse", "railway");
addMapping("landuse", "grass"); addMapping("landuse", "grass");
addMapping("landuse", "meadow"); addMapping("landuse", "meadow");
addMapping("landuse", "forest"); addMapping("landuse", "forest");
addMapping("landuse", "farm"); addMapping("landuse", "farm");
addMapping("landuse", "allotments"); addMapping("landuse", "allotments");
addMapping("landuse", "cemetery"); addMapping("landuse", "cemetery");
addMapping("landuse", "farmyard"); addMapping("landuse", "farmyard");
addMapping("landuse", "farmland"); addMapping("landuse", "farmland");
addMapping("landuse", "quarry"); addMapping("landuse", "quarry");
addMapping("landuse", "military"); addMapping("landuse", "military");
addMapping("landuse", "industrial"); addMapping("landuse", "industrial");
addMapping("landuse", "greenfield"); addMapping("landuse", "greenfield");
addMapping("landuse", "village_green"); addMapping("landuse", "village_green");
addMapping("landuse", "recreation_ground"); addMapping("landuse", "recreation_ground");
addMapping("landuse", "conservation"); addMapping("landuse", "conservation");
addMapping("landuse", "landfill"); addMapping("landuse", "landfill");
addMapping("landuse", "construction"); addMapping("landuse", "construction");
addMapping("leisure", "common"); addMapping("leisure", "common");
addMapping("leisure", "park"); addMapping("leisure", "park");
addMapping("leisure", "pitch"); addMapping("leisure", "pitch");
addMapping("leisure", "garden"); addMapping("leisure", "garden");
addMapping("leisure", "sports_centre"); addMapping("leisure", "sports_centre");
addMapping("leisure", "playground"); addMapping("leisure", "playground");
addMapping("leisure", "nature_reserve"); addMapping("leisure", "nature_reserve");
addMapping("leisure", "golf_course"); addMapping("leisure", "golf_course");
addMapping("leisure", "stadium"); addMapping("leisure", "stadium");
addMapping("amenity", "hospital"); addMapping("amenity", "hospital");
addMapping("amenity", "cinema"); addMapping("amenity", "cinema");
addMapping("amenity", "school"); addMapping("amenity", "school");
addMapping("amenity", "college"); addMapping("amenity", "college");
addMapping("amenity", "university"); addMapping("amenity", "university");
addMapping("amenity", "theatre"); addMapping("amenity", "theatre");
addMapping("amenity", "library"); addMapping("amenity", "library");
addMapping("amenity", "parking"); addMapping("amenity", "parking");
addMapping("amenity", "place_of_worship"); addMapping("amenity", "place_of_worship");
addMapping("highway", "pedestrian"); addMapping("highway", "pedestrian");
addMapping("highway", "footway"); addMapping("highway", "footway");
addMapping("highway", "service"); addMapping("highway", "service");
addMapping("highway", "street"); addMapping("highway", "street");
addMapping("natural", "scrub"); addMapping("natural", "scrub");
addMapping("natural", "wood"); addMapping("natural", "wood");
mappings.put("urban area", new Tag("landuse", "urban")); mappings.put("urban area", new Tag("landuse", "urban"));
mappings.put("park or protected land", new Tag("leisure", "park")); mappings.put("park or protected land", new Tag("leisure", "park"));
} }
private final static Tag mTagArea = new Tag("area", "yes"); private final static Tag mTagArea = new Tag("area", "yes");
@Override @Override
public void decodeTags(MapElement mapElement, Map<String, Object> properties) { public void decodeTags(MapElement mapElement, Map<String, Object> properties) {
for (Map.Entry<String, Object> entry : properties.entrySet()) { for (Map.Entry<String, Object> entry : properties.entrySet()) {
String key = entry.getKey(); String key = entry.getKey();
if (!"kind".equals(key)) if (!"kind".equals(key))
continue; continue;
String value = (String) entry.getValue(); String value = (String) entry.getValue();
Tag tag = mappings.get(value); Tag tag = mappings.get(value);
if (tag == null) { if (tag == null) {
System.out.println("unmatched " + value); System.out.println("unmatched " + value);
} else { } else {
mapElement.tags.add(tag); mapElement.tags.add(tag);
} }
break; break;
} }
} }
@Override @Override
public void postGeomHook(MapElement mapElement) { public void postGeomHook(MapElement mapElement) {
//if (mapElement.type != GeometryType.POLY) { //if (mapElement.type != GeometryType.POLY) {
mapElement.type = GeometryType.POLY; mapElement.type = GeometryType.POLY;
mapElement.tags.add(mTagArea); mapElement.tags.add(mTagArea);
//} //}
} }
} }

View File

@@ -25,35 +25,34 @@ import java.util.Map;
public class OsmRoadLabelJsonTileSource extends GeoJsonTileSource { public class OsmRoadLabelJsonTileSource extends GeoJsonTileSource {
static final Logger log = LoggerFactory.getLogger(OsmRoadLabelJsonTileSource.class); static final Logger log = LoggerFactory.getLogger(OsmRoadLabelJsonTileSource.class);
public OsmRoadLabelJsonTileSource() { public OsmRoadLabelJsonTileSource() {
super("http://tile.openstreetmap.us/vectiles-skeletron"); super("http://tile.openstreetmap.us/vectiles-skeletron");
} }
@Override @Override
public void decodeTags(MapElement mapElement, Map<String, Object> properties) { public void decodeTags(MapElement mapElement, Map<String, Object> properties) {
String highway = null; String highway = null;
for (Map.Entry<String, Object> entry : properties.entrySet()) { for (Map.Entry<String, Object> entry : properties.entrySet()) {
String key = entry.getKey(); String key = entry.getKey();
Object value = entry.getValue(); Object value = entry.getValue();
//log.debug(key + " : " + String.valueOf(value)); //log.debug(key + " : " + String.valueOf(value));
if (value == null) if (value == null)
continue; continue;
if ("highway".equals(key) && value instanceof String) { if ("highway".equals(key) && value instanceof String) {
highway = (String) entry.getValue(); highway = (String) entry.getValue();
} } else if ("name".equals(key) && value instanceof String) {
else if ("name".equals(key) && value instanceof String) { mapElement.tags.add(new Tag("name", (String) value));
mapElement.tags.add(new Tag("name", (String) value)); }
} }
}
if (highway == null) if (highway == null)
return; return;
mapElement.tags.add(new Tag("highway", highway)); mapElement.tags.add(new Tag("highway", highway));
} }
} }

View File

@@ -16,83 +16,78 @@
*/ */
package org.oscim.tiling.source.geojson; package org.oscim.tiling.source.geojson;
import java.util.Map;
import org.oscim.core.MapElement; import org.oscim.core.MapElement;
import org.oscim.core.Tag; import org.oscim.core.Tag;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Map;
public class OsmRoadLineJsonTileSource extends GeoJsonTileSource { public class OsmRoadLineJsonTileSource extends GeoJsonTileSource {
static final Logger log = LoggerFactory.getLogger(OsmRoadLineJsonTileSource.class); static final Logger log = LoggerFactory.getLogger(OsmRoadLineJsonTileSource.class);
Tag mTagTunnel = new Tag("tunnel", "yes"); Tag mTagTunnel = new Tag("tunnel", "yes");
Tag mTagBridge = new Tag("bridge", "yes"); Tag mTagBridge = new Tag("bridge", "yes");
public OsmRoadLineJsonTileSource() { public OsmRoadLineJsonTileSource() {
super("http://tile.openstreetmap.us/vectiles-highroad"); super("http://tile.openstreetmap.us/vectiles-highroad");
} }
@Override @Override
public void decodeTags(MapElement mapElement, Map<String, Object> properties) { public void decodeTags(MapElement mapElement, Map<String, Object> properties) {
String highway = null; String highway = null;
boolean isLink = false; boolean isLink = false;
mapElement.layer = 5; mapElement.layer = 5;
for (Map.Entry<String, Object> entry : properties.entrySet()) { for (Map.Entry<String, Object> entry : properties.entrySet()) {
String key = entry.getKey(); String key = entry.getKey();
Object value = entry.getValue(); Object value = entry.getValue();
//log.debug(key + " : " + String.valueOf(value)); //log.debug(key + " : " + String.valueOf(value));
if (value == null) if (value == null)
continue; continue;
if ("no".equals(value)) if ("no".equals(value))
continue; continue;
if ("highway".equals(key) && value instanceof String) { if ("highway".equals(key) && value instanceof String) {
highway = (String) entry.getValue(); highway = (String) entry.getValue();
} } else if ("is_link".equals(key)) {
else if ("is_link".equals(key)) { isLink = "yes".equals(value);
isLink = "yes".equals(value); } else if ("is_tunnel".equals(key)) {
} mapElement.tags.add(mTagTunnel);
else if ("is_tunnel".equals(key)) { } else if ("is_bridge".equals(key)) {
mapElement.tags.add(mTagTunnel); mapElement.tags.add(mTagBridge);
} } else if ("sort_key".equals(key)) {
else if ("is_bridge".equals(key)) { if (value instanceof Integer)
mapElement.tags.add(mTagBridge); mapElement.layer = 5 + (Integer) value;
} } else if ("railway".equals(key) && value instanceof String) {
else if ("sort_key".equals(key)) { mapElement.tags.add(new Tag("railway", (String) value));
if (value instanceof Integer) }
mapElement.layer = 5 + (Integer) value; }
}
else if ("railway".equals(key) && value instanceof String) {
mapElement.tags.add(new Tag("railway", (String) value));
}
}
if (highway == null) if (highway == null)
return; return;
if (isLink) if (isLink)
highway += "_link"; highway += "_link";
mapElement.tags.add(new Tag("highway", highway)); mapElement.tags.add(new Tag("highway", highway));
} }
@Override @Override
public Tag rewriteTag(String key, Object value) { public Tag rewriteTag(String key, Object value) {
if ("kind".equals(key)) if ("kind".equals(key))
return null; return null;
if (value == null) if (value == null)
return 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);
} }
} }

View File

@@ -16,23 +16,23 @@
*/ */
package org.oscim.tiling.source.geojson; package org.oscim.tiling.source.geojson;
import java.util.Map;
import org.oscim.core.MapElement; import org.oscim.core.MapElement;
import org.oscim.core.Tag; import org.oscim.core.Tag;
import java.util.Map;
public class OsmWaterJsonTileSource extends GeoJsonTileSource { public class OsmWaterJsonTileSource extends GeoJsonTileSource {
public OsmWaterJsonTileSource() { public OsmWaterJsonTileSource() {
super("http://tile.openstreetmap.us/vectiles-water-areas"); super("http://tile.openstreetmap.us/vectiles-water-areas");
} }
Tag mTagWater = new Tag("natural", "water"); Tag mTagWater = new Tag("natural", "water");
@Override @Override
public void decodeTags(MapElement mapElement, Map<String, Object> properties) { public void decodeTags(MapElement mapElement, Map<String, Object> properties) {
mapElement.tags.add(mTagWater); mapElement.tags.add(mTagWater);
} }
} }

View File

@@ -1,22 +1,22 @@
package org.oscim.tiling.source.geojson; package org.oscim.tiling.source.geojson;
import java.util.Map;
import org.oscim.core.MapElement; import org.oscim.core.MapElement;
import org.oscim.core.Tag; import org.oscim.core.Tag;
import java.util.Map;
public class RiverJsonTileSource extends GeoJsonTileSource { public class RiverJsonTileSource extends GeoJsonTileSource {
public RiverJsonTileSource() { public RiverJsonTileSource() {
super("http://www.somebits.com:8001/rivers"); super("http://www.somebits.com:8001/rivers");
} }
Tag mTagWater = new Tag("waterway", "river"); Tag mTagWater = new Tag("waterway", "river");
@Override @Override
public void decodeTags(MapElement mapElement, Map<String, Object> properties) { public void decodeTags(MapElement mapElement, Map<String, Object> properties) {
mapElement.tags.add(mTagWater); mapElement.tags.add(mTagWater);
} }
} }

View File

@@ -23,36 +23,36 @@ import org.oscim.tiling.source.UrlTileSource;
public class MapnikVectorTileSource extends UrlTileSource { public class MapnikVectorTileSource extends UrlTileSource {
public MapnikVectorTileSource() { public MapnikVectorTileSource() {
super("http://d1s11ojcu7opje.cloudfront.net/dev/764e0b8d", ""); super("http://d1s11ojcu7opje.cloudfront.net/dev/764e0b8d", "");
setUrlFormatter(new TileUrlFormatter() { setUrlFormatter(new TileUrlFormatter() {
@Override @Override
public String formatTilePath(UrlTileSource tileSource, Tile tile) { public String formatTilePath(UrlTileSource tileSource, Tile tile) {
// url formatter for mapbox streets // url formatter for mapbox streets
byte[] hexTable = { byte[] hexTable = {
'0', '1', '2', '3', '0', '1', '2', '3',
'4', '5', '6', '7', '4', '5', '6', '7',
'8', '9', 'a', 'b', '8', '9', 'a', 'b',
'c', 'd', 'e', 'f' 'c', 'd', 'e', 'f'
}; };
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append('/'); sb.append('/');
sb.append(hexTable[(tile.tileX) % 16]); sb.append(hexTable[(tile.tileX) % 16]);
sb.append(hexTable[(tile.tileY) % 16]); sb.append(hexTable[(tile.tileY) % 16]);
sb.append('/'); sb.append('/');
sb.append(tile.zoomLevel); sb.append(tile.zoomLevel);
sb.append('/'); sb.append('/');
sb.append(tile.tileX); sb.append(tile.tileX);
sb.append('/'); sb.append('/');
sb.append(tile.tileY); sb.append(tile.tileY);
return sb.toString(); return sb.toString();
} }
}); });
} }
@Override @Override
public ITileDataSource getDataSource() { public ITileDataSource getDataSource() {
return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine()); return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine());
} }
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -22,16 +22,15 @@ import org.oscim.tiling.source.UrlTileSource;
/** /**
* Deprecated * Deprecated
*
*/ */
public class OSciMap1TileSource extends UrlTileSource { public class OSciMap1TileSource extends UrlTileSource {
public OSciMap1TileSource(String url) { public OSciMap1TileSource(String url) {
super(url, "/{Z}/{X}/{Y}.osmtile"); super(url, "/{Z}/{X}/{Y}.osmtile");
} }
@Override @Override
public ITileDataSource getDataSource() { public ITileDataSource getDataSource() {
return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine()); return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine());
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -16,12 +16,6 @@
*/ */
package org.oscim.tiling.source.oscimap; package org.oscim.tiling.source.oscimap;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import org.oscim.core.GeometryBuffer.GeometryType; import org.oscim.core.GeometryBuffer.GeometryType;
import org.oscim.core.MapElement; import org.oscim.core.MapElement;
import org.oscim.core.Tag; import org.oscim.core.Tag;
@@ -31,427 +25,433 @@ import org.oscim.tiling.source.PbfDecoder;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
public class TileDecoder extends PbfDecoder { public class TileDecoder extends PbfDecoder {
static final Logger log = LoggerFactory.getLogger(TileDecoder.class); static final Logger log = LoggerFactory.getLogger(TileDecoder.class);
private final static float REF_TILE_SIZE = 4096.0f; private final static float REF_TILE_SIZE = 4096.0f;
private static final int TAG_TILE_TAGS = 1; private static final int TAG_TILE_TAGS = 1;
private static final int TAG_TILE_WAYS = 2; private static final int TAG_TILE_WAYS = 2;
private static final int TAG_TILE_POLY = 3; private static final int TAG_TILE_POLY = 3;
private static final int TAG_TILE_NODES = 4; private static final int TAG_TILE_NODES = 4;
private static final int TAG_WAY_TAGS = 11; private static final int TAG_WAY_TAGS = 11;
private static final int TAG_WAY_INDEX = 12; private static final int TAG_WAY_INDEX = 12;
private static final int TAG_WAY_COORDS = 13; private static final int TAG_WAY_COORDS = 13;
private static final int TAG_WAY_LAYER = 21; private static final int TAG_WAY_LAYER = 21;
private static final int TAG_WAY_NUM_TAGS = 1; private static final int TAG_WAY_NUM_TAGS = 1;
private static final int TAG_WAY_NUM_INDICES = 2; private static final int TAG_WAY_NUM_INDICES = 2;
private static final int TAG_WAY_NUM_COORDS = 3; private static final int TAG_WAY_NUM_COORDS = 3;
private static final int TAG_NODE_TAGS = 11; private static final int TAG_NODE_TAGS = 11;
private static final int TAG_NODE_COORDS = 12; private static final int TAG_NODE_COORDS = 12;
private static final int TAG_NODE_LAYER = 21; private static final int TAG_NODE_LAYER = 21;
private static final int TAG_NODE_NUM_TAGS = 1; private static final int TAG_NODE_NUM_TAGS = 1;
private static final int TAG_NODE_NUM_COORDS = 2; private static final int TAG_NODE_NUM_COORDS = 2;
private int MAX_TILE_TAGS = 100; private int MAX_TILE_TAGS = 100;
private Tag[] curTags = new Tag[MAX_TILE_TAGS]; private Tag[] curTags = new Tag[MAX_TILE_TAGS];
private int mCurTagCnt; private int mCurTagCnt;
private ITileDataSink mSink; private ITileDataSink mSink;
private float mScale; private float mScale;
private Tile mTile; private Tile mTile;
private final MapElement mElem; private final MapElement mElem;
TileDecoder() { TileDecoder() {
mElem = new MapElement(); mElem = new MapElement();
} }
@Override @Override
public boolean decode(Tile tile, ITileDataSink sink, InputStream is) public boolean decode(Tile tile, ITileDataSink sink, InputStream is)
throws IOException { throws IOException {
setInputStream(is); setInputStream(is);
mTile = tile; mTile = tile;
mSink = sink; mSink = sink;
mScale = REF_TILE_SIZE / Tile.SIZE; mScale = REF_TILE_SIZE / Tile.SIZE;
return decode(); return decode();
} }
private static final int MAX_TAGS_CACHE = 100; private static final int MAX_TAGS_CACHE = 100;
private static Map<String, Tag> tagHash = private static Map<String, Tag> tagHash =
Collections.synchronizedMap(new LinkedHashMap<String, Tag>(MAX_TAGS_CACHE, Collections.synchronizedMap(new LinkedHashMap<String, Tag>(MAX_TAGS_CACHE,
0.75f, 0.75f,
true) { true) {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
//@Override //@Override
//protected boolean removeEldestEntry(Entry<String, Tag> e) { //protected boolean removeEldestEntry(Entry<String, Tag> e) {
//if (size() < MAX_TAGS_CACHE) //if (size() < MAX_TAGS_CACHE)
//return false; //return false;
//return true; //return true;
//} //}
}); });
private boolean decode() throws IOException { private boolean decode() throws IOException {
int val; int val;
mCurTagCnt = 0; mCurTagCnt = 0;
while (hasData() && (val = decodeVarint32()) > 0) { while (hasData() && (val = decodeVarint32()) > 0) {
// read tag and wire type // read tag and wire type
int tag = (val >> 3); int tag = (val >> 3);
switch (tag) { switch (tag) {
case TAG_TILE_TAGS: case TAG_TILE_TAGS:
decodeTileTags(); decodeTileTags();
break; break;
case TAG_TILE_WAYS: case TAG_TILE_WAYS:
decodeTileWays(false); decodeTileWays(false);
break; break;
case TAG_TILE_POLY: case TAG_TILE_POLY:
decodeTileWays(true); decodeTileWays(true);
break; break;
case TAG_TILE_NODES: case TAG_TILE_NODES:
decodeTileNodes(); decodeTileNodes();
break; break;
default: default:
log.debug("invalid type for tile: " + tag); log.debug("invalid type for tile: " + tag);
return false; return false;
} }
} }
return true; return true;
} }
private boolean decodeTileTags() throws IOException { private boolean decodeTileTags() throws IOException {
String tagString = decodeString(); String tagString = decodeString();
if (tagString == null || tagString.length() == 0) { if (tagString == null || tagString.length() == 0) {
curTags[mCurTagCnt++] = new Tag(Tag.KEY_NAME, "..."); curTags[mCurTagCnt++] = new Tag(Tag.KEY_NAME, "...");
return false; return false;
} }
Tag tag = tagHash.get(tagString); Tag tag = tagHash.get(tagString);
if (tag == null) { if (tag == null) {
if (tagString.startsWith(Tag.KEY_NAME)) if (tagString.startsWith(Tag.KEY_NAME))
tag = new Tag(Tag.KEY_NAME, tagString.substring(5), false); tag = new Tag(Tag.KEY_NAME, tagString.substring(5), false);
else else
tag = Tag.parse(tagString); tag = Tag.parse(tagString);
if (tag != null) if (tag != null)
tagHash.put(tagString, tag); tagHash.put(tagString, tag);
} }
if (mCurTagCnt >= MAX_TILE_TAGS) { if (mCurTagCnt >= MAX_TILE_TAGS) {
MAX_TILE_TAGS = mCurTagCnt + 10; MAX_TILE_TAGS = mCurTagCnt + 10;
Tag[] tmp = new Tag[MAX_TILE_TAGS]; Tag[] tmp = new Tag[MAX_TILE_TAGS];
System.arraycopy(curTags, 0, tmp, 0, mCurTagCnt); System.arraycopy(curTags, 0, tmp, 0, mCurTagCnt);
curTags = tmp; curTags = tmp;
} }
curTags[mCurTagCnt++] = tag; curTags[mCurTagCnt++] = tag;
return true; return true;
} }
private boolean decodeTileWays(boolean polygon) throws IOException { private boolean decodeTileWays(boolean polygon) throws IOException {
int bytes = decodeVarint32(); int bytes = decodeVarint32();
int end = position() + bytes; int end = position() + bytes;
int indexCnt = 0; int indexCnt = 0;
int tagCnt = 0; int tagCnt = 0;
int coordCnt = 0; int coordCnt = 0;
int layer = 5; int layer = 5;
boolean fail = false; boolean fail = false;
while (position() < end) { while (position() < end) {
// read tag and wire type // read tag and wire type
int val = decodeVarint32(); int val = decodeVarint32();
if (val == 0) if (val == 0)
break; break;
int tag = (val >> 3); int tag = (val >> 3);
switch (tag) { switch (tag) {
case TAG_WAY_TAGS: case TAG_WAY_TAGS:
if (!decodeWayTags(tagCnt)) if (!decodeWayTags(tagCnt))
return false; return false;
break; break;
case TAG_WAY_INDEX: case TAG_WAY_INDEX:
decodeWayIndices(indexCnt); decodeWayIndices(indexCnt);
break; break;
case TAG_WAY_COORDS: case TAG_WAY_COORDS:
if (coordCnt == 0) { if (coordCnt == 0) {
log.debug(mTile + " no coordinates"); log.debug(mTile + " no coordinates");
} }
mElem.ensurePointSize(coordCnt, false); mElem.ensurePointSize(coordCnt, false);
int cnt = decodeInterleavedPoints(mElem.points, mScale); int cnt = decodeInterleavedPoints(mElem.points, mScale);
if (cnt != coordCnt) { if (cnt != coordCnt) {
log.debug(mTile + " wrong number of coordintes " log.debug(mTile + " wrong number of coordintes "
+ coordCnt + "/" + cnt); + coordCnt + "/" + cnt);
fail = true; fail = true;
} }
break; break;
case TAG_WAY_LAYER: case TAG_WAY_LAYER:
layer = decodeVarint32(); layer = decodeVarint32();
break; break;
case TAG_WAY_NUM_TAGS: case TAG_WAY_NUM_TAGS:
tagCnt = decodeVarint32(); tagCnt = decodeVarint32();
break; break;
case TAG_WAY_NUM_INDICES: case TAG_WAY_NUM_INDICES:
indexCnt = decodeVarint32(); indexCnt = decodeVarint32();
break; break;
case TAG_WAY_NUM_COORDS: case TAG_WAY_NUM_COORDS:
coordCnt = decodeVarint32(); coordCnt = decodeVarint32();
break; break;
default: default:
log.debug("X invalid type for way: " + tag); log.debug("X invalid type for way: " + tag);
} }
} }
if (fail || indexCnt == 0 || tagCnt == 0) { if (fail || indexCnt == 0 || tagCnt == 0) {
log.debug("failed reading way: bytes:" + bytes + " index:" log.debug("failed reading way: bytes:" + bytes + " index:"
//+ (tags != null ? tags.toString() : "...") + " " //+ (tags != null ? tags.toString() : "...") + " "
+ indexCnt + " " + coordCnt + " " + tagCnt); + indexCnt + " " + coordCnt + " " + tagCnt);
return false; return false;
} }
// FIXME, remove all tiles from cache then remove this below // FIXME, remove all tiles from cache then remove this below
//if (layer == 0) //if (layer == 0)
// layer = 5; // layer = 5;
mElem.type = polygon ? GeometryType.POLY : GeometryType.LINE; mElem.type = polygon ? GeometryType.POLY : GeometryType.LINE;
mElem.setLayer(layer); mElem.setLayer(layer);
mSink.process(mElem); mSink.process(mElem);
return true; return true;
} }
private boolean decodeTileNodes() throws IOException { private boolean decodeTileNodes() throws IOException {
int bytes = decodeVarint32(); int bytes = decodeVarint32();
int end = position() + bytes; int end = position() + bytes;
int tagCnt = 0; int tagCnt = 0;
int coordCnt = 0; int coordCnt = 0;
byte layer = 0; byte layer = 0;
while (position() < end) { while (position() < end) {
// read tag and wire type // read tag and wire type
int val = decodeVarint32(); int val = decodeVarint32();
if (val == 0) if (val == 0)
break; break;
int tag = (val >> 3); int tag = (val >> 3);
switch (tag) { switch (tag) {
case TAG_NODE_TAGS: case TAG_NODE_TAGS:
if (!decodeWayTags(tagCnt)) if (!decodeWayTags(tagCnt))
return false; return false;
break; break;
case TAG_NODE_COORDS: case TAG_NODE_COORDS:
int cnt = decodeNodeCoordinates(coordCnt, layer); int cnt = decodeNodeCoordinates(coordCnt, layer);
if (cnt != coordCnt) { if (cnt != coordCnt) {
log.debug("X wrong number of coordintes"); log.debug("X wrong number of coordintes");
return false; return false;
} }
break; break;
case TAG_NODE_LAYER: case TAG_NODE_LAYER:
layer = (byte) decodeVarint32(); layer = (byte) decodeVarint32();
break; break;
case TAG_NODE_NUM_TAGS: case TAG_NODE_NUM_TAGS:
tagCnt = decodeVarint32(); tagCnt = decodeVarint32();
break; break;
case TAG_NODE_NUM_COORDS: case TAG_NODE_NUM_COORDS:
coordCnt = decodeVarint32(); coordCnt = decodeVarint32();
break; break;
default: default:
log.debug("X invalid type for node: " + tag); log.debug("X invalid type for node: " + tag);
} }
} }
return true; return true;
} }
private int decodeNodeCoordinates(int numNodes, byte layer) private int decodeNodeCoordinates(int numNodes, byte layer)
throws IOException { throws IOException {
int bytes = decodeVarint32(); int bytes = decodeVarint32();
fillBuffer(bytes); fillBuffer(bytes);
int cnt = 0; int cnt = 0;
int end = position() + bytes; int end = position() + bytes;
// read repeated sint32 // read repeated sint32
int lastX = 0; int lastX = 0;
int lastY = 0; int lastY = 0;
float[] coords = mElem.ensurePointSize(numNodes, false); float[] coords = mElem.ensurePointSize(numNodes, false);
while (position() < end && cnt < numNodes) { while (position() < end && cnt < numNodes) {
int lon = deZigZag(decodeVarint32()); int lon = deZigZag(decodeVarint32());
int lat = deZigZag(decodeVarint32()); int lat = deZigZag(decodeVarint32());
lastX = lon + lastX; lastX = lon + lastX;
lastY = lat + lastY; lastY = lat + lastY;
coords[cnt++] = lastX / mScale; coords[cnt++] = lastX / mScale;
coords[cnt++] = Tile.SIZE - lastY / mScale; coords[cnt++] = Tile.SIZE - lastY / mScale;
} }
mElem.index[0] = (short) numNodes; mElem.index[0] = (short) numNodes;
mElem.type = GeometryType.POINT; mElem.type = GeometryType.POINT;
mElem.setLayer(layer); mElem.setLayer(layer);
mSink.process(mElem); mSink.process(mElem);
return cnt; return cnt;
} }
private boolean decodeWayTags(int tagCnt) throws IOException { private boolean decodeWayTags(int tagCnt) throws IOException {
int bytes = decodeVarint32(); int bytes = decodeVarint32();
mElem.tags.clear(); mElem.tags.clear();
int cnt = 0; int cnt = 0;
int end = position() + bytes; int end = position() + bytes;
int max = mCurTagCnt; int max = mCurTagCnt;
for (; position() < end; cnt++) { for (; position() < end; cnt++) {
int tagNum = decodeVarint32(); int tagNum = decodeVarint32();
if (tagNum < 0 || cnt == tagCnt) { if (tagNum < 0 || cnt == tagCnt) {
log.debug("NULL TAG: " + mTile log.debug("NULL TAG: " + mTile
+ " invalid tag:" + tagNum + " invalid tag:" + tagNum
+ " " + tagCnt + "/" + cnt); + " " + tagCnt + "/" + cnt);
continue; continue;
} }
if (tagNum < Tags.MAX) { if (tagNum < Tags.MAX) {
mElem.tags.add(Tags.tags[tagNum]); mElem.tags.add(Tags.tags[tagNum]);
continue; continue;
} }
tagNum -= Tags.LIMIT; tagNum -= Tags.LIMIT;
if (tagNum >= 0 && tagNum < max) { if (tagNum >= 0 && tagNum < max) {
mElem.tags.add(curTags[tagNum]); mElem.tags.add(curTags[tagNum]);
} else { } else {
log.debug("NULL TAG: " + mTile log.debug("NULL TAG: " + mTile
+ " could find tag:" + " could find tag:"
+ tagNum + " " + tagCnt + tagNum + " " + tagCnt
+ "/" + cnt); + "/" + cnt);
} }
} }
if (tagCnt != cnt) { if (tagCnt != cnt) {
log.debug("NULL TAG: " + mTile); log.debug("NULL TAG: " + mTile);
return false; return false;
} }
return true; return true;
} }
private int decodeWayIndices(int indexCnt) throws IOException { private int decodeWayIndices(int indexCnt) throws IOException {
mElem.ensureIndexSize(indexCnt, false); mElem.ensureIndexSize(indexCnt, false);
decodeVarintArray(indexCnt, mElem.index); decodeVarintArray(indexCnt, mElem.index);
int[] index = mElem.index; int[] index = mElem.index;
int coordCnt = 0; int coordCnt = 0;
for (int i = 0; i < indexCnt; i++) { for (int i = 0; i < indexCnt; i++) {
coordCnt += index[i]; coordCnt += index[i];
index[i] *= 2; index[i] *= 2;
} }
// set end marker // set end marker
if (indexCnt < index.length) if (indexCnt < index.length)
index[indexCnt] = -1; index[indexCnt] = -1;
return coordCnt; return coordCnt;
} }
//@Override //@Override
protected int decodeInterleavedPoints(float[] coords, float scale) protected int decodeInterleavedPoints(float[] coords, float scale)
throws IOException { throws IOException {
int bytes = decodeVarint32(); int bytes = decodeVarint32();
fillBuffer(bytes); fillBuffer(bytes);
int cnt = 0; int cnt = 0;
int lastX = 0; int lastX = 0;
int lastY = 0; int lastY = 0;
boolean even = true; boolean even = true;
byte[] buf = buffer; byte[] buf = buffer;
int pos = bufferPos; int pos = bufferPos;
int end = pos + bytes; int end = pos + bytes;
int val; int val;
while (pos < end) { while (pos < end) {
if (buf[pos] >= 0) { if (buf[pos] >= 0) {
val = buf[pos++]; val = buf[pos++];
} else if (buf[pos + 1] >= 0) { } else if (buf[pos + 1] >= 0) {
val = (buf[pos++] & 0x7f) val = (buf[pos++] & 0x7f)
| buf[pos++] << 7; | buf[pos++] << 7;
} else if (buf[pos + 2] >= 0) { } else if (buf[pos + 2] >= 0) {
val = (buf[pos++] & 0x7f) val = (buf[pos++] & 0x7f)
| (buf[pos++] & 0x7f) << 7 | (buf[pos++] & 0x7f) << 7
| (buf[pos++]) << 14; | (buf[pos++]) << 14;
} else if (buf[pos + 3] >= 0) { } else if (buf[pos + 3] >= 0) {
val = (buf[pos++] & 0x7f) val = (buf[pos++] & 0x7f)
| (buf[pos++] & 0x7f) << 7 | (buf[pos++] & 0x7f) << 7
| (buf[pos++] & 0x7f) << 14 | (buf[pos++] & 0x7f) << 14
| (buf[pos++]) << 21; | (buf[pos++]) << 21;
} else { } else {
val = (buf[pos++] & 0x7f) val = (buf[pos++] & 0x7f)
| (buf[pos++] & 0x7f) << 7 | (buf[pos++] & 0x7f) << 7
| (buf[pos++] & 0x7f) << 14 | (buf[pos++] & 0x7f) << 14
| (buf[pos++] & 0x7f) << 21 | (buf[pos++] & 0x7f) << 21
| (buf[pos]) << 28; | (buf[pos]) << 28;
if (buf[pos++] < 0) if (buf[pos++] < 0)
throw INVALID_VARINT; throw INVALID_VARINT;
} }
// zigzag decoding // zigzag decoding
int s = ((val >>> 1) ^ -(val & 1)); int s = ((val >>> 1) ^ -(val & 1));
if (even) { if (even) {
lastX = lastX + s; lastX = lastX + s;
coords[cnt++] = lastX / scale; coords[cnt++] = lastX / scale;
even = false; even = false;
} else { } else {
lastY = lastY + s; lastY = lastY + s;
coords[cnt++] = Tile.SIZE - lastY / scale; coords[cnt++] = Tile.SIZE - lastY / scale;
even = true; even = true;
} }
} }
if (pos != bufferPos + bytes) if (pos != bufferPos + bytes)
throw INVALID_PACKED_SIZE; throw INVALID_PACKED_SIZE;
bufferPos = pos; bufferPos = pos;
// return number of points read // return number of points read
return cnt; return cnt;
} }
} }

View File

@@ -16,10 +16,6 @@
*/ */
package org.oscim.tiling.source.oscimap2; package org.oscim.tiling.source.oscimap2;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import org.oscim.core.GeometryBuffer.GeometryType; import org.oscim.core.GeometryBuffer.GeometryType;
import org.oscim.core.MapElement; import org.oscim.core.MapElement;
import org.oscim.core.Tag; import org.oscim.core.Tag;
@@ -33,295 +29,299 @@ import org.oscim.tiling.source.UrlTileSource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
public class OSciMap2TileSource extends UrlTileSource { public class OSciMap2TileSource extends UrlTileSource {
public OSciMap2TileSource(String url) { public OSciMap2TileSource(String url) {
super(url, "/{Z}/{X}/{Y}.osmtile"); super(url, "/{Z}/{X}/{Y}.osmtile");
} }
@Override @Override
public ITileDataSource getDataSource() { public ITileDataSource getDataSource() {
return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine()); return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine());
} }
static class TileDecoder extends PbfDecoder { static class TileDecoder extends PbfDecoder {
static final Logger log = LoggerFactory.getLogger(TileDecoder.class); static final Logger log = LoggerFactory.getLogger(TileDecoder.class);
private static final int TAG_TILE_NUM_TAGS = 1; private static final int TAG_TILE_NUM_TAGS = 1;
private static final int TAG_TILE_TAG_KEYS = 2; private static final int TAG_TILE_TAG_KEYS = 2;
private static final int TAG_TILE_TAG_VALUES = 3; private static final int TAG_TILE_TAG_VALUES = 3;
private static final int TAG_TILE_LINE = 11; private static final int TAG_TILE_LINE = 11;
private static final int TAG_TILE_POLY = 12; private static final int TAG_TILE_POLY = 12;
private static final int TAG_TILE_POINT = 13; private static final int TAG_TILE_POINT = 13;
// private static final int TAG_TILE_LABEL = 21; // private static final int TAG_TILE_LABEL = 21;
// private static final int TAG_TILE_WATER = 31; // private static final int TAG_TILE_WATER = 31;
private static final int TAG_ELEM_NUM_INDICES = 1; private static final int TAG_ELEM_NUM_INDICES = 1;
private static final int TAG_ELEM_TAGS = 11; private static final int TAG_ELEM_TAGS = 11;
private static final int TAG_ELEM_INDEX = 12; private static final int TAG_ELEM_INDEX = 12;
private static final int TAG_ELEM_COORDS = 13; private static final int TAG_ELEM_COORDS = 13;
private static final int TAG_ELEM_LAYER = 21; private static final int TAG_ELEM_LAYER = 21;
private static final int TAG_ELEM_HEIGHT = 31; private static final int TAG_ELEM_HEIGHT = 31;
private static final int TAG_ELEM_MIN_HEIGHT = 32; private static final int TAG_ELEM_MIN_HEIGHT = 32;
private static final int TAG_ELEM_PRIORITY = 41; private static final int TAG_ELEM_PRIORITY = 41;
private int[] mSArray; private int[] mSArray;
private final TagSet mTileTags; private final TagSet mTileTags;
private final MapElement mElem; private final MapElement mElem;
private Tile mTile; private Tile mTile;
private ITileDataSink mMapDataSink; private ITileDataSink mMapDataSink;
// scale coordinates to tile size // scale coordinates to tile size
private final static float REF_TILE_SIZE = 4096.0f; private final static float REF_TILE_SIZE = 4096.0f;
private float mScale; private float mScale;
TileDecoder() { TileDecoder() {
mElem = new MapElement(); mElem = new MapElement();
mTileTags = new TagSet(20); mTileTags = new TagSet(20);
// temp array for decoding shorts // temp array for decoding shorts
mSArray = new int[100]; mSArray = new int[100];
} }
@Override @Override
public boolean decode(Tile tile, ITileDataSink sink, InputStream is) public boolean decode(Tile tile, ITileDataSink sink, InputStream is)
throws IOException { throws IOException {
readUnsignedInt(is, buffer); readUnsignedInt(is, buffer);
setInputStream(is); setInputStream(is);
mTile = tile; mTile = tile;
mMapDataSink = sink; mMapDataSink = sink;
mScale = REF_TILE_SIZE / Tile.SIZE; mScale = REF_TILE_SIZE / Tile.SIZE;
mTileTags.clear(); mTileTags.clear();
int val; int val;
int numTags = 0; int numTags = 0;
while (hasData() && (val = decodeVarint32()) > 0) { while (hasData() && (val = decodeVarint32()) > 0) {
// read tag and wire type // read tag and wire type
int tag = (val >> 3); int tag = (val >> 3);
switch (tag) { switch (tag) {
case TAG_TILE_NUM_TAGS: case TAG_TILE_NUM_TAGS:
numTags = decodeVarint32(); numTags = decodeVarint32();
break; break;
case TAG_TILE_TAG_KEYS: case TAG_TILE_TAG_KEYS:
int len = numTags; int len = numTags;
if (mSArray.length < len) if (mSArray.length < len)
mSArray = new int[len]; mSArray = new int[len];
decodeVarintArray(numTags, mSArray); decodeVarintArray(numTags, mSArray);
break; break;
case TAG_TILE_TAG_VALUES: case TAG_TILE_TAG_VALUES:
// this wastes one byte, as there is no packed string... // this wastes one byte, as there is no packed string...
decodeTileTags(); decodeTileTags();
break; break;
case TAG_TILE_LINE: case TAG_TILE_LINE:
case TAG_TILE_POLY: case TAG_TILE_POLY:
case TAG_TILE_POINT: case TAG_TILE_POINT:
decodeTileElement(tag); decodeTileElement(tag);
break; break;
default: default:
log.debug(mTile + " invalid type for tile: " + tag); log.debug(mTile + " invalid type for tile: " + tag);
return false; return false;
} }
} }
return true; return true;
} }
private boolean decodeTileTags() throws IOException { private boolean decodeTileTags() throws IOException {
String tagString = decodeString(); String tagString = decodeString();
int curTag = mTileTags.numTags; int curTag = mTileTags.numTags;
String key = Tags.keys[mSArray[curTag]]; String key = Tags.keys[mSArray[curTag]];
Tag tag; Tag tag;
if (key == Tag.KEY_NAME) if (key == Tag.KEY_NAME)
tag = new Tag(key, tagString, false); tag = new Tag(key, tagString, false);
else else
tag = new Tag(key, tagString, true); tag = new Tag(key, tagString, true);
if (debug) if (debug)
log.debug(mTile + " add tag: " + curTag + " " + tag); log.debug(mTile + " add tag: " + curTag + " " + tag);
mTileTags.add(tag); mTileTags.add(tag);
return true; return true;
} }
private int decodeWayIndices(int indexCnt) throws IOException { private int decodeWayIndices(int indexCnt) throws IOException {
mElem.ensureIndexSize(indexCnt, false); mElem.ensureIndexSize(indexCnt, false);
decodeVarintArray(indexCnt, mElem.index); decodeVarintArray(indexCnt, mElem.index);
int[] index = mElem.index; int[] index = mElem.index;
int coordCnt = 0; int coordCnt = 0;
for (int i = 0; i < indexCnt; i++) { for (int i = 0; i < indexCnt; i++) {
coordCnt += index[i]; coordCnt += index[i];
index[i] *= 2; index[i] *= 2;
} }
// set end marker // set end marker
if (indexCnt < index.length) if (indexCnt < index.length)
index[indexCnt] = -1; index[indexCnt] = -1;
return coordCnt; return coordCnt;
} }
private boolean decodeTileElement(int type) throws IOException { private boolean decodeTileElement(int type) throws IOException {
int bytes = decodeVarint32(); int bytes = decodeVarint32();
short[] index = null; short[] index = null;
int end = position() + bytes; int end = position() + bytes;
int indexCnt = 1; int indexCnt = 1;
boolean fail = false; boolean fail = false;
int coordCnt = 0; int coordCnt = 0;
if (type == TAG_TILE_POINT) { if (type == TAG_TILE_POINT) {
coordCnt = 1; coordCnt = 1;
mElem.index[0] = 2; mElem.index[0] = 2;
} }
mElem.layer = 5; mElem.layer = 5;
//mElem.height = 0; //mElem.height = 0;
//mElem.minHeight = 0; //mElem.minHeight = 0;
while (position() < end) { while (position() < end) {
// read tag and wire type // read tag and wire type
int val = decodeVarint32(); int val = decodeVarint32();
if (val == 0) if (val == 0)
break; break;
int tag = (val >> 3); int tag = (val >> 3);
switch (tag) { switch (tag) {
case TAG_ELEM_TAGS: case TAG_ELEM_TAGS:
if (!decodeElementTags()) if (!decodeElementTags())
return false; return false;
break; break;
case TAG_ELEM_NUM_INDICES: case TAG_ELEM_NUM_INDICES:
indexCnt = decodeVarint32(); indexCnt = decodeVarint32();
break; break;
case TAG_ELEM_INDEX: case TAG_ELEM_INDEX:
coordCnt = decodeWayIndices(indexCnt); coordCnt = decodeWayIndices(indexCnt);
break; break;
case TAG_ELEM_COORDS: case TAG_ELEM_COORDS:
if (coordCnt == 0) { if (coordCnt == 0) {
log.debug(mTile + " no coordinates"); log.debug(mTile + " no coordinates");
} }
mElem.ensurePointSize(coordCnt, false); mElem.ensurePointSize(coordCnt, false);
int cnt = decodeInterleavedPoints(mElem, mScale); int cnt = decodeInterleavedPoints(mElem, mScale);
if (cnt != coordCnt) { if (cnt != coordCnt) {
log.debug(mTile + " wrong number of coordintes"); log.debug(mTile + " wrong number of coordintes");
fail = true; fail = true;
} }
break; break;
case TAG_ELEM_LAYER: case TAG_ELEM_LAYER:
mElem.layer = decodeVarint32(); mElem.layer = decodeVarint32();
break; break;
case TAG_ELEM_HEIGHT: case TAG_ELEM_HEIGHT:
//mElem.height = //mElem.height =
decodeVarint32(); decodeVarint32();
break; break;
case TAG_ELEM_MIN_HEIGHT: case TAG_ELEM_MIN_HEIGHT:
//mElem.minHeight = //mElem.minHeight =
decodeVarint32(); decodeVarint32();
break; break;
case TAG_ELEM_PRIORITY: case TAG_ELEM_PRIORITY:
//mElem.priority = //mElem.priority =
decodeVarint32(); decodeVarint32();
break; break;
default: default:
log.debug(mTile + " invalid type for way: " + tag); log.debug(mTile + " invalid type for way: " + tag);
} }
} }
if (fail || indexCnt == 0) { if (fail || indexCnt == 0) {
log.debug(mTile + " failed reading way: bytes:" + bytes + " index:" log.debug(mTile + " failed reading way: bytes:" + bytes + " index:"
+ (Arrays.toString(index)) + " tag:" + (Arrays.toString(index)) + " tag:"
+ (mElem.tags.numTags > 0 ? Arrays.deepToString(mElem.tags.tags) : "null") + (mElem.tags.numTags > 0 ? Arrays.deepToString(mElem.tags.tags) : "null")
+ " " + indexCnt + " " + coordCnt); + " " + indexCnt + " " + coordCnt);
return false; return false;
} }
switch (type) { switch (type) {
case TAG_TILE_LINE: case TAG_TILE_LINE:
mElem.type = GeometryType.LINE; mElem.type = GeometryType.LINE;
break; break;
case TAG_TILE_POLY: case TAG_TILE_POLY:
mElem.type = GeometryType.POLY; mElem.type = GeometryType.POLY;
break; break;
case TAG_TILE_POINT: case TAG_TILE_POINT:
mElem.type = GeometryType.POINT; mElem.type = GeometryType.POINT;
break; break;
} }
mMapDataSink.process(mElem); mMapDataSink.process(mElem);
return true; return true;
} }
private boolean decodeElementTags() throws IOException { private boolean decodeElementTags() throws IOException {
int bytes = decodeVarint32(); int bytes = decodeVarint32();
mElem.tags.clear(); mElem.tags.clear();
int cnt = 0; int cnt = 0;
int end = position() + bytes; int end = position() + bytes;
int max = mTileTags.numTags - 1; int max = mTileTags.numTags - 1;
for (; position() < end; cnt++) { for (; position() < end; cnt++) {
int tagNum = decodeVarint32(); int tagNum = decodeVarint32();
if (tagNum < 0) { if (tagNum < 0) {
log.debug("NULL TAG: " + mTile log.debug("NULL TAG: " + mTile
+ " invalid tag:" + " invalid tag:"
+ tagNum + " " + cnt); + tagNum + " " + cnt);
return false; return false;
} }
if (tagNum < Tags.MAX) { if (tagNum < Tags.MAX) {
mElem.tags.add(Tags.tags[tagNum]); mElem.tags.add(Tags.tags[tagNum]);
continue; continue;
} }
tagNum -= Tags.LIMIT; tagNum -= Tags.LIMIT;
if (tagNum < 0 || tagNum > max) { if (tagNum < 0 || tagNum > max) {
log.debug("NULL TAG: " + mTile log.debug("NULL TAG: " + mTile
+ " could not find tag:" + " could not find tag:"
+ tagNum + " " + cnt); + tagNum + " " + cnt);
return false; return false;
} }
mElem.tags.add(mTileTags.tags[tagNum]); mElem.tags.add(mTileTags.tags[tagNum]);
} }
if (cnt == 0) { if (cnt == 0) {
log.debug("got no TAG!"); log.debug("got no TAG!");
return false; return false;
} }
return true; return true;
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -5,362 +5,376 @@ import java.util.ArrayList;
/** /**
* Triangulates a polygon into triangles - duh. Doesn't handle * Triangulates a polygon into triangles - duh. Doesn't handle
* holes in polys * holes in polys
* *
* @author Public Source from FlipCode * @author Public Source from FlipCode
*/ */
public class Triangulator { public class Triangulator {
/** The accepted error value */ /**
private static final float EPSILON = 0.0000000001f; * The accepted error value
/** The list of points to be triangulated */ */
private final PointList poly = new PointList(); private static final float EPSILON = 0.0000000001f;
/** The list of points describing the triangles */ /**
private final PointList tris = new PointList(); * The list of points to be triangulated
/** True if we've tried to triangulate */ */
private boolean tried; private final PointList poly = new PointList();
/**
* The list of points describing the triangles
*/
private final PointList tris = new PointList();
/**
* True if we've tried to triangulate
*/
private boolean tried;
/** /**
* Create a new triangulator * Create a new triangulator
*/ */
public Triangulator() { public Triangulator() {
} }
/** /**
* Add a point describing the polygon to be triangulated * Add a point describing the polygon to be triangulated
* *
* @param x The x coordinate of the point * @param x The x coordinate of the point
* @param y the y coordinate of the point * @param y the y coordinate of the point
*/ */
public void addPolyPoint(float x, float y) { public void addPolyPoint(float x, float y) {
poly.add(new Point(x, y)); poly.add(new Point(x, y));
} }
/** /**
* Cause the triangulator to split the polygon * Cause the triangulator to split the polygon
* *
* @return True if we managed the task * @return True if we managed the task
*/ */
public boolean triangulate() { public boolean triangulate() {
tried = true; tried = true;
boolean worked = process(poly, tris); boolean worked = process(poly, tris);
return worked; return worked;
} }
/** /**
* Get a count of the number of triangles produced * Get a count of the number of triangles produced
* *
* @return The number of triangles produced * @return The number of triangles produced
*/ */
public int getTriangleCount() { public int getTriangleCount() {
if (!tried) { if (!tried) {
throw new RuntimeException("Call triangulate() before accessing triangles"); throw new RuntimeException("Call triangulate() before accessing triangles");
} }
return tris.size() / 3; return tris.size() / 3;
} }
/** /**
* Get a point on a specified generated triangle * Get a point on a specified generated triangle
* *
* @param tri The index of the triangle to interegate * @param tri The index of the triangle to interegate
* @param i The index of the point within the triangle to retrieve * @param i The index of the point within the triangle to retrieve
* (0 - 2) * (0 - 2)
* @return The x,y coordinate pair for the point * @return The x,y coordinate pair for the point
*/ */
public float[] getTrianglePoint(int tri, int i) { public float[] getTrianglePoint(int tri, int i) {
if (!tried) { if (!tried) {
throw new RuntimeException("Call triangulate() before accessing triangles"); throw new RuntimeException("Call triangulate() before accessing triangles");
} }
return tris.get((tri * 3) + i).toArray(); return tris.get((tri * 3) + i).toArray();
} }
/** /**
* Find the area of a polygon defined by the series of points * Find the area of a polygon defined by the series of points
* in the list * in the list
* *
* @param contour The list of points defined the contour of the polygon * @param contour The list of points defined the contour of the polygon
* (Vector2f) * (Vector2f)
* @return The area of the polygon defined * @return The area of the polygon defined
*/ */
private static float area(PointList contour) { private static float area(PointList contour) {
int n = contour.size(); int n = contour.size();
float A = 0.0f; float A = 0.0f;
for (int p = n - 1, q = 0; q < n; p = q++) { for (int p = n - 1, q = 0; q < n; p = q++) {
Point contourP = contour.get(p); Point contourP = contour.get(p);
Point contourQ = contour.get(q); Point contourQ = contour.get(q);
A += contourP.getX() * contourQ.getY() - contourQ.getX() A += contourP.getX() * contourQ.getY() - contourQ.getX()
* contourP.getY(); * contourP.getY();
} }
return A * 0.5f; return A * 0.5f;
} }
/** /**
* Check if the point P is inside the triangle defined by * Check if the point P is inside the triangle defined by
* the points A,B,C * the points A,B,C
* *
* @param Ax Point A x-coordinate * @param Ax Point A x-coordinate
* @param Ay Point A y-coordinate * @param Ay Point A y-coordinate
* @param Bx Point B x-coordinate * @param Bx Point B x-coordinate
* @param By Point B y-coordinate * @param By Point B y-coordinate
* @param Cx Point C x-coordinate * @param Cx Point C x-coordinate
* @param Cy Point C y-coordinate * @param Cy Point C y-coordinate
* @param Px Point P x-coordinate * @param Px Point P x-coordinate
* @param Py Point P y-coordinate * @param Py Point P y-coordinate
* @return True if the point specified is within the triangle * @return True if the point specified is within the triangle
*/ */
private static boolean insideTriangle(float Ax, float Ay, float Bx, private static boolean insideTriangle(float Ax, float Ay, float Bx,
float By, float Cx, float Cy, float Px, float Py) { float By, float Cx, float Cy, float Px, float Py) {
float ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy; float ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy;
float cCROSSap, bCROSScp, aCROSSbp; float cCROSSap, bCROSScp, aCROSSbp;
ax = Cx - Bx; ax = Cx - Bx;
ay = Cy - By; ay = Cy - By;
bx = Ax - Cx; bx = Ax - Cx;
by = Ay - Cy; by = Ay - Cy;
cx = Bx - Ax; cx = Bx - Ax;
cy = By - Ay; cy = By - Ay;
apx = Px - Ax; apx = Px - Ax;
apy = Py - Ay; apy = Py - Ay;
bpx = Px - Bx; bpx = Px - Bx;
bpy = Py - By; bpy = Py - By;
cpx = Px - Cx; cpx = Px - Cx;
cpy = Py - Cy; cpy = Py - Cy;
aCROSSbp = ax * bpy - ay * bpx; aCROSSbp = ax * bpy - ay * bpx;
cCROSSap = cx * apy - cy * apx; cCROSSap = cx * apy - cy * apx;
bCROSScp = bx * cpy - by * cpx; bCROSScp = bx * cpy - by * cpx;
return ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f)); return ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f));
} }
/** /**
* Cut a the contour and add a triangle into V to describe the * Cut a the contour and add a triangle into V to describe the
* location of the cut * location of the cut
* *
* @param contour The list of points defining the polygon * @param contour The list of points defining the polygon
* @param u The index of the first point * @param u The index of the first point
* @param v The index of the second point * @param v The index of the second point
* @param w The index of the third point * @param w The index of the third point
* @param n ? * @param n ?
* @param V The array to populate with indicies of triangles * @param V The array to populate with indicies of triangles
* @return True if a triangle was found * @return True if a triangle was found
*/ */
private static boolean snip(PointList contour, int u, int v, int w, int n, private static boolean snip(PointList contour, int u, int v, int w, int n,
int[] V) { int[] V) {
int p; int p;
float Ax, Ay, Bx, By, Cx, Cy, Px, Py; float Ax, Ay, Bx, By, Cx, Cy, Px, Py;
Ax = contour.get(V[u]).getX(); Ax = contour.get(V[u]).getX();
Ay = contour.get(V[u]).getY(); Ay = contour.get(V[u]).getY();
Bx = contour.get(V[v]).getX(); Bx = contour.get(V[v]).getX();
By = contour.get(V[v]).getY(); By = contour.get(V[v]).getY();
Cx = contour.get(V[w]).getX(); Cx = contour.get(V[w]).getX();
Cy = contour.get(V[w]).getY(); Cy = contour.get(V[w]).getY();
if (EPSILON > (((Bx - Ax) * (Cy - Ay)) - ((By - Ay) * (Cx - Ax)))) { if (EPSILON > (((Bx - Ax) * (Cy - Ay)) - ((By - Ay) * (Cx - Ax)))) {
return false; return false;
} }
for (p = 0; p < n; p++) { for (p = 0; p < n; p++) {
if ((p == u) || (p == v) || (p == w)) { if ((p == u) || (p == v) || (p == w)) {
continue; continue;
} }
Px = contour.get(V[p]).getX(); Px = contour.get(V[p]).getX();
Py = contour.get(V[p]).getY(); Py = contour.get(V[p]).getY();
if (insideTriangle(Ax, Ay, Bx, By, Cx, Cy, Px, Py)) { if (insideTriangle(Ax, Ay, Bx, By, Cx, Cy, Px, Py)) {
return false; return false;
} }
} }
return true; return true;
} }
/** /**
* Process a list of points defining a polygon * Process a list of points defining a polygon
* *
* @param contour The list of points describing the polygon * @param contour The list of points describing the polygon
* @param result The list of points describing the triangles. Groups * @param result The list of points describing the triangles. Groups
* of 3 describe each triangle * of 3 describe each triangle
* @return True if we succeeded in completing triangulation * @return True if we succeeded in completing triangulation
*/ */
private static boolean process(PointList contour, PointList result) { private static boolean process(PointList contour, PointList result) {
/* allocate and initialize list of Vertices in polygon */ /* allocate and initialize list of Vertices in polygon */
int n = contour.size(); int n = contour.size();
if (n < 3) if (n < 3)
return false; return false;
int[] V = new int[n]; int[] V = new int[n];
/* we want a counter-clockwise polygon in V */ /* we want a counter-clockwise polygon in V */
if (0.0f < area(contour)) { if (0.0f < area(contour)) {
for (int v = 0; v < n; v++) for (int v = 0; v < n; v++)
V[v] = v; V[v] = v;
} else { } else {
for (int v = 0; v < n; v++) for (int v = 0; v < n; v++)
V[v] = (n - 1) - v; V[v] = (n - 1) - v;
} }
int nv = n; int nv = n;
/* remove nv-2 Vertices, creating 1 triangle every time */ /* remove nv-2 Vertices, creating 1 triangle every time */
int count = 2 * nv; /* error detection */ int count = 2 * nv; /* error detection */
//for (int m = 0, v = nv - 1; nv > 2;) { //for (int m = 0, v = nv - 1; nv > 2;) {
for (int v = nv - 1; nv > 2;) { for (int v = nv - 1; nv > 2; ) {
/* if we loop, it is probably a non-simple polygon */ /* if we loop, it is probably a non-simple polygon */
if (0 >= (count--)) { if (0 >= (count--)) {
//** Triangulate: ERROR - probable bad polygon! //** Triangulate: ERROR - probable bad polygon!
return false; return false;
} }
/* three consecutive vertices in current polygon, <u,v,w> */ /* three consecutive vertices in current polygon, <u,v,w> */
int u = v; int u = v;
if (nv <= u) if (nv <= u)
u = 0; /* previous */ u = 0; /* previous */
v = u + 1; v = u + 1;
if (nv <= v) if (nv <= v)
v = 0; /* new v */ v = 0; /* new v */
int w = v + 1; int w = v + 1;
if (nv <= w) if (nv <= w)
w = 0; /* next */ w = 0; /* next */
if (snip(contour, u, v, w, nv, V)) { if (snip(contour, u, v, w, nv, V)) {
int a, b, c, s, t; int a, b, c, s, t;
/* true names of the vertices */ /* true names of the vertices */
a = V[u]; a = V[u];
b = V[v]; b = V[v];
c = V[w]; c = V[w];
/* output Triangle */ /* output Triangle */
result.add(contour.get(a)); result.add(contour.get(a));
result.add(contour.get(b)); result.add(contour.get(b));
result.add(contour.get(c)); result.add(contour.get(c));
//m++; //m++;
/* remove v from remaining polygon */ /* remove v from remaining polygon */
for (s = v, t = v + 1; t < nv; s++, t++) { for (s = v, t = v + 1; t < nv; s++, t++) {
V[s] = V[t]; V[s] = V[t];
} }
nv--; nv--;
/* resest error detection counter */ /* resest error detection counter */
count = 2 * nv; count = 2 * nv;
} }
} }
return true; return true;
} }
/** /**
* A single point handled by the triangulator * A single point handled by the triangulator
* *
* @author Kevin Glass * @author Kevin Glass
*/ */
private class Point { private class Point {
/** The x coorindate of this point */ /**
private final float x; * The x coorindate of this point
/** The y coorindate of this point */ */
private final float y; private final float x;
/**
* The y coorindate of this point
*/
private final float y;
/** /**
* Create a new point * Create a new point
* *
* @param x The x coordindate of the point * @param x The x coordindate of the point
* @param y The y coordindate of the point * @param y The y coordindate of the point
*/ */
public Point(float x, float y) { public Point(float x, float y) {
this.x = x; this.x = x;
this.y = y; this.y = y;
} }
/** /**
* Get the x coordinate of the point * Get the x coordinate of the point
* *
* @return The x coordinate of the point * @return The x coordinate of the point
*/ */
public float getX() { public float getX() {
return x; return x;
} }
/** /**
* Get the y coordinate of the point * Get the y coordinate of the point
* *
* @return The y coordinate of the point * @return The y coordinate of the point
*/ */
public float getY() { public float getY() {
return y; return y;
} }
/** /**
* Convert this point into a float array * Convert this point into a float array
* *
* @return The contents of this point as a float array * @return The contents of this point as a float array
*/ */
public float[] toArray() { public float[] toArray() {
return new float[] { x, y }; return new float[]{x, y};
} }
} }
/** /**
* A list of type <code>Point</code> * A list of type <code>Point</code>
* *
* @author Kevin Glass * @author Kevin Glass
*/ */
private class PointList { private class PointList {
/** The list of points */ /**
private final ArrayList<Point> points = new ArrayList<Point>(); * The list of points
*/
private final ArrayList<Point> points = new ArrayList<Point>();
/** /**
* Create a new empty list * Create a new empty list
*/ */
public PointList() { public PointList() {
} }
/** /**
* Add a point to the list * Add a point to the list
* *
* @param point The point to add * @param point The point to add
*/ */
public void add(Point point) { public void add(Point point) {
points.add(point); points.add(point);
} }
///** ///**
// * Remove a point from the list // * Remove a point from the list
// * // *
// * @param point The point to remove // * @param point The point to remove
// */ // */
//public void remove(Point point) { //public void remove(Point point) {
// points.remove(point); // points.remove(point);
//} //}
/** /**
* Get the size of the list * Get the size of the list
* *
* @return The size of the list * @return The size of the list
*/ */
public int size() { public int size() {
return points.size(); return points.size();
} }
/** /**
* Get a point a specific index in the list * Get a point a specific index in the list
* *
* @param i The index of the point to retrieve * @param i The index of the point to retrieve
* @return The point * @return The point
*/ */
public Point get(int i) { public Point get(int i) {
return points.get(i); return points.get(i);
} }
} }
} }

View File

@@ -17,10 +17,6 @@
package org.oscim.utils.osmpbf; package org.oscim.utils.osmpbf;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.openstreetmap.osmosis.osmbinary.BinaryParser; import org.openstreetmap.osmosis.osmbinary.BinaryParser;
import org.openstreetmap.osmosis.osmbinary.Osmformat; import org.openstreetmap.osmosis.osmbinary.Osmformat;
import org.oscim.core.Tag; import org.oscim.core.Tag;
@@ -31,303 +27,309 @@ import org.oscim.core.osm.OsmNode;
import org.oscim.core.osm.OsmRelation; import org.oscim.core.osm.OsmRelation;
import org.oscim.core.osm.OsmWay; import org.oscim.core.osm.OsmWay;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/** /**
* Class that reads and parses binary files and sends the contained entities to * Class that reads and parses binary files and sends the contained entities to
* the sink. * the sink.
*/ */
public class OsmPbfParser extends BinaryParser { public class OsmPbfParser extends BinaryParser {
@Override @Override
public void complete() { public void complete() {
//sink.complete(); //sink.complete();
} }
// /** Get the osmosis object representing a the user in a given Info protobuf. // /** Get the osmosis object representing a the user in a given Info protobuf.
// * @param info The info protobuf. // * @param info The info protobuf.
// * @return The OsmUser object */ // * @return The OsmUser object */
// OsmUser getUser(Osmformat.Info info) { // OsmUser getUser(Osmformat.Info info) {
// // System.out.println(info); // // System.out.println(info);
// if (info.hasUid() && info.hasUserSid()) { // if (info.hasUid() && info.hasUserSid()) {
// if (info.getUid() < 0) { // if (info.getUid() < 0) {
// return OsmUser.NONE; // return OsmUser.NONE;
// } // }
// return new OsmUser(info.getUid(), getStringById(info.getUserSid())); // return new OsmUser(info.getUid(), getStringById(info.getUserSid()));
// } else { // } else {
// return OsmUser.NONE; // return OsmUser.NONE;
// } // }
// } // }
/** /**
* The magic number used to indicate no version number metadata for this * The magic number used to indicate no version number metadata for this
* entity. * entity.
*/ */
static final int NOVERSION = -1; static final int NOVERSION = -1;
/** The magic number used to indicate no changeset metadata for this entity. */ /**
static final int NOCHANGESET = -1; * The magic number used to indicate no changeset metadata for this entity.
*/
static final int NOCHANGESET = -1;
HashMap<Long, OsmNode> mNodeMap = new HashMap<Long, OsmNode>(); HashMap<Long, OsmNode> mNodeMap = new HashMap<Long, OsmNode>();
HashMap<Long, OsmWay> mWayMap = new HashMap<Long, OsmWay>(); HashMap<Long, OsmWay> mWayMap = new HashMap<Long, OsmWay>();
@Override @Override
protected void parseNodes(List<Osmformat.Node> nodes) { protected void parseNodes(List<Osmformat.Node> nodes) {
for (Osmformat.Node i : nodes) { for (Osmformat.Node i : nodes) {
int tagCnt = i.getKeysCount(); int tagCnt = i.getKeysCount();
TagSet tags = new TagSet(tagCnt); TagSet tags = new TagSet(tagCnt);
// List<Tag> tags = new ArrayList<Tag>(); // List<Tag> tags = new ArrayList<Tag>();
for (int j = 0; j < tagCnt; j++) { for (int j = 0; j < tagCnt; j++) {
tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j)))); tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j))));
} }
// long id, int version, Date timestamp, OsmUser user, // long id, int version, Date timestamp, OsmUser user,
// long changesetId, Collection<Tag> tags, // long changesetId, Collection<Tag> tags,
// double latitude, double longitude // double latitude, double longitude
OsmNode tmp; OsmNode tmp;
long id = i.getId(); long id = i.getId();
double latf = parseLat(i.getLat()), lonf = parseLon(i.getLon()); double latf = parseLat(i.getLat()), lonf = parseLon(i.getLon());
// if (i.hasInfo()) { // if (i.hasInfo()) {
// Osmformat.Info info = i.getInfo(); // Osmformat.Info info = i.getInfo();
// tmp = new OsmNode(new CommonEntityData(id, info.getVersion(), getDate(info), // tmp = new OsmNode(new CommonEntityData(id, info.getVersion(), getDate(info),
// getUser(info), info.getChangeset(), tags), latf, lonf); // getUser(info), info.getChangeset(), tags), latf, lonf);
// } else { // } else {
tmp = new OsmNode(latf, lonf, tags, id); tmp = new OsmNode(latf, lonf, tags, id);
// tmp = new Node(new CommonEntityData(id, NOVERSION, NODATE, OsmUser.NONE, // tmp = new Node(new CommonEntityData(id, NOVERSION, NODATE, OsmUser.NONE,
// NOCHANGESET, tags), latf, lonf); // NOCHANGESET, tags), latf, lonf);
// } // }
//sink.process(new NodeContainer(tmp)); //sink.process(new NodeContainer(tmp));
mNodeMap.put(Long.valueOf(id), tmp); mNodeMap.put(Long.valueOf(id), tmp);
} }
} }
@Override @Override
protected void parseDense(Osmformat.DenseNodes nodes) { protected void parseDense(Osmformat.DenseNodes nodes) {
long lastId = 0, lastLat = 0, lastLon = 0; long lastId = 0, lastLat = 0, lastLon = 0;
int j = 0; // Index into the keysvals array. int j = 0; // Index into the keysvals array.
// Stuff for dense info // Stuff for dense info
// long lasttimestamp = 0, lastchangeset = 0; // long lasttimestamp = 0, lastchangeset = 0;
// int lastuserSid = 0, lastuid = 0; // int lastuserSid = 0, lastuid = 0;
// DenseInfo di = null; // DenseInfo di = null;
// if (nodes.hasDenseinfo()) { // if (nodes.hasDenseinfo()) {
// di = nodes.getDenseinfo(); // di = nodes.getDenseinfo();
// } // }
for (int i = 0; i < nodes.getIdCount(); i++) { for (int i = 0; i < nodes.getIdCount(); i++) {
OsmNode tmp; OsmNode tmp;
TagSet tags = new TagSet(4); TagSet tags = new TagSet(4);
long lat = nodes.getLat(i) + lastLat; long lat = nodes.getLat(i) + lastLat;
lastLat = lat; lastLat = lat;
long lon = nodes.getLon(i) + lastLon; long lon = nodes.getLon(i) + lastLon;
lastLon = lon; lastLon = lon;
long id = nodes.getId(i) + lastId; long id = nodes.getId(i) + lastId;
lastId = id; lastId = id;
double latf = parseLat(lat), lonf = parseLon(lon); double latf = parseLat(lat), lonf = parseLon(lon);
// If empty, assume that nothing here has keys or vals. // If empty, assume that nothing here has keys or vals.
if (nodes.getKeysValsCount() > 0) { if (nodes.getKeysValsCount() > 0) {
while (nodes.getKeysVals(j) != 0) { while (nodes.getKeysVals(j) != 0) {
int keyid = nodes.getKeysVals(j++); int keyid = nodes.getKeysVals(j++);
int valid = nodes.getKeysVals(j++); int valid = nodes.getKeysVals(j++);
tags.add(new Tag(getStringById(keyid), getStringById(valid))); tags.add(new Tag(getStringById(keyid), getStringById(valid)));
} }
j++; // Skip over the '0' delimiter. j++; // Skip over the '0' delimiter.
} }
// Handle dense info. // Handle dense info.
// if (di != null) { // if (di != null) {
// int uid = di.getUid(i) + lastuid; lastuid = uid; // int uid = di.getUid(i) + lastuid; lastuid = uid;
// int userSid = di.getUserSid(i) + lastuserSid; lastuserSid = userSid; // int userSid = di.getUserSid(i) + lastuserSid; lastuserSid = userSid;
// long timestamp = di.getTimestamp(i) + lasttimestamp; lasttimestamp = timestamp; // long timestamp = di.getTimestamp(i) + lasttimestamp; lasttimestamp = timestamp;
// int version = di.getVersion(i); // int version = di.getVersion(i);
// long changeset = di.getChangeset(i) + lastchangeset; lastchangeset = changeset; // long changeset = di.getChangeset(i) + lastchangeset; lastchangeset = changeset;
// //
// Date date = new Date(date_granularity * timestamp); // Date date = new Date(date_granularity * timestamp);
//OsmUser user; //OsmUser user;
// if (uid < 0) { // if (uid < 0) {
// user = OsmUser.NONE; // user = OsmUser.NONE;
// } else { // } else {
// user = new OsmUser(uid, getStringById(userSid)); // user = new OsmUser(uid, getStringById(userSid));
// } // }
// //
// tmp = new OsmNode(id, tags, latf, lonf); // tmp = new OsmNode(id, tags, latf, lonf);
// } else { // } else {
tmp = new OsmNode(latf, lonf, tags, id); tmp = new OsmNode(latf, lonf, tags, id);
mNodeMap.put(Long.valueOf(id), tmp); mNodeMap.put(Long.valueOf(id), tmp);
// } // }
//sink.process(new NodeContainer(tmp)); //sink.process(new NodeContainer(tmp));
} }
} }
@Override @Override
protected void parseWays(List<Osmformat.Way> ways) { protected void parseWays(List<Osmformat.Way> ways) {
for (Osmformat.Way i : ways) { for (Osmformat.Way i : ways) {
int tagCnt = i.getKeysCount(); int tagCnt = i.getKeysCount();
TagSet tags = new TagSet(tagCnt); TagSet tags = new TagSet(tagCnt);
// List<Tag> tags = new ArrayList<Tag>(); // List<Tag> tags = new ArrayList<Tag>();
for (int j = 0; j < tagCnt; j++) { for (int j = 0; j < tagCnt; j++) {
tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j)))); tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j))));
} }
// List<Tag> tags = new ArrayList<Tag>(); // List<Tag> tags = new ArrayList<Tag>();
// for (int j = 0; j < ; j++) { // for (int j = 0; j < ; j++) {
// tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j)))); // tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j))));
// } // }
long lastId = 0; long lastId = 0;
List<OsmNode> nodes = new ArrayList<OsmNode>(); List<OsmNode> nodes = new ArrayList<OsmNode>();
for (long j : i.getRefsList()) { for (long j : i.getRefsList()) {
OsmNode n = mNodeMap.get(Long.valueOf(j + lastId)); OsmNode n = mNodeMap.get(Long.valueOf(j + lastId));
if (n == null) if (n == null)
n = new OsmNode(Double.NaN, Double.NaN, null, j + lastId); n = new OsmNode(Double.NaN, Double.NaN, null, j + lastId);
nodes.add(n); nodes.add(n);
lastId = j + lastId; lastId = j + lastId;
} }
long id = i.getId(); long id = i.getId();
// long id, int version, Date timestamp, OsmUser user, // long id, int version, Date timestamp, OsmUser user,
// long changesetId, Collection<Tag> tags, // long changesetId, Collection<Tag> tags,
// List<WayNode> wayNodes // List<WayNode> wayNodes
OsmWay tmp; OsmWay tmp;
// if (i.hasInfo()) { // if (i.hasInfo()) {
// Osmformat.Info info = i.getInfo(); // Osmformat.Info info = i.getInfo();
// tmp = new Way(new CommonEntityData(id, info.getVersion(), getDate(info), // tmp = new Way(new CommonEntityData(id, info.getVersion(), getDate(info),
// getUser(info), info.getChangeset(), tags), nodes); // getUser(info), info.getChangeset(), tags), nodes);
// } else { // } else {
tmp = new OsmWay(tags, id, nodes); tmp = new OsmWay(tags, id, nodes);
// } // }
mWayMap.put(Long.valueOf(id), tmp); mWayMap.put(Long.valueOf(id), tmp);
//sink.process(new WayContainer(tmp)); //sink.process(new WayContainer(tmp));
} }
} }
@Override @Override
protected void parseRelations(List<Osmformat.Relation> rels) { protected void parseRelations(List<Osmformat.Relation> rels) {
for (Osmformat.Relation i : rels) { for (Osmformat.Relation i : rels) {
int tagCnt = i.getKeysCount(); int tagCnt = i.getKeysCount();
TagSet tags = new TagSet(tagCnt); TagSet tags = new TagSet(tagCnt);
for (int j = 0; j < tagCnt; j++) for (int j = 0; j < tagCnt; j++)
tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j)))); tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j))));
long id = i.getId(); long id = i.getId();
long lastMid = 0; long lastMid = 0;
List<OsmMember> nodes = new ArrayList<OsmMember>(); List<OsmMember> nodes = new ArrayList<OsmMember>();
int memberCnt = i.getMemidsCount(); int memberCnt = i.getMemidsCount();
// for (int j = 0; j < memberCnt; j++) { // for (int j = 0; j < memberCnt; j++) {
// long mid = lastMid + i.getMemids(j); // long mid = lastMid + i.getMemids(j);
// lastMid = mid; // lastMid = mid;
// String role = getStringById(i.getRolesSid(j)); // String role = getStringById(i.getRolesSid(j));
// //
// Osmformat.Relation.MemberType t = i.getTypes(j); // Osmformat.Relation.MemberType t = i.getTypes(j);
// //
// if (t == Osmformat.Relation.MemberType.NODE) { // if (t == Osmformat.Relation.MemberType.NODE) {
// etype = EntityType.Node; // etype = EntityType.Node;
// } else if (t == Osmformat.Relation.MemberType.WAY) { // } else if (t == Osmformat.Relation.MemberType.WAY) {
// etype = EntityType.Way; // etype = EntityType.Way;
// } else if (t == Osmformat.Relation.MemberType.RELATION) { // } else if (t == Osmformat.Relation.MemberType.RELATION) {
// etype = EntityType.Relation; // etype = EntityType.Relation;
// } else { // } else {
// assert false; // TODO; Illegal file? // assert false; // TODO; Illegal file?
// } // }
// //
// nodes.add(new OsmMember(mid, etype, role)); // nodes.add(new OsmMember(mid, etype, role));
// } // }
// long id, int version, TimestampContainer timestampContainer, // long id, int version, TimestampContainer timestampContainer,
// OsmUser user, // OsmUser user,
// long changesetId, Collection<Tag> tags, // long changesetId, Collection<Tag> tags,
// List<RelationMember> members // List<RelationMember> members
OsmRelation tmp = new OsmRelation(tags, id, memberCnt); OsmRelation tmp = new OsmRelation(tags, id, memberCnt);
// if (i.hasInfo()) { // if (i.hasInfo()) {
// Osmformat.Info info = i.getInfo(); // Osmformat.Info info = i.getInfo();
// tmp = new Relation(new CommonEntityData(id, info.getVersion(), getDate(info), // tmp = new Relation(new CommonEntityData(id, info.getVersion(), getDate(info),
// getUser(info), info.getChangeset(), tags), nodes); // getUser(info), info.getChangeset(), tags), nodes);
// } else { // } else {
// tmp = new Relation(new CommonEntityData(id, NOVERSION, NODATE, OsmUser.NONE, // tmp = new Relation(new CommonEntityData(id, NOVERSION, NODATE, OsmUser.NONE,
// NOCHANGESET, tags), nodes); // NOCHANGESET, tags), nodes);
// } // }
// sink.process(new RelationContainer(tmp)); // sink.process(new RelationContainer(tmp));
} }
} }
@Override @Override
public void parse(Osmformat.HeaderBlock block) { public void parse(Osmformat.HeaderBlock block) {
for (String s : block.getRequiredFeaturesList()) { for (String s : block.getRequiredFeaturesList()) {
if (s.equals("OsmSchema-V0.6")) { if (s.equals("OsmSchema-V0.6")) {
continue; // We can parse this. continue; // We can parse this.
} }
if (s.equals("DenseNodes")) { if (s.equals("DenseNodes")) {
continue; // We can parse this. continue; // We can parse this.
} }
throw new RuntimeException("File requires unknown feature: " + s); throw new RuntimeException("File requires unknown feature: " + s);
} }
// if (block.hasBbox()) { // if (block.hasBbox()) {
// String source = OsmosisConstants.VERSION; // String source = OsmosisConstants.VERSION;
// if (block.hasSource()) { // if (block.hasSource()) {
// source = block.getSource(); // source = block.getSource();
// } // }
// //
// double multiplier = .000000001; // double multiplier = .000000001;
// double rightf = block.getBbox().getRight() * multiplier; // double rightf = block.getBbox().getRight() * multiplier;
// double leftf = block.getBbox().getLeft() * multiplier; // double leftf = block.getBbox().getLeft() * multiplier;
// double topf = block.getBbox().getTop() * multiplier; // double topf = block.getBbox().getTop() * multiplier;
// double bottomf = block.getBbox().getBottom() * multiplier; // double bottomf = block.getBbox().getBottom() * multiplier;
// //
// Bound bounds = new Bound(rightf, leftf, topf, bottomf, source); // Bound bounds = new Bound(rightf, leftf, topf, bottomf, source);
// sink.process(new BoundContainer(bounds)); // sink.process(new BoundContainer(bounds));
// } // }
} }
public OsmData getData() { public OsmData getData() {
// for (Entry<OsmRelation, List<TmpRelation>> entry : relationMembersForRelation // for (Entry<OsmRelation, List<TmpRelation>> entry : relationMembersForRelation
// .entrySet()) { // .entrySet()) {
// //
// OsmRelation relation = entry.getKey(); // OsmRelation relation = entry.getKey();
// //
// for (TmpRelation member : entry.getValue()) { // for (TmpRelation member : entry.getValue()) {
// //
// OsmElement memberObject = null; // OsmElement memberObject = null;
// //
// if ("node".equals(member)) { // if ("node".equals(member)) {
// memberObject = nodesById.get(member.id); // memberObject = nodesById.get(member.id);
// } else if ("way".equals(member)) { // } else if ("way".equals(member)) {
// memberObject = waysById.get(member.id); // memberObject = waysById.get(member.id);
// } else if ("relation".equals(member)) { // } else if ("relation".equals(member)) {
// memberObject = relationsById.get(member.id); // memberObject = relationsById.get(member.id);
// } else { // } else {
// // log("missing relation " + member.id); // // log("missing relation " + member.id);
// continue; // continue;
// } // }
// //
// if (memberObject != null) { // if (memberObject != null) {
// OsmMember ownMember = new OsmMember(member.role, // OsmMember ownMember = new OsmMember(member.role,
// memberObject); // memberObject);
// //
// relation.relationMembers.add(ownMember); // relation.relationMembers.add(ownMember);
// } // }
// } // }
// } // }
// give up references to original collections // give up references to original collections
ArrayList<OsmWay> ways = new ArrayList<OsmWay>(mWayMap.values()); ArrayList<OsmWay> ways = new ArrayList<OsmWay>(mWayMap.values());
ArrayList<OsmNode> nodes = new ArrayList<OsmNode>(mNodeMap.values()); ArrayList<OsmNode> nodes = new ArrayList<OsmNode>(mNodeMap.values());
//log.debug("nodes: " + nodes.size() + " ways: " + ways.size()); //log.debug("nodes: " + nodes.size() + " ways: " + ways.size());
return new OsmData(null, nodes, ways, null); return new OsmData(null, nodes, ways, null);
} }
} }

Some files were not shown because too many files have changed in this diff Show More