# W3

Week 3. Integrating System (API, Sound, Mobile, Unreal)

## 1. API: Introduction

- What is API?
  - An application programming interface is a connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software. - Wikipedia
- Various types of APIs
  - Weather, news, maps, public data
  - OpenAI API, Anthropic API (Claude)
  - Replicate API
  - Microsoft Azure/AWS/Google Cloud
- Integration with Next.js
  - App Router: Route Handlers [LINK](https://nextjs.org/docs/app/building-your-application/routing/route-handlers)
    - What is a Route Handler: Create Server-side logic directly in your Next.js without having to create a separate Backend Server
    - `app/api/<name>/route.ts` → `fetch("/api/<name>")` from your page
    - Runs on the server. Your API key never reaches the browser
    - Route Handlers DO deploy to Vercel (unlike the socket relay)

## 2. Using an API

**Free APIs**

| API | Data | Key |
| --- | --- | --- |
| [Open-Meteo](https://open-meteo.com/) | Weather, air quality | No key |
| [USGS Earthquakes](https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php) | Earthquakes of the last hour / day / week | No key |
| [New York Times](https://developer.nytimes.com/) | News: top stories, article search | Free key |
| [NASA](https://api.nasa.gov/) | Space images and data | Free key |
| [공공데이터포털](https://www.data.go.kr/) | Korean public data | Free key |

**Without a key**: call it from the page with `fetch`

```tsx
const response = await fetch(
  "https://api.open-meteo.com/v1/forecast?latitude=36.37&longitude=127.36&current=temperature_2m,wind_speed_10m",
);
const data = await response.json();
console.log(data.current.temperature_2m, data.current.wind_speed_10m);
```

**With a key**: call it from a Route Handler

- Step 1. Register and create an API Key
  - New York Times: https://developer.nytimes.com/
- Step 2. Store your API Key in `.env.local`: `NYT_API_KEY=...`
  - What is `.env.local`? Environment variables, read only on the server
  - Do NOT prefix it with `NEXT_PUBLIC_`. Anything with that prefix is shipped to the browser, i.e. public
- Step 3. Check `.gitignore`: `.env*` is already there. Your key must never be committed
- Step 4. Write the API code in a Route Handler: `app/api/<name>/route.ts`. Read the key with `process.env.NYT_API_KEY`
- Step 5. On the frontend, call this Route Handler via fetch

**API examples** ([/experiments/w3](/experiments/w3))

1. Weather → wind field (no key): [api/weather](/experiments/w3/api/weather)
2. NYT headlines (key, Route Handler): [api/nyt-headlines](/experiments/w3/api/nyt-headlines) → `app/api/nyt-headlines/route.ts`

**LLM API**

- LLM APIs (OpenAI, Anthropic) are used the same way: key in `.env.local`, call from a Route Handler
  - OpenAI: https://platform.openai.com/docs/overview
  - Anthropic: https://platform.claude.com/docs
- SoTA (2024): GPT-4o writes what the AI avatar docent says. When the visitor leaves: GPT-4o API → Embeddings API → token embedding cross-similarity matrix → lines

## 3. Sound: Tone.js

- Web Audio API: the browser's audio engine. Oscillators, samples, effects, analysis (volume, FFT)
- Tone.js: Javascript library on top of Web Audio, musician-friendly (Synths, Transport, Effects) [LINK](https://tonejs.github.io/)
- Already installed in the template: `tone`
- Rules
  - Audio starts only after a user gesture (tap/click): `await Tone.start()` inside an event handler
  - Microphone input requires HTTPS (see [W2 A2](/lecture-materials/w2#a2-https-for-local-dev-pnpm-devmobile))

```tsx
import * as Tone from "tone";

async function play() {
  await Tone.start();
  const synth = new Tone.Synth().toDestination();
  synth.triggerAttackRelease("C4", "8n");
}
```

**Ways to make sound**

1. Synthesis: `Tone.Synth`, `Tone.FatOscillator`, `Tone.NoiseSynth`. Parameters → frequency, volume
2. Samples: recorded files in `public/`, played with `Tone.Player` / `Tone.Sampler`
3. Sequencing: `Tone.Transport`, `Tone.Loop`. Tempo as a parameter
4. Effects: `Tone.Filter`, `Tone.Reverb`, `Tone.Distortion`, `Tone.FeedbackDelay` between the source and the speakers
5. Microphone as input: `Tone.UserMedia` + `Tone.Meter` / `Tone.FFT`
6. Speech: the browser's `speechSynthesis`, or a TTS API through a Route Handler

**Sound examples**

1. Tone Pad: pointer → pitch, filter: [sound/tone-pad](/experiments/w3/sound/tone-pad)
2. Data → sound (drone, wind, heartbeat, impacts): [w1/snp](/experiments/w1/snp) → `sound.ts`
3. Microphone → parameter: [w1/video](/experiments/w1/video)

## 4. Unreal

- A mobile can control Unreal Engine too, not only a web page. The path is the same as in W2: mobile → relay → output. Here the output is Unreal instead of a browser
- Example repo: https://github.com/jeanyoon-choi/mobile-to-unreal-realtime-backbone
- What it does: drag a finger on the mobile, and a sphere in Unreal follows it
  1. The mobile opens a web page with an XY pad
  2. While the finger drags, the page sends its position (`x`, `y`) and `pressure` to the relay over WebSocket, 25 times a second
  3. The relay (Node.js) keeps only the newest position and passes it on to Unreal, 30 times a second
  4. In Unreal, one C++ actor receives it and moves the sphere
- What is different from our relay: a browser can receive Socket.io messages, Unreal cannot. So the relay sends the last step over UDP, a simpler way of sending data over a network, which Unreal can receive
- To run it you need Node.js 20 or newer, pnpm 11 and Unreal Engine 5.8
  1. `pnpm install`, then `pnpm dev`. This starts the mobile page (port 3000) and the relay (port 4000)
  2. On the mobile, on the same Wi-Fi, open `http://<YOUR_IP>:3000`
  3. Open `unreal/MobileToUnrealBackbone/MobileToUnrealBackbone.uproject` in Unreal Engine
  4. Drag on the mobile. The sphere in Unreal moves
- Folders: `apps/mobile/` (the mobile page), `relay/` (the relay), `unreal/` (the Unreal project), `docs/` (how it works, in detail)

## 5. System & Interaction

Examples ([/experiments/w3](/experiments/w3))

1. Fish Food ([mobile](/experiments/w3/system/fish-food/mobile) · [screen](/experiments/w3/system/fish-food/screen))
   - Mobile: tap or slide on the map to drop food or something bitter into the water
   - System: thousands of goldfish, each following the same few rules: stay with the school, go to food, flee from bitter water. Fright passes from fish to fish
   - Screen: the schools gather around the food and scatter from the bitter cloud
2. Cloud Field ([mobile](/experiments/w3/system/cloud-field/mobile) · [screen](/experiments/w3/system/cloud-field/screen))
   - Mobile: drag on a map to choose a place in the sky, and set two sliders: pressure and heat
   - System: each mobile is a centre of pressure. Low pressure gathers cloud, high pressure clears it. All mobiles are added up at every pixel
   - Screen: one slow sky of clouds, with sound. Each mobile is one voice
3. City Walk ([mobile](/experiments/w3/system/city-walk/mobile) · [screen](/experiments/w3/system/city-walk/screen))
   - Mobile: drag to walk and turn through Shibuya crossing, seen in first person
   - System: every device builds the same city from the same map data. Each mobile sends where it is, 15 times a second
   - Screen: the whole city from above, with a beam of light on every walker

## Appendix. Projection Mapping

- The 1st-floor gallery (Black Room) has two projectors, one for each wall
- The picture a projector throws is larger than the wall. Only a part of it lands on the wall
  - Left wall: 1920 × 602 of the picture. Right wall: 1675 × 602

- So a page that fills the whole screen does not fit the wall: part of it falls outside. Projection mapping is placing your content exactly on the wall
- How, in the browser
  1. Make the whole page black. Black means the projector sends no light there, so it cannot be seen
  2. Put one box on the page, and put all of your content inside the box
  3. In the room, move and resize the box until its four edges meet the edges of the wall
- Example: projection-mapping ([left](/experiments/w3/projection-mapping?side=left) · [right](/experiments/w3/projection-mapping?side=right)) → `app/experiments/w3/projection-mapping/`
  - One laptop per projector. Open `?side=left` on one and `?side=right` on the other
  - Four sliders move the box: top, left, width, height. When it fits, write the four numbers into `FRAMES` at the top of `MappingFrame.tsx`, then press hide
  - `Content.tsx` is your content. Give it the size of the box (`100%`), not of the whole window (`100vw` / `100vh`)
- Reference: https://github.com/jeanyoon-choi/xdlab-mapping