A location-based augmented reality game where your real-world neighborhood procedurally generates the game around you.
TurfSynth AR merges open-world turf dynamics with creature collection and environmental synthesis. Instead of overlaying static content onto the real world the way existing location-based games do, TurfSynth extracts compact “Place Fingerprints” from camera, microphone, and sensor data, then uses those fingerprints to procedurally generate creatures, soundscapes, visuals, and mission flavor that are unique to every block. The core pitch: what if you could take over the turf in your own neighborhood, and the world you are standing in literally builds the game around you?
This repository contains the authoritative backend implementation (Fastify + TypeScript), the Unity AR client scaffolding, two Gemini-powered prototype applications (3D maps and spatial understanding), and the full specification-driven feature library that governs ongoing development.
Location-based games today overlay static, artist-authored content on top of the real world. Every player who visits the same spot sees the same gym, the same spawn, the same assets. The world itself contributes nothing to the experience. Environmental context – color, sound, geometry, motion, time of day – is completely ignored.
TurfSynth AR introduces environmental synthesis: the player’s actual surroundings become the creative engine. On-device pipelines extract a compact “Place Fingerprint” (a privacy-preserving feature vector under 400 bytes) from camera frames, ambient audio, motion sensors, and GPS locality. That fingerprint drives procedural generation of collectible creatures (“Synthlings”), ambient soundscapes, visual themes, and mission parameters. No raw camera or audio data ever leaves the device.
The game layer on top of this synthesis engine is a turf-control system where neighborhoods are divided into H3 hexagonal cells grouped into districts. Players form crews, earn influence through exploration and combat, deploy outposts, and execute asynchronous raids to contest territory. Influence decays over time, so holding turf requires continuous play rather than a one-time capture.
A location-based game where every block sounds and looks like itself, every player’s creature collection reflects the places they have actually visited, and neighborhood pride becomes a literal game mechanic. The result is a system where the real world and the game world are coupled at a level of specificity that no existing title achieves.
You are a “Mapper” who samples reality to produce a personalized, stylized underworld layer: graffiti sigils, neon signage, ambient beats, faction banners, procedural creatures, and mission set dressing – all generated from your surroundings without requiring artists to hand-author every block of every city.
┌─────────────────────────────────────────────────────────────────┐
│ Unity Client │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ AR Session │ │ Fingerprint │ │ Turf │ │
│ │ Manager │ │ Capture │ │ Display │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└───────────────────────────┬─────────────────────────────────────┘
│ REST API (shared/api-types.ts)
┌───────────────────────────┴─────────────────────────────────────┐
│ Node.js Backend (Fastify 5) │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Geofencing │ │ Fingerprint │ │ Turf │ │
│ │ Service │ │ Service │ │ Service │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │ │
│ ┌──────┴─────────────────┴──────────────────┴───────┐ │
│ │ PostgreSQL 16 + PostGIS 3.4 │ │
│ │ Redis 7 │ │
│ └────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
The backend is structured as three domain services, each with its own API route prefix, database tables, and specification document.
| Service | Route Prefix | Purpose | Key Modules |
|---|---|---|---|
| Geofencing | /api/v1/location |
GPS validation, exclusion zones (schools, hospitals, government buildings), spoof detection, speed lockouts | zone-checker, speed-validator, spoof-detector, h3-cache, zone-sync |
| Fingerprint | /api/v1/fingerprint |
Receive, validate, store, and query Place Fingerprints; award influence for submissions; calculate fingerprint similarity | capture-manager, color-extractor, visual-pipeline, audio-pipeline, assembler, validation-gate |
| Turf | /api/v1/turf |
Territory control: influence scoring with time-decay, outpost deployment and module management, raid initiation and resolution, district leaderboards, crew management, contract generation | influence-manager, outpost-manager, raid-engine |
All three services share a PostgreSQL connection pool and a Redis instance. The server entry point (src/server.ts) registers Fastify plugins for CORS and rate limiting, mounts the three route prefixes, and exposes /health and /ready endpoints suitable for Kubernetes probes.
The Unity project (unity/) targets Unity 2022.3 LTS with AR Foundation for cross-platform ARKit/ARCore support:
| Component | Purpose | Path |
|---|---|---|
| ARSessionManager | AR Foundation setup, camera and sensor access | unity/Assets/Scripts/AR/ |
| FingerprintCapture | On-device environmental feature extraction | unity/Assets/Scripts/Fingerprint/ |
| ApiClient | REST client for backend communication | unity/Assets/Scripts/Networking/ |
| LocationService | GPS management and location updates | unity/Assets/Scripts/Networking/ |
C# API types can be generated from the shared TypeScript contract:
npx quicktype -s typescript -o unity/Assets/Scripts/Generated/ApiTypes.cs shared/api-types.ts
Two Gemini-powered web prototypes provide proof-of-concept spatial tooling:
Both use Vite + TypeScript and require a GEMINI_API_KEY in .env.local.
Three SQL migrations define the persistence layer:
001 – Geofencing (src/db/migrations/001_geofencing_schema.sql): Exclusion zones with PostGIS geometry, H3 cell-to-zone cache, partitioned location validation audit log (monthly partitions with 6-month retention), speed lockout records, cumulative spoof scores, and helper functions (check_exclusion_zone, get_cached_zones, update_h3_cache).
002 – Fingerprints (src/db/migrations/002_fingerprint_schema.sql): Fingerprint storage with JSONB columns for palette, geometry, motion, audio, and locality descriptors. User and area queries.
003 – Turf Mechanics (src/db/migrations/003_turf_mechanics_schema.sql): Districts, outposts (one per cell, up to 4 module types), raids with JSONB results, contracts (5 types: capture, survey, patrol, raid, defend), spawn configuration per cell, and stored functions for outpost ticks, district control calculation, raid resolution, and daily contract generation.
| Dependency | Minimum Version | Purpose |
|---|---|---|
| Node.js | 20.0 | Runtime |
| PostgreSQL | 16 | Primary data store |
| PostGIS | 3.4 | Geospatial queries |
| Redis | 7 | Caching, rate limiting, speed lockout state |
| Unity | 2022.3 LTS | AR client (optional, for client development only) |
# Clone the repository
git clone https://github.com/organvm-iii-ergon/my-block-warfare.git
cd my-block-warfare
# Install dependencies
npm install
# Configure environment
cp .env.example .env.local
# Edit .env.local with your database credentials and Redis URL
# Database
DATABASE_URL=postgresql://localhost:5432/turfsynth
DATABASE_POOL_SIZE=20
# Redis
REDIS_URL=redis://localhost:6379
REDIS_CLUSTER_MODE=false
# Server
PORT=3000
HOST=0.0.0.0
NODE_ENV=development
# H3 Configuration
H3_RESOLUTION_STORAGE=7 # ~5km cells for storage
H3_RESOLUTION_GAMEPLAY=9 # ~175m cells for gameplay
# Rate Limiting
RATE_LIMIT_MAX=100
RATE_LIMIT_WINDOW_MS=60000
# Geofencing
SPEED_LOCKOUT_KMH=15
SPEED_WINDOW_SECONDS=30
SPOOF_VELOCITY_MAX_KMH=500
# Zone Data Sources
OSM_API_URL=https://overpass-api.de/api/interpreter
SAFEGRAPH_API_KEY= # Optional
# Logging
LOG_LEVEL=info
# Ensure PostGIS extension is available
psql -d turfsynth -c "CREATE EXTENSION IF NOT EXISTS postgis;"
psql -d turfsynth -c "CREATE EXTENSION IF NOT EXISTS pg_trgm;"
# Run migrations
npm run db:migrate
# Seed development data (optional)
npm run db:seed
npm run dev
# Server starts at http://localhost:3000
# Health check: http://localhost:3000/health
# Readiness probe: http://localhost:3000/ready
# 3D Maps (LitElement + MCP + Google Maps)
cd mcp-maps-3d && npm install && npm run dev
# Spatial Understanding (React + Gemini Vision)
cd spatial-understanding && npm install && npm run dev
Both require GEMINI_API_KEY set in their respective .env.local files.
┌─────────────────────────────────────────────────────────────────┐
│ Player walks into cell │
│ │ │
│ ▼ │
│ Location validated (Safety Geofencing) ─── Fails? ──▶ Blocked │
│ │ │
│ ▼ Passes │
│ Extract fingerprint (Place Fingerprint) │
│ │ │
│ ├──▶ Submit fingerprint ──▶ +10 Influence │
│ │ │
│ └──▶ Encounter Synthling (procedural creature) │
│ │ │
│ ▼ │
│ Capture ──▶ +5 Influence + Add to Collection │
│ │
│ [Passive] Influence decays hourly (48h half-life) │
│ [Async] Raid rival outposts │
│ [Goal] Control districts, evolve Synthlings │
└─────────────────────────────────────────────────────────────────┘
The Place Fingerprint is the core technical innovation. It is a compact, privacy-preserving feature vector (under 400 bytes serialized) extracted entirely on-device from camera frames, ambient audio, motion sensors, and GPS locality. The fingerprint contains five descriptors:
| Descriptor | Size | Source | Contents |
|---|---|---|---|
| Visual Palette | ~80 bytes | Camera frame | 5-7 dominant colors with weights, overall brightness, saturation |
| Geometry | ~64 bytes | Scene understanding | Edge orientation histogram (8 buckets), surface type distribution (sky, vegetation, building, ground, water, road), vertical bias, complexity score |
| Motion | ~16 bytes | Accelerometer | Motion level, dominant direction, periodicity |
| Audio | ~48 bytes | Microphone | Spectral centroid, harmonic ratio, rhythm density, loudness, dominant frequency band |
| Locality | ~32 bytes | GPS + Clock | H3 cell index (resolution 7), time-of-day bucket, day type (weekday/weekend), season hint |
Raw capture inputs (pixel data, audio samples, precise coordinates) never leave the device. Only the extracted fingerprint vector is transmitted to the server.
The territory layer uses Uber’s H3 hexagonal grid system:
Players deploy outposts (one per cell) to project persistent influence. Each outpost supports up to four module types:
| Module | Effect | Max Level |
|---|---|---|
| Scanner | Increases Synthling spawn rate in the cell | 3 |
| Amplifier | Multiplies passive influence generation (0.25x per level) | 3 |
| Shield | Reduces incoming raid damage (5 defense per level) | 3 |
| Beacon | Attracts crew members (social signal) | 3 |
Outposts have health (0-100) and level (1-5). They generate influence passively via hourly ticks processed by a server-side stored function.
Raids are the primary conflict mechanic. They are cell-targeted (not player-targeted) and currently resolve immediately (asynchronous job-queue resolution planned for production):
Synthlings are procedurally generated creatures whose attributes derive from Place Fingerprints:
| Attribute | Source | Types |
|---|---|---|
| Palette | Visual fingerprint colors | RGB arrays mapped to skin/energy tones |
| Geometry | Edge histogram, surface distribution | Crystalline, Organic, Geometric, Fluid, Fractal |
| Motion | Motion descriptor | Float, Pulse, Spiral, Bounce, Swarm |
| Sound | Audio descriptor | Ambient, Melodic, Percussive, Harmonic, Noise |
| Rarity | Composite fingerprint rarity score | Common, Uncommon, Rare, Epic, Legendary |
Evolution requires visiting distinct micro-biomes (three different environment signatures within a district), coupling real-world exploration to creature progression.
Context-aware short missions available per district:
| Type | Objective | Typical Reward |
|---|---|---|
| Capture | Capture specific Synthlings | 50 influence |
| Survey | Submit fingerprints in target area | 50 influence |
| Patrol | Visit multiple cells in sequence | 50 influence |
| Raid | Execute a successful raid | Variable |
| Defend | Successfully defend against a raid | Variable |
Contracts expire after 24 hours and are generated daily via the generate_district_contracts stored function.
Crews are 6-30 player factions identified by name, 3-5 character tag, and hex color. Crew-level progression unlocks district benefits (faster influence gain, better defense, cosmetic district themes). The “Heat” mechanic tracks rival attention: high heat yields higher rewards but makes holding turf harder.
POST /api/v1/location/validate
Content-Type: application/json
{
"userId": "uuid",
"sessionId": "uuid",
"latitude": 37.7749,
"longitude": -122.4194,
"accuracy": 10,
"timestamp": "2026-01-15T10:30:00Z",
"platform": "ios"
}
Response includes validation result code (valid, blocked_exclusion_zone, blocked_speed_lockout, blocked_spoof_detected, blocked_rate_limit, error), the resolved H3 cell index, and detailed check results for zone, speed, and spoof analysis.
POST /api/v1/fingerprint/submit
Content-Type: application/json
{
"h3Cell": "89283082813ffff",
"colorPalette": [{"r": 120, "g": 85, "b": 200}],
"dominantColor": {"r": 120, "g": 85, "b": 200},
"brightness": 0.65,
"colorTemperature": 5600,
"planeCount": 4,
"audioFeatures": {
"ambientLevel": 0.4,
"frequency": 440,
"complexity": 0.3
},
"motionSignature": {
"rotationX": 0.1,
"rotationY": 0.02,
"rotationZ": -0.05,
"accelerationMagnitude": 1.02
}
}
GET /api/v1/turf/cell/:h3Index # Get cell territory status
GET /api/v1/turf/district/:districtId/leaderboard # District rankings
POST /api/v1/turf/raid # Initiate a raid
See shared/api-types.ts for complete TypeScript type definitions covering all request/response shapes, including outpost deployment, module installation, Synthling spawning and capture, and error responses.
my-block-warfare/
├── src/ # Backend source (TypeScript)
│ ├── server.ts # Fastify entry point
│ ├── config/ # Environment configuration
│ ├── api/v1/ # REST route handlers
│ │ ├── location.ts # Geofencing endpoints
│ │ ├── fingerprint.ts # Fingerprint endpoints
│ │ └── turf.ts # Territory endpoints
│ ├── services/ # Domain services
│ │ ├── geofencing/ # Safety validation pipeline
│ │ │ ├── index.ts # GeofencingService orchestrator
│ │ │ ├── zone-checker.ts # Exclusion zone lookup
│ │ │ ├── speed-validator.ts # Vehicle speed detection
│ │ │ ├── spoof-detector.ts # GPS manipulation analysis
│ │ │ ├── h3-cache.ts # H3-to-zone cache layer
│ │ │ └── zone-sync.ts # External zone data sync
│ │ ├── fingerprint/ # Place Fingerprint processing
│ │ │ ├── index.ts # FingerprintService
│ │ │ ├── capture-manager.ts # Capture coordination
│ │ │ ├── color-extractor.ts # Palette extraction
│ │ │ ├── visual-pipeline.ts # Visual feature pipeline
│ │ │ ├── audio-pipeline.ts # Audio feature pipeline
│ │ │ ├── assembler.ts # Fingerprint assembly + similarity
│ │ │ └── validation-gate.ts # Submission validation
│ │ └── turf/ # Territory mechanics
│ │ ├── index.ts # TurfService
│ │ ├── influence-manager.ts # Influence scoring + decay
│ │ ├── outpost-manager.ts # Outpost CRUD + ticks
│ │ └── raid-engine.ts # Raid initiation + resolution
│ ├── db/ # Database layer
│ │ ├── connection.ts # PostgreSQL pool
│ │ ├── redis.ts # Redis client
│ │ └── migrations/ # SQL schema migrations
│ │ ├── 001_geofencing_schema.sql
│ │ ├── 002_fingerprint_schema.sql
│ │ └── 003_turf_mechanics_schema.sql
│ ├── types/ # TypeScript type definitions
│ │ ├── geofencing.ts
│ │ ├── fingerprint.ts
│ │ ├── turf.ts
│ │ ├── synthling.ts
│ │ └── index.ts
│ ├── utils/ # Shared utilities
│ │ └── logger.ts # Pino logger factory
│ └── __tests__/ # Test suite
│ ├── setup.ts
│ └── unit/
│ ├── influence-manager.test.ts
│ ├── raid-engine.test.ts
│ └── zone-checker.test.ts
├── shared/ # Cross-platform API contract
│ └── api-types.ts # TypeScript types (source of truth)
├── unity/ # Unity AR client
│ ├── Assets/Scripts/
│ │ ├── AR/ARSessionManager.cs
│ │ ├── Fingerprint/FingerprintCapture.cs
│ │ └── Networking/
│ │ ├── ApiClient.cs
│ │ └── LocationService.cs
│ └── README.md
├── mcp-maps-3d/ # Gemini + MCP 3D map prototype
├── spatial-understanding/ # Gemini vision spatial detector
├── specs/ # Feature specifications (speckit)
│ ├── safety-geofencing/
│ ├── place-fingerprint/
│ ├── synthling-generation/
│ └── turf-mechanics/
├── docs/
│ ├── evaluation/ # Project evaluation reports
│ ├── roadmap/ # Execution roadmap
│ └── runbook/ # Operations runbook
├── memory/
│ └── constitution.md # Immutable architectural principles
├── TurfSynth-AR-Concept.md # Master product specification
├── CLAUDE.md # AI assistant context
├── .github/workflows/ci.yml # CI pipeline
├── .env.example # Environment template
├── package.json # Node.js manifest
├── tsconfig.json # TypeScript configuration
├── vitest.config.ts # Test runner configuration
└── eslint.config.js # ESLint flat config
| Decision | Choice | Rationale |
|---|---|---|
| Spatial indexing | H3 (Uber) | Consistent hexagonal cells with no shape distortion at edges, efficient gridDisk neighbor queries, deterministic cell IDs from coordinates |
| Database | PostgreSQL 16 + PostGIS 3.4 | Mature geospatial operators, JSONB for flexible per-cell influence maps, table partitioning for audit log retention |
| Cache/real-time | Redis 7 | Pub/sub for live updates, sorted sets for leaderboards, key expiry for speed lockouts, sub-millisecond lookups for hot-path geofence data |
| API framework | Fastify 5 | Schema-validated routes, plugin architecture, structured JSON logging via Pino, built-in rate limiting |
| AR client | Unity 2022.3 LTS + AR Foundation | Cross-platform ARKit/ARCore, C# type generation from shared TypeScript contract via quicktype |
| Schema validation | Zod | Runtime request validation with TypeScript type inference, composable schemas |
| Test runner | Vitest | Native ESM support, fast watch mode, Vite-aligned configuration |
| Audit log partitioning | Monthly PostgreSQL partitions | Efficient retention management (6-month policy), partition-level DROP instead of row-level DELETE |
Privacy and safety are constitutional constraints, not afterthoughts. The project constitution (memory/constitution.md) mandates Safety-Mandatory and Privacy-First as the two highest-priority gates.
The geofencing service performs three checks in order of computational cost (target: <100ms p95 latency):
This project uses the speckit methodology: specifications are truth, code is generated output. Feature specifications live in specs/ and follow a three-artifact structure:
| Artifact | Purpose | Example |
|---|---|---|
spec.md |
Requirements, success criteria, constitution gates | specs/safety-geofencing/spec.md |
plan.md |
Implementation approach, architecture decisions | specs/place-fingerprint/plan.md |
tasks.md |
Executable work items with estimates | specs/turf-mechanics/tasks.md |
| Feature | Status | Engineering Estimate | Constitution Gates |
|---|---|---|---|
| Safety Geofencing | Specified + Implemented | 68h | Safety-Mandatory, Privacy-First |
| Place Fingerprint | Specified + Implemented | 92h | Privacy-First, Mobile-First, Environmental Authenticity |
| Synthling Generation | Specified | 192h (72h eng + 120h art) | Environmental Authenticity, Progressive Disclosure |
| Turf Mechanics | Specified + Implemented | 88h | Safety-Mandatory, Privacy-First |
Safety Geofencing ──────┐
│ │ (constitution priority #1)
▼ │
Place Fingerprint ◄─────┘
│
├──────────────────┐
▼ ▼
Synthling Generation Turf Mechanics
(hard dependency) (soft dependency)
| Command | Description |
|---|---|
npm run dev |
Start development server with hot reload (tsx watch) |
npm run build |
Compile TypeScript to dist/ |
npm run start |
Run compiled production build |
npm run test |
Run test suite (Vitest) |
npm run test:coverage |
Run tests with coverage report |
npm run test:integration |
Run integration tests (requires running database) |
npm run lint |
Check code style (ESLint flat config) |
npm run lint:fix |
Auto-fix lint errors |
npm run format |
Format source with Prettier |
npm run typecheck |
Run TypeScript type checker (tsc --noEmit) |
npm run db:migrate |
Run database migrations |
npm run db:seed |
Seed development data |
The test suite uses Vitest with 59 unit tests covering the three core services:
# Run all tests
npm run test
# Run with coverage
npm run test:coverage
# Run a specific test file
npm run test -- src/__tests__/unit/influence-manager.test.ts
| Test | Covers | Key Scenarios |
|---|---|---|
influence-manager.test.ts |
Influence scoring, decay processing, cell control transitions | Fingerprint influence award, decay half-life, crew influence aggregation |
raid-engine.test.ts |
Raid lifecycle, defense calculation, reward distribution | Successful raid, failed raid, cooldown enforcement, outpost damage |
zone-checker.test.ts |
Exclusion zone lookup, H3 cache behavior | Zone block, zone allowance, cache hit/miss, expired zone handling |
The GitHub Actions workflow (.github/workflows/ci.yml) runs on pushes and pull requests to main and develop:
tsc --noEmit on Ubuntu with Node.js 22Concurrency groups cancel in-progress runs for the same branch.
The concept document includes detailed scaling cost models using an Effort Unit (EU) framework where 1 EU = 1 person-week of productive work.
| Stage | Target Scale | Team Size | Annual People Cost | Monthly Infra |
|---|---|---|---|---|
| S0: MVP | Private alpha, <=10k users | 8-10 FTE | $2.0M-$3.4M | $5k-$25k |
| S1: City Pilot | 1 metro, 50k-200k MAU | 12-18 FTE | $3.5M-$6.1M | $25k-$120k |
| S2: Multi-City | 5-10 metros, 0.5M-2M MAU | 25-40 FTE | $7.8M-$13.5M | $120k-$450k |
| S3: National | US-wide, 2M-10M MAU | 50-80 FTE | $15.6M-$27.0M | $450k-$1.8M |
| S4: Global | Multi-region, 10M-50M MAU | 100-160 FTE | $31.2M-$54.1M | $1.8M-$6.0M |
Infrastructure cost bracket: $0.03-$0.20 per DAU per month (lower end for cached/async architecture, upper end for real-time sync with heavy anti-cheat).
This repository lives within ORGAN-III (Ergon), the commerce organ of the organvm eight-organ system. ORGAN-III houses SaaS, B2B, and B2C product repositories – the applied, revenue-capable outputs of the broader creative-institutional project.
TurfSynth AR draws on work from adjacent organs:
| Organ | Relationship |
|---|---|
| ORGAN-I (Theoria) | Theoretical foundations: the recursive-engine provides the recursive self-reference patterns that inform the fingerprint similarity calculus and the influence decay model |
| ORGAN-II (Poiesis) | Creative precedents: the metasystem-master project’s generative art pipelines inform the Synthling visual synthesis approach |
| ORGAN-IV (Taxis) | Orchestration: the agentic-titan agent framework may coordinate future CI/CD and deployment automation for TurfSynth |
| ORGAN-V (Logos) | Public process: development decisions and design rationale will be documented as essays in the public-process repository |
The dependency direction follows the organ system invariant: I -> II -> III only. ORGAN-III consumes theory and art but never introduces back-edges.
shared/api-types.ts)git checkout -b feature/amazing-feature)npm run test)npm run lint && npm run typecheck)git commit -m 'Add amazing feature')git push origin feature/amazing-feature)All contributions must comply with the project constitution (memory/constitution.md), particularly the Safety-Mandatory and Privacy-First gates.
MIT
@4444j99 – github.com/4444J99
Part of the ORGAN-III: Ergon commerce organ within the organvm eight-organ system.