diff --git a/README.md b/README.md index fde879f..7df3ddc 100644 --- a/README.md +++ b/README.md @@ -5,4 +5,19 @@ This is the repo for https://play.google.com/store/apps/details?id=atorch.shorte I first released this app in 2014, around the same time as https://github.com/atorch/probability_puzzles. Shortest path didn't get nearly as many installs as probability puzzles, so I ended up forgetting about this one and let it gather dust for many years. -I'm going to add it to github and try to get it working again in 2023 :-) \ No newline at end of file +I'm going to add it to github and try to get it working again in 2023 :-) +## Map screen + +The "Study the Map", "Review Map" and "Map hint" screens draw country borders with a small custom view +(`CountryMapView`): no map SDK, no API key, no network access. The country polygons come from +[Natural Earth](https://www.naturalearthdata.com/) (public domain) and are bundled in +`app/src/main/assets/world_map.bin`, which is generated by a dependency-free Python script: + +```bash +curl -L -o /tmp/ne_10m_admin_0_countries.geojson \ + https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_admin_0_countries.geojson +python3 scripts/build_world_map.py /tmp/ne_10m_admin_0_countries.geojson +``` + +The script maps every puzzle country name in `strings.xml` to one or more Natural Earth units (see `GAME_UNITS`) +and fails if any name is missing, so re-run it whenever the country list changes. diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index c8f7843..9f9e39f 100755 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -26,6 +26,11 @@ android:exported="false" tools:node="merge"> + + diff --git a/app/src/main/assets/world_map.bin b/app/src/main/assets/world_map.bin new file mode 100644 index 0000000..5850761 Binary files /dev/null and b/app/src/main/assets/world_map.bin differ diff --git a/app/src/main/java/atorch/shortestpaths/CountryMapView.java b/app/src/main/java/atorch/shortestpaths/CountryMapView.java new file mode 100644 index 0000000..811ad29 --- /dev/null +++ b/app/src/main/java/atorch/shortestpaths/CountryMapView.java @@ -0,0 +1,509 @@ +package atorch.shortestpaths; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.RectF; +import android.util.AttributeSet; +import android.util.TypedValue; +import android.view.GestureDetector; +import android.view.MotionEvent; +import android.view.ScaleGestureDetector; +import android.view.View; +import android.widget.OverScroller; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * A minimal, offline, pannable / zoomable map of country borders, drawn with plain Canvas calls. + * + * Deliberately shows nothing but land, sea, borders and (optionally) puzzle country names. + * Callers can highlight countries with a fill colour and choose which names are shown. + */ +public class CountryMapView extends View { + + public interface OnCountryTapListener { + /** + * @param countryName the puzzle country that was tapped, or null for the sea or for land that is not + * part of the puzzles (e.g. Greenland) + * @param onLand whether the tap hit any land at all + */ + void onCountryTapped(String countryName, boolean onLand); + } + + public enum LabelMode { ALL, HIGHLIGHTED_ONLY, NONE } + + private static final int COLOR_SEA = 0xFFDCE8F0; + private static final int COLOR_LAND = 0xFFF7F4EC; + private static final int COLOR_OTHER_LAND = 0xFFE4E2DC; // Territories that never appear in puzzles + private static final int COLOR_BORDER = 0xFF6E6E6E; + private static final int COLOR_LABEL = 0xFF2B2B2B; + private static final int COLOR_LABEL_HALO = 0xDDFFFFFF; + + private static final float MAX_PIXELS_PER_UNIT = 400000f; // Deep enough to see Vatican City's outline + private static final float MAX_LOD_ERROR_PX = 0.75f; + + private WorldMap map; + private final List drawOrder = new ArrayList<>(); // Big first, so enclaves end up on top + + private final Map highlightColors = new HashMap<>(); + private final Set labelledHighlights = new HashSet<>(); + private LabelMode labelMode = LabelMode.ALL; + private OnCountryTapListener tapListener; + + // Viewport: screenX = mapX * scale + translateX (same for y) + private float scale = 1f; + private float translateX = 0f; + private float translateY = 0f; + private float minScale = 1f; + private RectF pendingFit; // Fit request made before the view was laid out + private float[] pendingViewport; + + private final Paint fillPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint borderPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint labelPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint haloPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final float density; + private final float borderWidthPx; + private final float dotRadiusPx; + private final Map labelWidths = new HashMap<>(); + private final List placedLabels = new ArrayList<>(); + private final RectF visible = new RectF(); + private final RectF scratch = new RectF(); + + private final ScaleGestureDetector scaleDetector; + private final GestureDetector gestureDetector; + private final OverScroller scroller; + + public CountryMapView(Context context) { + this(context, null); + } + + public CountryMapView(Context context, AttributeSet attrs) { + super(context, attrs); + density = getResources().getDisplayMetrics().density; + borderWidthPx = 1.0f * density; + dotRadiusPx = 3.5f * density; + + fillPaint.setStyle(Paint.Style.FILL); + borderPaint.setStyle(Paint.Style.STROKE); + borderPaint.setColor(COLOR_BORDER); + borderPaint.setStrokeJoin(Paint.Join.ROUND); + labelPaint.setColor(COLOR_LABEL); + labelPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12f, getResources().getDisplayMetrics())); + labelPaint.setTextAlign(Paint.Align.CENTER); + haloPaint.set(labelPaint); + haloPaint.setColor(COLOR_LABEL_HALO); + haloPaint.setStyle(Paint.Style.STROKE); + haloPaint.setStrokeWidth(3f * density); + haloPaint.setStrokeJoin(Paint.Join.ROUND); + + scroller = new OverScroller(context); + scaleDetector = new ScaleGestureDetector(context, new ScaleGestureDetector.SimpleOnScaleGestureListener() { + @Override + public boolean onScale(ScaleGestureDetector detector) { + zoomBy(detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY()); + return true; + } + }); + gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { + @Override + public boolean onDown(MotionEvent e) { + scroller.forceFinished(true); + return true; + } + + @Override + public boolean onScroll(MotionEvent e1, MotionEvent e2, float dx, float dy) { + translateX -= dx; + translateY -= dy; + clampTranslation(); + invalidate(); + return true; + } + + @Override + public boolean onFling(MotionEvent e1, MotionEvent e2, float vx, float vy) { + if (map == null) { + return false; + } + float[] range = translationRange(); + scroller.fling((int) translateX, (int) translateY, (int) vx, (int) vy, + (int) range[0], (int) range[1], (int) range[2], (int) range[3]); + postInvalidateOnAnimation(); + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + zoomBy(2f, e.getX(), e.getY()); + return true; + } + + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + if (tapListener != null && map != null) { + WorldMap.Feature hit = featureAt(e.getX(), e.getY()); + tapListener.onCountryTapped(hit == null ? null : map.countryNameFor(hit), hit != null); + } + return true; + } + }); + } + + public void setMap(WorldMap map) { + this.map = map; + drawOrder.clear(); + drawOrder.addAll(map.features); + Collections.sort(drawOrder, new Comparator() { + @Override + public int compare(WorldMap.Feature a, WorldMap.Feature b) { + return Float.compare(b.area, a.area); + } + }); + if (getWidth() > 0) { + updateMinScale(); + } + invalidate(); + } + + /** Fill every map unit of a puzzle country with a colour; labelled highlights stay visible in HIGHLIGHTED_ONLY. */ + public void highlightCountry(String countryName, int color, boolean showLabel) { + if (map == null) { + return; + } + for (WorldMap.Feature feature : map.featuresFor(countryName)) { + highlightColors.put(feature, color); + } + WorldMap.Feature primary = map.primaryFeatureFor(countryName); + if (primary != null && showLabel) { + labelledHighlights.add(primary); + } + invalidate(); + } + + public void clearHighlight(String countryName) { + if (map == null) { + return; + } + for (WorldMap.Feature feature : map.featuresFor(countryName)) { + highlightColors.remove(feature); + labelledHighlights.remove(feature); + } + invalidate(); + } + + public void setLabelMode(LabelMode mode) { + labelMode = mode; + invalidate(); + } + + public void setOnCountryTapListener(OnCountryTapListener listener) { + tapListener = listener; + } + + /** Bounds (in map coordinates) of the primary map units of these puzzle countries, or null if none are known. */ + public RectF boundsOf(List countryNames) { + RectF result = null; + for (String name : countryNames) { + WorldMap.Feature primary = map == null ? null : map.primaryFeatureFor(name); + if (primary == null) { + continue; + } + if (result == null) { + result = new RectF(primary.bounds); + } else { + result.union(primary.bounds); + } + } + return result; + } + + /** Zoom so that rect (map coordinates) fills the view, leaving a margin of `margin` times its size. */ + public void fitTo(RectF rect, float margin) { + RectF padded = new RectF(rect); + float minSize = 0.01f; // Don't zoom all the way in on a microstate + float w = Math.max(padded.width(), minSize) * (1 + 2 * margin); + float h = Math.max(padded.height(), minSize) * (1 + 2 * margin); + padded.set(padded.centerX() - w / 2, padded.centerY() - h / 2, padded.centerX() + w / 2, padded.centerY() + h / 2); + if (getWidth() == 0 || getHeight() == 0) { + pendingFit = padded; + return; + } + scale = clampScale(Math.min(getWidth() / padded.width(), getHeight() / padded.height())); + translateX = getWidth() / 2f - padded.centerX() * scale; + translateY = getHeight() / 2f - padded.centerY() * scale; + clampTranslation(); + invalidate(); + } + + public void fitWorld() { + if (map != null) { + fitTo(map.bounds, 0f); + } + } + + /** {centerX, centerY, pixelsPerUnit}, for saving across configuration changes. */ + public float[] getViewport() { + if (getWidth() == 0) { + return pendingViewport; + } + return new float[]{(getWidth() / 2f - translateX) / scale, (getHeight() / 2f - translateY) / scale, scale}; + } + + public void setViewport(float[] viewport) { + if (viewport == null) { + return; + } + if (getWidth() == 0) { + pendingViewport = viewport; + pendingFit = null; + return; + } + scale = clampScale(viewport[2]); + translateX = getWidth() / 2f - viewport[0] * scale; + translateY = getHeight() / 2f - viewport[1] * scale; + clampTranslation(); + invalidate(); + } + + @Override + protected void onSizeChanged(int w, int h, int oldW, int oldH) { + super.onSizeChanged(w, h, oldW, oldH); + float[] keep = null; + if (oldW > 0 && oldH > 0) { + keep = new float[]{(oldW / 2f - translateX) / scale, (oldH / 2f - translateY) / scale, scale}; + } + updateMinScale(); + if (pendingViewport != null) { + float[] viewport = pendingViewport; + pendingViewport = null; + setViewport(viewport); + } else if (pendingFit != null) { + RectF fit = pendingFit; + pendingFit = null; + fitTo(fit, 0f); + } else if (keep != null) { + setViewport(keep); + } else { + fitWorld(); + } + } + + private void updateMinScale() { + if (map == null || getWidth() == 0) { + return; + } + minScale = Math.min(getWidth() / map.bounds.width(), getHeight() / map.bounds.height()); + } + + private float clampScale(float s) { + return Math.max(minScale, Math.min(MAX_PIXELS_PER_UNIT, s)); + } + + private void zoomBy(float factor, float focusX, float focusY) { + float newScale = clampScale(scale * factor); + float applied = newScale / scale; + translateX = focusX - (focusX - translateX) * applied; + translateY = focusY - (focusY - translateY) * applied; + scale = newScale; + clampTranslation(); + invalidate(); + } + + /** {minX, maxX, minY, maxY} for the translation: the view's centre must stay over the map. */ + private float[] translationRange() { + RectF b = map.bounds; + float cx = getWidth() / 2f; + float cy = getHeight() / 2f; + float minX = cx - b.right * scale, maxX = cx - b.left * scale; + float minY = cy - b.bottom * scale, maxY = cy - b.top * scale; + // When the whole map fits in one dimension, just centre it + if (b.width() * scale <= getWidth()) { + minX = maxX = cx - b.centerX() * scale; + } + if (b.height() * scale <= getHeight()) { + minY = maxY = cy - b.centerY() * scale; + } + return new float[]{minX, maxX, minY, maxY}; + } + + private void clampTranslation() { + if (map == null) { + return; + } + float[] range = translationRange(); + translateX = Math.max(range[0], Math.min(range[1], translateX)); + translateY = Math.max(range[2], Math.min(range[3], translateY)); + } + + @Override + public void computeScroll() { + if (scroller.computeScrollOffset()) { + translateX = scroller.getCurrX(); + translateY = scroller.getCurrY(); + clampTranslation(); + postInvalidateOnAnimation(); + } + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + boolean handled = scaleDetector.onTouchEvent(event); + handled = gestureDetector.onTouchEvent(event) || handled; + return handled || super.onTouchEvent(event); + } + + // ------------------------------------------------------------------------------------------------------------ + // Drawing + + private boolean isDot(WorldMap.Feature f) { + // Microstates (and other tiny units) get a dot so they can be seen and tapped at any zoom + float threshold = 2.5f * dotRadiusPx; + return f.bounds.width() * scale < threshold && f.bounds.height() * scale < threshold; + } + + private int fillColorFor(WorldMap.Feature f) { + Integer highlight = highlightColors.get(f); + if (highlight != null) { + return highlight; + } + return map.countryNameFor(f) != null ? COLOR_LAND : COLOR_OTHER_LAND; + } + + @Override + protected void onDraw(Canvas canvas) { + canvas.drawColor(COLOR_SEA); + if (map == null) { + return; + } + visible.set(-translateX / scale, -translateY / scale, + (getWidth() - translateX) / scale, (getHeight() - translateY) / scale); + int lod = map.lodFor(scale, MAX_LOD_ERROR_PX); + + canvas.save(); + canvas.translate(translateX, translateY); + canvas.scale(scale, scale); + borderPaint.setStrokeWidth(borderWidthPx / scale); + for (WorldMap.Feature f : drawOrder) { + if (!RectF.intersects(visible, f.bounds)) { + continue; + } + fillPaint.setColor(fillColorFor(f)); + canvas.drawPath(f.getPath(lod), fillPaint); + canvas.drawPath(f.getPath(lod), borderPaint); + } + canvas.restore(); + + // Dots for tiny puzzle countries, drawn in screen space + borderPaint.setStrokeWidth(borderWidthPx); + for (WorldMap.Feature f : drawOrder) { + if (!f.isLabelled() || !isDot(f) || !visible.contains(f.labelX, f.labelY)) { + continue; + } + float x = f.labelX * scale + translateX; + float y = f.labelY * scale + translateY; + fillPaint.setColor(highlightColors.containsKey(f) ? highlightColors.get(f) : Color.WHITE); + canvas.drawCircle(x, y, dotRadiusPx, fillPaint); + canvas.drawCircle(x, y, dotRadiusPx, borderPaint); + } + + drawLabels(canvas); + } + + private void drawLabels(Canvas canvas) { + if (labelMode == LabelMode.NONE) { + return; + } + // Highlighted labels first (they must win collisions), then bigger countries first + List candidates = new ArrayList<>(); + for (WorldMap.Feature f : labelledHighlights) { + if (f.isLabelled()) { + candidates.add(f); + } + } + if (labelMode == LabelMode.ALL) { + for (WorldMap.Feature f : drawOrder) { + if (f.isLabelled() && !labelledHighlights.contains(f)) { + candidates.add(f); + } + } + } + + placedLabels.clear(); + Paint.FontMetrics fm = labelPaint.getFontMetrics(); + float textHeight = fm.descent - fm.ascent; + float pad = 2f * density; + for (WorldMap.Feature f : candidates) { + if (!visible.contains(f.labelX, f.labelY)) { + continue; + } + Float width = labelWidths.get(f); + if (width == null) { + width = labelPaint.measureText(f.label); + labelWidths.put(f, width); + } + boolean important = labelledHighlights.contains(f); + boolean dot = isDot(f); + // Skip names that are much wider than their country, unless highlighted (or drawn as a dot) + if (!important && !dot && f.bounds.width() * scale < 0.6f * width) { + continue; + } + float x = f.labelX * scale + translateX; + float y = f.labelY * scale + translateY; + if (dot) { + y += dotRadiusPx + textHeight / 2; // Name goes under the dot + } + float baseline = y - (fm.ascent + fm.descent) / 2; + scratch.set(x - width / 2 - pad, y - textHeight / 2 - pad, x + width / 2 + pad, y + textHeight / 2 + pad); + boolean collides = false; + for (RectF placed : placedLabels) { + if (RectF.intersects(placed, scratch)) { + collides = true; + break; + } + } + if (collides && !important) { + continue; + } + placedLabels.add(new RectF(scratch)); + canvas.drawText(f.label, x, baseline, haloPaint); + canvas.drawText(f.label, x, baseline, labelPaint); + } + } + + // ------------------------------------------------------------------------------------------------------------ + // Hit testing + + private WorldMap.Feature featureAt(float screenX, float screenY) { + // Dots first: they are the only practical way to tap a microstate + float slop = 2f * dotRadiusPx; + for (int i = drawOrder.size() - 1; i >= 0; i--) { + WorldMap.Feature f = drawOrder.get(i); + if (f.isLabelled() && isDot(f)) { + float dx = f.labelX * scale + translateX - screenX; + float dy = f.labelY * scale + translateY - screenY; + if (dx * dx + dy * dy <= slop * slop) { + return f; + } + } + } + float x = (screenX - translateX) / scale; + float y = (screenY - translateY) / scale; + for (int i = drawOrder.size() - 1; i >= 0; i--) { // Smallest first: enclaves sit on top + WorldMap.Feature f = drawOrder.get(i); + if (f.contains(x, y)) { + return f; + } + } + return null; + } +} diff --git a/app/src/main/java/atorch/shortestpaths/MainActivity.java b/app/src/main/java/atorch/shortestpaths/MainActivity.java index d966238..bd34a45 100755 --- a/app/src/main/java/atorch/shortestpaths/MainActivity.java +++ b/app/src/main/java/atorch/shortestpaths/MainActivity.java @@ -163,6 +163,10 @@ public void startPuzzle(View view) { } } + public void studyMap(View view) { + startActivity(ReviewMap.studyIntent(this)); + } + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); diff --git a/app/src/main/java/atorch/shortestpaths/ReviewMap.java b/app/src/main/java/atorch/shortestpaths/ReviewMap.java new file mode 100644 index 0000000..9e31c1f --- /dev/null +++ b/app/src/main/java/atorch/shortestpaths/ReviewMap.java @@ -0,0 +1,276 @@ +package atorch.shortestpaths; + +import android.content.Context; +import android.content.Intent; +import android.graphics.RectF; +import android.os.Bundle; +import android.text.SpannableStringBuilder; +import android.text.Spanned; +import android.text.style.ForegroundColorSpan; +import android.text.style.StyleSpan; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.app.AppCompatActivity; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Map screen (issue #4). Four modes: + *
    + *
  • STUDY: the whole world with every puzzle country named; tap a country to see its name. + * Names can be hidden from the menu, to quiz yourself by tapping.
  • + *
  • REVIEW: after solving a puzzle, the route we took is highlighted and named.
  • + *
  • ANSWER: after giving up, one of the shortest routes is highlighted and named.
  • + *
  • HINT: while solving, borders only. Just the start, the destination and the countries we have already + * passed through are named, and tapping doesn't reveal anything.
  • + *
