{"id":50553831,"url":"https://github.com/orbitalfoundation/terratwin","last_synced_at":"2026-06-04T05:04:50.499Z","repository":{"id":362164705,"uuid":"1058950504","full_name":"orbitalfoundation/terratwin","owner":"orbitalfoundation","description":"While there are many academic models and simulations, the goal here is to provide 'civic models' that a farmer might actually use themselves - both as a predictive tool but also as a communication tool for sponsorship and support.","archived":false,"fork":false,"pushed_at":"2026-06-02T23:11:43.000Z","size":4026,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-06-03T01:05:55.721Z","etag":null,"topics":["simulation"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/orbitalfoundation.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-09-17T19:18:00.000Z","updated_at":"2026-06-02T23:11:46.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/orbitalfoundation/terratwin","commit_stats":null,"previous_names":["orbitalfoundation/terratwin"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/orbitalfoundation/terratwin","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/orbitalfoundation%2Fterratwin","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/orbitalfoundation%2Fterratwin/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/orbitalfoundation%2Fterratwin/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/orbitalfoundation%2Fterratwin/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/orbitalfoundation","download_url":"https://codeload.github.com/orbitalfoundation/terratwin/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/orbitalfoundation%2Fterratwin/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33890052,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-04T02:00:06.755Z","response_time":64,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["simulation"],"created_at":"2026-06-04T05:04:48.736Z","updated_at":"2026-06-04T05:04:50.492Z","avatar_url":"https://github.com/orbitalfoundation.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# TerraTwin\n\n![TerraTwin](terratwin.png)\n\n**[Live demo →](https://orbitalfoundation.github.io/terratwin/)**\n\n*A civic simulation and visualization platform for bamboo agroforestry leveraging Orbital*\n\n---\n\n## What Was Built\n\nTerraTwin is a browser-based application with four technically interesting components. This document covers both the engineering and the product reasoning behind it.\n\n### 1. A navigable 3D tile map engine\n\nThe NASA/Cesium tile renderer ([3d-tiles-renderer](https://github.com/NASA-AMAC/3DTilesRendererJS)) is a powerful library but ships without user navigation controls. This project adds a full control layer: **OrbitControls** for close-in ground-level views of individual plots, and **GlobeControls** for planetary-scale orbiting — with properly configured near/far clip planes, distance clamping, and damping so the transition between zoom levels feels natural rather than jittery. Getting the camera math right across twelve orders of magnitude of scale (from a 500m plot boundary up to a 160,000km orbital view) required careful tuning of the projection parameters.\n\nThe result is a globe you can fly around, zoom smoothly into a specific hillside in Mindanao, and then inspect individual bamboo plot locations as georeferenced markers in a satellite terrain context.\n\n### 2. Shader-based terrain carving\n\nA more unusual feature: the map can be configured to **clip the terrain to an arbitrary polygon**, rendering only the tiles inside a user-defined boundary and discarding everything outside it. This is done entirely in the GPU via a custom GLSL fragment shader that performs a ray-casting point-in-polygon test in world space:\n\n```glsl\nbool isPointInPolygon(vec2 p) {\n  bool inside = false;\n  for (int i = 0, j = numPoints - 1; i \u003c numPoints; j = i++) {\n    vec2 pi = boundaryPoints[i];\n    vec2 pj = boundaryPoints[j];\n    if ((pi.y \u003e p.y) != (pj.y \u003e p.y) \u0026\u0026\n        p.x \u003c (pj.x - pi.x) * (p.y - pi.y) / (pj.y - pi.y) + pi.x)\n      inside = !inside;\n  }\n  return inside;\n}\n```\n\nTiles outside the polygon are discarded at the fragment stage. The boundary points are passed in as a uniform array. The effect is that any arbitrary parcel of the Earth can be carved out on demand, showing real DEM terrain and satellite imagery, with clean edges at the boundary walls.\n\nThis technique descends from an earlier project, [aterrain](https://github.com/anselm/aterrain), which explored on-demand terrain carving for WebGL. That work was covered in [Mozilla Hacks](https://hacks.mozilla.org) and demonstrated that it was possible to take an arbitrary geographic region, pull the elevation and imagery tiles, and render it as a self-contained 3D object inside a browser.\n\n### 3. An agent-based crop growth simulation\n\nThe simulation core uses [Orbital Foundation](https://orbital.foundation), a framework for agent-based environmental modeling. The bamboo growth model runs at one simulation step per day over a 20-year horizon and incorporates:\n\n- Soil conditions (nitrogen, microbial mass, earthworm density, salinity, pH, fertility)\n- Climate variables (rainfall, elevation, slope and aspect)\n- Pest load (bamboo borer, aphids, fungal pathogens)\n- Intervention choices (weeding, mulching, fertilization, pest control)\n- Intercropping strategies (legumes, herbs, specialty crops, animals)\n- Harvest schedule (years to first harvest, annual harvest rate)\n\nThe output tracks biomass accumulation, carbon sequestration, harvest yield, economic return, and ecosystem health indicators over the full simulation period. The model is designed to be sensitive to the combinations of variables in ways a spreadsheet formula would miss — soil feedback loops, the compounding benefit of legume intercropping on nitrogen over multi-year cycles, the interaction between pest load and intervention timing.\n\n### 4. Conversational and narrative interfaces\n\nThere is a broader shift happening in how people interact with complex software, and it matters particularly for tools aimed at non-technical users. Traditional GIS and agricultural modeling tools require training, expertise, and patience. The emergence of capable language models changes the calculus: a farmer in Mindanao who has never opened a spreadsheet can now ask a question in plain language and get a useful answer about their plot.\n\nTerraTwin leans into this in two ways.\n\nThe **AI chat interface** lets users ask questions about their plots, get agronomic guidance, and trigger navigation actions conversationally — \"show me the Bukidnon plot\" or \"start the simulation.\" The assistant understands the current page context and the available plots, so responses are grounded rather than generic. In server mode this uses GPT; in local/static mode it routes to the Groq API (Llama 3) directly from the browser, with no server required. The principle is meeting people where they are: the interface adapts to the user rather than requiring the user to adapt to the interface.\n\nThe **story mode** takes this further for presentation contexts. Rather than handing a stakeholder a dashboard and hoping they can orient themselves, the app narrates its own walkthrough — advancing through pages, scrolling to relevant components, and speaking each caption aloud. In local mode this uses the browser's built-in `speechSynthesis` API; in server mode it uses OpenAI TTS for higher-quality voice. A farmer cooperative can show this to a development bank or carbon registry without needing a technical presenter in the room.\n\nThe broader point is that the value of a modeling tool is not in its computational sophistication but in whether the right people can act on its output. AI-powered interfaces lower the floor dramatically — making it possible to build tools that are genuinely usable by the farmers, tribal leaders, city councils, and regional cooperatives who need them most, rather than only by the consultants they hire.\n\n---\n\n## Product Context\n\n### Earth modeling as an emerging discipline\n\nWe are at an early point in the development of what might be called **earth modeling** — the capability to build predictive simulations of bioregional systems. The infrastructure for this is beginning to materialize:\n\n- **Data**: A generation of Earth observing satellites has produced extraordinary freely available datasets — MODIS spectral imagery, USGS elevation data, EUMETSAT weather simulations, gravity maps from GOCE, reef coverage from Allen Coral Atlas, biome maps from OneEarth. The raw material exists.\n\n- **Semantic extraction**: Deep learning models are now being applied to satellite imagery for feature detection — identifying road incursions into protected forest, mapping crop coverage, detecting water turbidity changes. See for example [Earth Index](https://www.earthgenome.org/earth-index).\n\n- **Gaps**: What's still missing is coherent multi-layer simulation (most models address one phenomenon at a time), temporal relationship discovery across system layers, and accessible tooling for non-expert stakeholders. A city council or farmer cooperative wanting to evaluate a policy option — say, changing buffer zones between farms and a local river — typically can't run that scenario themselves.\n\n### The verification problem\n\nThe commercialization of ecological work runs through MRV: Measurement, Reporting, and Verification. Buyers of carbon credits, biodiversity credits, or the emerging class of **resilience credits** want verified evidence of impact over time. Organizations like [NatureMetrics](https://www.naturemetrics.com/), [the Science Based Targets Network](https://sciencebasedtargetsnetwork.org/), [the NatureTech Collective](https://www.naturetechcollective.org/), and [Earthly](https://earthly.org/) are building the plumbing for this.\n\nThe framing of \"resilience credits\" is worth unpacking. Conventional ecological valuation rewards *preservation of what exists* — don't cut the trees, don't drain the wetland. A more useful frame, argued by practitioners including Ben Ceverny, is to reward *preservation of the capacity to change*. Natural systems are not static; they have always changed. What matters for long-term ecosystem health is maintaining the adaptive capacity — the redundancy, the genetic diversity, the functional variety — that allows ecosystems to recover from shocks. A framework that rewards resilience rather than stasis leads to better incentives.\n\nBamboo farming sits at an interesting edge of this. Commercial *Dendrocalamus asper* monocultures are straightforwardly a carbon and timber play — they don't qualify for biodiversity or resilience credits. But protecting *native bamboo forests*, where bamboo is part of a diverse ecosystem, is a different matter. TerraTwin doesn't conflate these; the current tool addresses commercial agroforestry economics.\n\n### Why bamboo\n\nCompared to timber trees: bamboo reaches harvestable maturity in three to five years rather than twenty to thirty. It regenerates from the root system after harvest without replanting. Per-hectare carbon sequestration is competitive with fast-growing hardwoods. The harvesting is labor-intensive, which creates rural employment in communities where alternatives are scarce. The applications — construction materials, textiles, bamboo shoots, bioenergy, composites — span multiple markets.\n\nThe carbon math for a bamboo farm is also simpler to verify than native forest restoration, which makes it more tractable for smallholders entering credit markets for the first time.\n\n### What exists, what's planned\n\n**Today:** A demonstration and forecasting tool. Farmers register plots, set parameters, run growth simulations, and share a visual presentation with funders or cooperatives. The static demo runs entirely in the browser with no server required; a PostgreSQL backend exists for production use.\n\n**Near term:** Real data integration — automatic parameter estimation from regional satellite/DEM sources, MRV-compatible export formats for credit registry submission.\n\n**Later:** Early tokenization of carbon credits at planting time based on forecast yield, with periodic reissuance tied to verified measurements. A ledger suited to conditional logic — releasing the next credit tranche when a verified biomass threshold is met — is more tractable with an intent-based system like [Anoma](https://anoma.net/) than with conventional smart contracts.\n\n**Eventually:** Portfolio aggregation for regional cooperatives managing dozens of smallholder plots — aggregate risk modeling, consolidated MRV reporting, and the full digital twin loop where the simulation is continuously updated from field sensor data.\n\n---\n\n## Running\n\n### Static demo (no server required)\n\n```bash\nnpm install\nnpm run dev:local\n```\n\nThe globe requires a free [Cesium ion](https://ion.cesium.com) access token:\n\n```\necho \"VITE_CESIUM_KEY=your_token_here\" \u003e .env.local\nnpm run dev:local\n```\n\nThe AI chat works in demo mode without a key; for live responses paste a free [Groq API key](https://console.groq.com) into the key icon in the chat header.\n\n### Server mode (with database, OpenAI TTS, and persistent storage)\n\n```bash\nexport DATABASE_URL=\"postgresql://...\"\nexport OPENAI_API_KEY=\"sk-...\"\nexport CESIUM_KEY=\"...\"\nnpm run dev\n```\n\n### GitHub Pages\n\nPush to `main`. The workflow in [.github/workflows/deploy-pages.yml](.github/workflows/deploy-pages.yml) builds the static bundle and deploys automatically. Add `VITE_CESIUM_KEY` as a repository secret to enable the map on the live demo.\n\n---\n\n## Stack\n\n- **Frontend**: React 18, TypeScript, Vite, Tailwind CSS, shadcn/ui, TanStack Query, Wouter\n- **3D/Map**: Three.js, 3D Tiles Renderer, Cesium ion, NASA/USGS tile sources\n- **Shader pipeline**: Custom GLSL polygon-clipping shaders for terrain carving\n- **Simulation**: [Orbital Foundation](https://orbital.foundation) (agent-based environmental modeling)\n- **Backend** (optional): Express, PostgreSQL via Neon, Drizzle ORM\n- **AI** (optional): OpenAI GPT + TTS (server mode) / Groq Llama + Web Speech API (browser mode)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Forbitalfoundation%2Fterratwin","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Forbitalfoundation%2Fterratwin","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Forbitalfoundation%2Fterratwin/lists"}