+ */ +public class ReviewMap extends AppCompatActivity { + + public static final String EXTRA_MODE = "atorch.shortestpaths.MAP_MODE"; + public static final String EXTRA_FROM = "atorch.shortestpaths.MAP_FROM"; + public static final String EXTRA_TO = "atorch.shortestpaths.MAP_TO"; + public static final String EXTRA_ROUTE = "atorch.shortestpaths.MAP_ROUTE"; // Countries between FROM and TO + + public static final int MODE_STUDY = 0; + public static final int MODE_REVIEW = 1; + public static final int MODE_HINT = 2; + public static final int MODE_ANSWER = 3; + + private static final int COLOR_START = 0xFF93D293; + private static final int COLOR_DESTINATION = 0xFFF2A48E; + private static final int COLOR_ROUTE = 0xFFA3C6EE; + private static final int COLOR_SELECTED = 0xFFF6DC7A; + + private static final String STATE_VIEWPORT = "viewport"; + private static final String STATE_SHOW_NAMES = "show_names"; + private static final String STATE_SELECTED = "selected"; + + private CountryMapView mapView; + private TextView status; + private int mode; + private boolean showNames = true; + private String selected; + private final Map routeHighlights = new LinkedHashMap<>(); + + public static Intent studyIntent(Context context) { + Intent intent = new Intent(context, ReviewMap.class); + intent.putExtra(EXTRA_MODE, MODE_STUDY); + return intent; + } + + public static Intent routeIntent(Context context, int mode, String from, String to, List route) { + Intent intent = new Intent(context, ReviewMap.class); + intent.putExtra(EXTRA_MODE, mode); + intent.putExtra(EXTRA_FROM, from); + intent.putExtra(EXTRA_TO, to); + intent.putExtra(EXTRA_ROUTE, route.toArray(new String[0])); + return intent; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_review_map); + SystemBars.setUp(this); // Keeps the legend below the action bar and the status text above the navigation bar + + ActionBar actionBar = getSupportActionBar(); + if (actionBar != null) { + actionBar.setDisplayHomeAsUpEnabled(true); + } + + WorldMap worldMap; + try { + worldMap = WorldMap.get(this); + } catch (IOException e) { + Toast.makeText(this, R.string.map_load_error, Toast.LENGTH_LONG).show(); + finish(); + return; + } + + Intent intent = getIntent(); + mode = intent.getIntExtra(EXTRA_MODE, MODE_STUDY); + String from = intent.getStringExtra(EXTRA_FROM); + String to = intent.getStringExtra(EXTRA_TO); + String[] routeExtra = intent.getStringArrayExtra(EXTRA_ROUTE); + List route = routeExtra == null ? new ArrayList() : Arrays.asList(routeExtra); + + mapView = findViewById(R.id.country_map); + status = findViewById(R.id.map_status); + TextView legend = findViewById(R.id.map_legend); + mapView.setMap(worldMap); + + if (savedInstanceState != null) { + showNames = savedInstanceState.getBoolean(STATE_SHOW_NAMES, true); + selected = savedInstanceState.getString(STATE_SELECTED); + } + + switch (mode) { + case MODE_REVIEW: + setTitle(R.string.title_activity_review_map); + break; + case MODE_ANSWER: + setTitle(R.string.title_activity_answer_map); + break; + case MODE_HINT: + setTitle(R.string.title_activity_hint_map); + break; + default: + setTitle(R.string.title_activity_study_map); + } + + List allCountries = new ArrayList<>(); + if (mode != MODE_STUDY && from != null && to != null) { + routeHighlights.put(from, COLOR_START); + for (String country : route) { + routeHighlights.put(country, COLOR_ROUTE); + } + routeHighlights.put(to, COLOR_DESTINATION); + for (Map.Entry entry : routeHighlights.entrySet()) { + mapView.highlightCountry(entry.getKey(), entry.getValue(), true); + } + allCountries.add(from); + allCountries.addAll(route); + allCountries.add(to); + legend.setText(buildLegend(from, route, to)); + legend.setVisibility(View.VISIBLE); + } + + if (mode == MODE_HINT) { + showNames = false; + status.setText(R.string.map_hint_explanation); + status.setVisibility(View.VISIBLE); + } else { + mapView.setOnCountryTapListener(new CountryMapView.OnCountryTapListener() { + @Override + public void onCountryTapped(String countryName, boolean onLand) { + select(countryName, onLand); + } + }); + status.setText(R.string.map_tap_explanation); + status.setVisibility(View.VISIBLE); + if (selected != null) { + select(selected, true); + } + } + applyLabelMode(); + + float[] viewport = savedInstanceState == null ? null : savedInstanceState.getFloatArray(STATE_VIEWPORT); + if (viewport != null) { + mapView.setViewport(viewport); + } else if (!allCountries.isEmpty()) { + RectF bounds = mapView.boundsOf(allCountries); + if (bounds != null) { + // Hints zoom out a little more, so that some of the neighbours are visible too + mapView.fitTo(bounds, mode == MODE_HINT ? 0.6f : 0.25f); + } + } + } + + private CharSequence buildLegend(String from, List route, String to) { + SpannableStringBuilder text = new SpannableStringBuilder(); + int intro; + if (mode == MODE_REVIEW) { + intro = R.string.map_legend_review; + } else if (mode == MODE_ANSWER) { + intro = R.string.map_legend_answer; + } else { + intro = R.string.map_legend_hint; + } + text.append(getString(intro)).append("\n"); + appendCountry(text, from, COLOR_START); + for (String country : route) { + text.append(" → "); + appendCountry(text, country, COLOR_ROUTE); + } + text.append(" → "); + if (mode == MODE_HINT) { + text.append("… → "); + } + appendCountry(text, to, COLOR_DESTINATION); + return text; + } + + private static void appendCountry(SpannableStringBuilder text, String country, int color) { + int start = text.length(); + text.append("●"); + text.setSpan(new ForegroundColorSpan(color), start, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + text.append(" "); + int nameStart = text.length(); + text.append(country); + text.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), nameStart, text.length(), + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } + + private void select(String countryName, boolean onLand) { + if (selected != null) { + mapView.clearHighlight(selected); + Integer routeColor = routeHighlights.get(selected); + if (routeColor != null) { + mapView.highlightCountry(selected, routeColor, true); + } + } + selected = countryName; + if (countryName != null) { + mapView.highlightCountry(countryName, COLOR_SELECTED, true); + status.setText(countryName); + } else if (onLand) { + status.setText(R.string.map_not_in_puzzles); + } else { + status.setText(R.string.map_tap_explanation); + } + status.setVisibility(View.VISIBLE); + } + + private void applyLabelMode() { + mapView.setLabelMode(showNames ? CountryMapView.LabelMode.ALL : CountryMapView.LabelMode.HIGHLIGHTED_ONLY); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + if (mode == MODE_HINT) { + return false; // No way to turn the names back on during a puzzle + } + getMenuInflater().inflate(R.menu.review_map, menu); + menu.findItem(R.id.action_show_names).setChecked(showNames); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + if (id == android.R.id.home) { + finish(); // Behave like "back": we can be opened from the main menu or from a puzzle + return true; + } else if (id == R.id.action_show_names) { + showNames = !showNames; + item.setChecked(showNames); + applyLabelMode(); + return true; + } else if (id == R.id.action_show_world) { + mapView.fitWorld(); + return true; + } + return super.onOptionsItemSelected(item); + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + if (mapView != null) { + outState.putFloatArray(STATE_VIEWPORT, mapView.getViewport()); + } + outState.putBoolean(STATE_SHOW_NAMES, showNames); + outState.putString(STATE_SELECTED, selected); + } +} diff --git a/app/src/main/java/atorch/shortestpaths/SolvePuzzle.java b/app/src/main/java/atorch/shortestpaths/SolvePuzzle.java index de16a0c..7b8f524 100755 --- a/app/src/main/java/atorch/shortestpaths/SolvePuzzle.java +++ b/app/src/main/java/atorch/shortestpaths/SolvePuzzle.java @@ -118,6 +118,13 @@ public void onClick(DialogInterface dialog, int id) { } } ); + builder.setNeutralButton(R.string.give_up_show_me, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + showAnswer(); + } + } + ); builder.setNegativeButton("Keep Going", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { @@ -329,6 +336,22 @@ public void newPuzzle(View view) { startActivity(intent); } + public void reviewMap(View view) { + startActivity(ReviewMap.routeIntent(this, ReviewMap.MODE_REVIEW, country_from, country_to, user_route)); + } + + private void showAnswer() { + // Any shortest path that is consistent with what the user has entered so far + for (int i = 0; i < number_of_paths; i++) { + if (path_indicators[i]) { + startActivity(ReviewMap.routeIntent(this, ReviewMap.MODE_ANSWER, country_from, country_to, + Arrays.asList(paths[i]))); + finish(); // No sneaking back to finish the puzzle once you've seen the answer + return; + } + } + } + @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.solve_puzzle, menu); @@ -337,6 +360,12 @@ public boolean onCreateOptionsMenu(Menu menu) { @Override public boolean onOptionsItemSelected(MenuItem item) { + if (item.getItemId() == R.id.action_map_hint) { + boolean solved = user_progress >= path_length_inner; + int mode = solved ? ReviewMap.MODE_REVIEW : ReviewMap.MODE_HINT; + startActivity(ReviewMap.routeIntent(this, mode, country_from, country_to, user_route)); + return true; + } return super.onOptionsItemSelected(item); } } diff --git a/app/src/main/java/atorch/shortestpaths/WorldMap.java b/app/src/main/java/atorch/shortestpaths/WorldMap.java new file mode 100644 index 0000000..22057ac --- /dev/null +++ b/app/src/main/java/atorch/shortestpaths/WorldMap.java @@ -0,0 +1,262 @@ +package atorch.shortestpaths; + +import android.content.Context; +import android.graphics.Path; +import android.graphics.RectF; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Country polygons for the map screen, read from assets/world_map.bin. + * + * The asset is generated by scripts/build_world_map.py from Natural Earth (public domain) data; + * see that script for the binary format. Coordinates are Web Mercator, normalized to the unit + * square: x in [0, 1] from 180W to 180E, y in [0, 1] from north to south. + */ +public class WorldMap { + + private static final String ASSET_NAME = "world_map.bin"; + private static WorldMap instance; + + public static class Feature { + public final String code; // Natural Earth ADM0_A3 code, e.g. "FRA" (or our own "GUF" / "KAL") + public final String label; // Puzzle country name to draw, or "" if this unit is not labelled + public final float labelX; + public final float labelY; + public final float[][][] lods; // lods[lod][ring] = {x0, y0, x1, y1, ...}, coarsest LOD first + public final RectF bounds = new RectF(); + public final float area; // Approximate (bounding box) area, used for draw & label order + private final Path[] paths; + + Feature(String code, String label, float labelX, float labelY, float[][][] lods) { + this.code = code; + this.label = label; + this.labelX = labelX; + this.labelY = labelY; + this.lods = lods; + this.paths = new Path[lods.length]; + float minX = Float.MAX_VALUE, minY = Float.MAX_VALUE; + float maxX = -Float.MAX_VALUE, maxY = -Float.MAX_VALUE; + for (float[] ring : lods[lods.length - 1]) { + for (int i = 0; i < ring.length; i += 2) { + minX = Math.min(minX, ring[i]); + maxX = Math.max(maxX, ring[i]); + minY = Math.min(minY, ring[i + 1]); + maxY = Math.max(maxY, ring[i + 1]); + } + } + bounds.set(minX, minY, maxX, maxY); + area = bounds.width() * bounds.height(); + } + + public boolean isLabelled() { + return label.length() > 0; + } + + /** Lazily builds (and caches) an android Path for the given level of detail. */ + public Path getPath(int lod) { + if (paths[lod] == null) { + Path path = new Path(); + path.setFillType(Path.FillType.EVEN_ODD); // Holes (e.g. Lesotho inside South Africa) + for (float[] ring : lods[lod]) { + path.moveTo(ring[0], ring[1]); + for (int i = 2; i < ring.length; i += 2) { + path.lineTo(ring[i], ring[i + 1]); + } + path.close(); + } + paths[lod] = path; + } + return paths[lod]; + } + + /** Even-odd point-in-polygon test, in map coordinates, against the finest LOD. */ + public boolean contains(float x, float y) { + if (!bounds.contains(x, y)) { + return false; + } + boolean inside = false; + for (float[] ring : lods[lods.length - 1]) { + int n = ring.length; + for (int i = 0, j = n - 2; i < n; j = i, i += 2) { + float xi = ring[i], yi = ring[i + 1], xj = ring[j], yj = ring[j + 1]; + if ((yi > y) != (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) { + inside = !inside; + } + } + } + return inside; + } + } + + public final List features; + private final Map aliases; // Puzzle country name -> feature indices (first is primary) + private final Map countryNames = new HashMap<>(); // Map unit -> puzzle country name + public final float[] lodTolerances; // Simplification tolerance of each LOD, coarsest first + public final RectF bounds = new RectF(); // Union of all features + + private WorldMap(List features, Map aliases, float[] lodTolerances) { + this.features = features; + this.aliases = aliases; + this.lodTolerances = lodTolerances; + // Unlabelled units that belong to a puzzle country, e.g. Saint-Martin (France), Akrotiri (United Kingdom) + for (Map.Entry entry : aliases.entrySet()) { + for (int index : entry.getValue()) { + Feature feature = features.get(index); + if (!feature.isLabelled()) { + countryNames.put(feature, entry.getKey()); + } + } + } + bounds.set(features.get(0).bounds); + for (Feature feature : features) { + bounds.union(feature.bounds); + } + } + + /** The puzzle country a map unit belongs to, or null (e.g. Greenland, Western Sahara). */ + public String countryNameFor(Feature feature) { + if (feature.isLabelled()) { + return feature.label; + } + return countryNames.get(feature); + } + + /** Index of the coarsest LOD whose simplification error is below maxErrorPx at this zoom. */ + public int lodFor(float pixelsPerUnit, float maxErrorPx) { + for (int lod = 0; lod < lodTolerances.length; lod++) { + if (lodTolerances[lod] * pixelsPerUnit <= maxErrorPx) { + return lod; + } + } + return lodTolerances.length - 1; + } + + public static synchronized WorldMap get(Context context) throws IOException { + if (instance == null) { + instance = parse(readAsset(context)); + } + return instance; + } + + /** All map units that make up a puzzle country (empty if unknown). */ + public List featuresFor(String countryName) { + List result = new ArrayList<>(); + int[] indices = aliases.get(countryName); + if (indices != null) { + for (int index : indices) { + result.add(features.get(index)); + } + } + return result; + } + + /** The map unit that carries a puzzle country's label, or null if unknown. */ + public Feature primaryFeatureFor(String countryName) { + int[] indices = aliases.get(countryName); + return (indices == null || indices.length == 0) ? null : features.get(indices[0]); + } + + private static byte[] readAsset(Context context) throws IOException { + InputStream in = context.getAssets().open(ASSET_NAME); + try { + ByteArrayOutputStream out = new ByteArrayOutputStream(1 << 20); + byte[] buffer = new byte[1 << 16]; + int n; + while ((n = in.read(buffer)) > 0) { + out.write(buffer, 0, n); + } + return out.toByteArray(); + } finally { + in.close(); + } + } + + static WorldMap parse(byte[] data) throws IOException { + ByteBuffer buf = ByteBuffer.wrap(data); // Big-endian by default, matching the script + if (buf.get() != 'S' || buf.get() != 'P' || buf.get() != 'W' || buf.get() != 'M') { + throw new IOException("Not a world map file"); + } + int version = buf.get(); + if (version != 1) { + throw new IOException("Unsupported world map version " + version); + } + float quantScale = 1.0f / (1 << readVarint(buf)); + int lodCount = readVarint(buf); + float[] lodTolerances = new float[lodCount]; + for (int lod = 0; lod < lodCount; lod++) { + lodTolerances[lod] = buf.getFloat(); + } + int featureCount = readVarint(buf); + + List features = new ArrayList<>(featureCount); + for (int f = 0; f < featureCount; f++) { + String code = readString(buf); + String label = readString(buf); + float labelX = buf.getFloat(); + float labelY = buf.getFloat(); + float[][][] lods = new float[lodCount][][]; + for (int lod = 0; lod < lodCount; lod++) { + int ringCount = readVarint(buf); + float[][] rings = new float[ringCount][]; + for (int r = 0; r < ringCount; r++) { + int pointCount = readVarint(buf); + float[] ring = new float[2 * pointCount]; + int x = 0, y = 0; + for (int i = 0; i < pointCount; i++) { + x += readZigzag(buf); + y += readZigzag(buf); + ring[2 * i] = x * quantScale; + ring[2 * i + 1] = y * quantScale; + } + rings[r] = ring; + } + lods[lod] = rings; + } + features.add(new Feature(code, label, labelX, labelY, lods)); + } + + int aliasCount = readVarint(buf); + Map aliases = new HashMap<>(); + for (int a = 0; a < aliasCount; a++) { + String name = readString(buf); + int[] indices = new int[readVarint(buf)]; + for (int i = 0; i < indices.length; i++) { + indices[i] = readVarint(buf); + } + aliases.put(name, indices); + } + return new WorldMap(features, aliases, lodTolerances); + } + + private static int readVarint(ByteBuffer buf) { + int result = 0; + int shift = 0; + while (true) { + int b = buf.get() & 0xFF; + result |= (b & 0x7F) << shift; + if ((b & 0x80) == 0) { + return result; + } + shift += 7; + } + } + + private static int readZigzag(ByteBuffer buf) { + int v = readVarint(buf); + return (v >>> 1) ^ -(v & 1); + } + + private static String readString(ByteBuffer buf) throws IOException { + byte[] bytes = new byte[readVarint(buf)]; + buf.get(bytes); + return new String(bytes, "UTF-8"); + } +} diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 6b0852e..90bb860 100755 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -99,6 +99,26 @@ android:text="@string/button_level_2" /> + + + +